django-publicauth / openauth /

from django.utils.translation import ugettext as _
from django.shortcuts import redirect
from django.http import Http404
from django.contrib import auth 

from annoying.decorators import render_to

from openauth.utils import str_to_class, get_backend
from openauth import settings

def logout(request):
    request.flash['success'] = _('You have been logged out')
    return redirect("/")

def social_login(request, provider=None):
    Display authentication form. This is also the first step
    in social registration. The actual login is in social_complete 
    function below.
    if provider:
        # merge data from POST and GET methods
        data = request.GET.copy()

        request.session['next_url'] = request.GET.get("next") or settings.LOGIN_REDIRECT_URL
        # start the authentication process 
        backend = get_backend(provider)
        backend.begin(request, data)

    return {}

def social_complete(request, provider):
    Complete SocialID authorization process.
    If SocialID was successfuly authenticated:
     * if no user with such ID exists and current user is authenticated then
       assign SocialID to this user.
     * if user with such ID exists and current user is anonimouse then login 
       as this user.
     * if no user with such ID exists and user must fill extra fields, 
       redirect him to registration form.
    backend = get_backend(provider)
    response = backend.validate_response(request)
    if request.user.is_authenticated():
        backend.attach_account(request, request.user)
        if not settings.REGISTRATION_ALLOWED:
            request.flash['warning'] =  openauth.lang.REGISTRATION_DISABLED
            return redirect(settings.REGISTRATION_DISABLED_REDIRECT)
    backend.complete(request, response)

def social_extra(request, provider):
    Handle registration of new user with extra data for profile
        identity = request.session['identity']
    except KeyError:
        raise Http404

    if request.method == "POST":
        form = str_to_class(settings.SOCIALID_EXTRA_FORM)(request.POST)
        if form.is_valid():
            user =, provider)
            del request.session['identity']
            user = auth.authenticate(identity=identity, provider=provider)
            if user:
                auth.login(request, user)
                next_url = request.session['next_url']
                del request.session['next_url']
                return redirect(next_url)
        initial = request.session['extra']
        form = str_to_class(settings.SOCIALID_EXTRA_FORM)(initial=initial)

    return {'form': form}