django-publicauth / publicauth /

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

from annoying.decorators import render_to

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

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

def begin(request, provider=None):
    Display authentication form. This is also the first step
    in 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 global_settings.LOGIN_REDIRECT_URL
        # start the authentication process 
        backend = get_backend(provider)
        backend.begin(request, data)

    return {}

def complete(request, provider):
    Complete PublicID authorization process.
    If PublicID was successfuly authenticated:
     * if no user with such ID exists and current user is authenticated then
       assign PublicID 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'] =  publicauth.lang.REGISTRATION_DISABLED
            return redirect(settings.REGISTRATION_DISABLED_REDIRECT)
    backend.complete(request, response)

def 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.PUBLICID_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.PUBLICID_EXTRA_FORM)(initial=initial)

    return {'form': form}