views.py 827 Bytes
Newer Older
Sharad Heft's avatar
Sharad Heft committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
from django.shortcuts import redirect
from django.contrib import auth
from django.views.decorators.cache import never_cache

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)
    return redirect("/")


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

    session = TESTOAuth2Session(token=token)

    auth.login(request, auth.authenticate(**session.profile))

    return redirect('/')