'''
Created on 2010/05/15

@author: katsuhiro
'''
from django.contrib.auth import backends as django_backends
from djanction.appauth.models import User

"""
Override django.contrib.auth.backends
Only the model class that refers is different.
"""
class ModelBackend(django_backends.ModelBackend):

    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(username=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


class RemoteUserBackend(django_backends.RemoteUserBackend):

    def authenticate(self, remote_user):
        if not remote_user:
            return
        user = None
        username = self.clean_username(remote_user)

        if self.create_unknown_user:
            user, created = User.objects.get_or_create(username=username)
            if created:
                user = self.configure_user(user)
        else:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                pass
        return user

