django-acl / acl /

from django.contrib import auth
from django.contrib.auth.models import User

def _anonymous_patch():
    This patch is needed in order to make the has_perm method available on the
    anonymous user too. It creates an new inactive user with the username
    "anonymous", then it replaces the django.contrib.auth.models.AnonymousUser
    with a patched version of this new user.
    if not hasattr(_anonymous_patch, 'user'):
        anon = User.objects.get_or_create(username='anonymous')[0]
        anon.is_anonymous = lambda: True
        anon.is_authenticated = lambda: False

        def anon_has_perm(perm):
            # skip the "is_active" check.
            for backend in auth.get_backends():
                if hasattr(backend, "has_perm"):
                    if backend.has_perm(anon, perm):
                        return True
            return False

        anon.has_perm = anon_has_perm
        _anonymous_patch.user = anon
    return _anonymous_patch.user

auth.models.AnonymousUser = _anonymous_patch