Source

Ochs / lib / auth_backends.py

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model
from django.contrib.auth.models import User

from staff.models import Profile

class ProfileModelBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}
        try:
            user = Profile.objects.get(**kwargs)
            if user.check_password(password):
                return user
        except Profile.DoesNotExist:
            try:
                user = User.objects.get(**kwargs)
                if user.is_superuser:
                    return user
                else:
                    return None
            except User.DoesNotExist:
                return None

    def get_user(self, user_id):
        try:
            return Profile.objects.get(pk=user_id)
        except Profile.DoesNotExist:
            try:
                user = User.objects.get(pk=user_id)
                if user.is_superuser:
                    return user
                else:
                    return None
            except User.DoesNotExist:
                return None