app/django/contrib/auth/handlers/modpython.py
changeset 54 03e267d67478
equal deleted inserted replaced
53:57b4279d8c4e 54:03e267d67478
       
     1 from mod_python import apache
       
     2 import os
       
     3 
       
     4 def authenhandler(req, **kwargs):
       
     5     """
       
     6     Authentication handler that checks against Django's auth database.
       
     7     """
       
     8 
       
     9     # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes
       
    10     # that so that the following import works
       
    11     os.environ.update(req.subprocess_env)
       
    12 
       
    13     # apache 2.2 requires a call to req.get_basic_auth_pw() before 
       
    14     # req.user and friends are available.
       
    15     req.get_basic_auth_pw()
       
    16 
       
    17     # check for PythonOptions
       
    18     _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes')
       
    19 
       
    20     options = req.get_options()
       
    21     permission_name = options.get('DjangoPermissionName', None)
       
    22     staff_only = _str_to_bool(options.get('DjangoRequireStaffStatus', "on"))
       
    23     superuser_only = _str_to_bool(options.get('DjangoRequireSuperuserStatus', "off"))
       
    24     settings_module = options.get('DJANGO_SETTINGS_MODULE', None)
       
    25     if settings_module:
       
    26         os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
       
    27 
       
    28     from django.contrib.auth.models import User
       
    29     from django import db
       
    30     db.reset_queries()
       
    31 
       
    32     # check that the username is valid
       
    33     kwargs = {'username': req.user, 'is_active': True}
       
    34     if staff_only:
       
    35         kwargs['is_staff'] = True
       
    36     if superuser_only:
       
    37         kwargs['is_superuser'] = True
       
    38     try:
       
    39         try:
       
    40             user = User.objects.get(**kwargs)
       
    41         except User.DoesNotExist:
       
    42             return apache.HTTP_UNAUTHORIZED
       
    43     
       
    44         # check the password and any permission given
       
    45         if user.check_password(req.get_basic_auth_pw()):
       
    46             if permission_name:
       
    47                 if user.has_perm(permission_name):
       
    48                     return apache.OK
       
    49                 else:
       
    50                     return apache.HTTP_UNAUTHORIZED
       
    51             else:
       
    52                 return apache.OK
       
    53         else:
       
    54             return apache.HTTP_UNAUTHORIZED
       
    55     finally:
       
    56         db.connection.close()