Ticket #2630: backends_custom_auth.diff

File backends_custom_auth.diff, 2.1 KB (added by erob@…, 18 years ago)

here's initial revision -- comments are encouraged!

  • backends.py

     
     1from django.db import models
    12from django.contrib.auth.models import User
    23
     4from django.conf import settings
     5AUTH_MODULE_HINT = settings.AUTH_MODULE_HINT
     6DEBUG = settings.DEBUG
     7
     8
     9def get_auth_module(module_name):
     10    """
     11    Return a user-defined module for authentication.
     12    """
     13    # cls is the last component
     14    tmp = module_name.split('.')
     15    cls = tmp.pop()
     16    if DEBUG: print "Class: ", cls
     17    module_name = ".".join(tmp)
     18    if DEBUG: print "module name: %s" % module_name
     19    mod = __import__(module_name, globals(), locals(), [''])
     20    auth_module = getattr(mod, cls)
     21    return auth_module
     22   
     23
    324class ModelBackend:
    425    """
    526    Authenticate against django.contrib.auth.models.User
     
    728    # TODO: Model, login attribute name and password attribute name should be
    829    # configurable.
    930    def authenticate(self, username=None, password=None):
     31        # get the custom user model
     32        auth_module = get_auth_module(AUTH_MODULE_HINT)
    1033        try:
    11             user = User.objects.get(username=username)
     34            # retrieve the user object
     35            user = auth_module.objects.get(username=username)
     36            # check_password is a method inherited from User
    1237            if user.check_password(password):
    1338                return user
    14         except User.DoesNotExist:
     39        except auth_module.DoesNotExist:
     40            # fallback on the default method
     41            try:
     42                user = User.objects.get(username=username)
     43                if user.check_password(password):
     44                   return user
     45            except User.DoesNotExist:
     46                return None
     47        else:
    1548            return None
    16 
     49           
    1750    def get_user(self, user_id):
    1851        try:
    19             return User.objects.get(pk=user_id)
     52           return User.objects.get(pk=user_id)
    2053        except User.DoesNotExist:
    21             return None
     54           return None
     55
     56   
Back to Top