views.py 1007 Bytes
Newer Older
Sharad Heft's avatar
Sharad Heft committed
1
from django.shortcuts import redirect
2
from django.contrib import auth, messages
Sharad Heft's avatar
Sharad Heft committed
3
from django.views.decorators.cache import never_cache
4
from django.conf import settings
Sharad Heft's avatar
Sharad Heft committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

from test_oauth.session import TESTOAuth2Session


@never_cache
def login(request, next=None):
    authorization_url, request.session['oauth_state'] = TESTOAuth2Session(
        scope=['read_profile'],
    ).authorization_url()

    return redirect(authorization_url)


@never_cache
def logout(request):
    if request.user.is_authenticated():
        auth.logout(request)
22
    return redirect(getattr(settings, 'TEST_OAUTH_REDIRECT', '/'))
Sharad Heft's avatar
Sharad Heft committed
23 24 25 26 27 28 29 30 31


@never_cache
def callback(request):
    token = (
        TESTOAuth2Session(state=request.session['oauth_state'])
        .fetch_token(code=request.GET['code'])
    )

32 33 34 35 36 37
    user = auth.authenticate(token=token)

    if user is not None:
        auth.login(request, user)
    else:
        messages.error(request, 'Login failed.')
Sharad Heft's avatar
Sharad Heft committed
38

39
    return redirect(getattr(settings, 'TEST_OAUTH_REDIRECT', '/'))