Google AppEngine Django login_required google accounts

Tue Sep 9, 2008

I like to use Google Accounts with App Engine and django. The django login_required decorator depends on the django auth model – so I rewrote it for use with Google Accounts authentication.

I’m not sure if it is better to cache the create_login_url or not, but this works well enough for now.

from django.http import HttpResponseRedirect
from google.appengine.api import users

def login_required(fn):
    """ checks to see if the user is logged in, if not, redirect to login """

    def _dec(view_func):
        def _checklogin(request, *args, **kwargs):
            user = users.get_current_user()
            if user:
                return view_func(request, *args, **kwargs)
                return HttpResponseRedirect(users.create_login_url('/'))
        _checklogin.__doc__ = view_func.__doc__
        _checklogin.__dict__ = view_func.__dict__
        return _checklogin
    return _dec(fn)