| | 166 | |
|---|
| | 167 | def authenhandler(req, **kwargs): |
|---|
| | 168 | """ |
|---|
| | 169 | Authentication handler that checks against Django's auth database. |
|---|
| | 170 | """ |
|---|
| | 171 | from mod_python import apache |
|---|
| | 172 | |
|---|
| | 173 | # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes |
|---|
| | 174 | # that so that the following import works |
|---|
| | 175 | os.environ.update(req.subprocess_env) |
|---|
| | 176 | from django.models.auth import users |
|---|
| | 177 | |
|---|
| | 178 | # check for PythonOptions |
|---|
| | 179 | _str_to_bool = lambda s: s.lower() in '1', 'true', 'on', 'yes' |
|---|
| | 180 | |
|---|
| | 181 | options = req.get_options() |
|---|
| | 182 | permission_name = options.get('DjangoPermissionName', None) |
|---|
| | 183 | staff_only = _str_to_bool(options.get('DjangoRequireStaffStatus', "on")) |
|---|
| | 184 | superuser_only = _str_to_bool(options.get('DjangoRequireSuperuserStatus', "off")) |
|---|
| | 185 | |
|---|
| | 186 | # check that the username is valid |
|---|
| | 187 | kwargs = {'username__exact': req.user, 'is_active__exact': True} |
|---|
| | 188 | if staff_only: |
|---|
| | 189 | kwargs['is_staff__exact'] = True |
|---|
| | 190 | if superuser_only: |
|---|
| | 191 | kwargs['is_superuser__exact'] = True |
|---|
| | 192 | try: |
|---|
| | 193 | user = users.get_object(**kwargs) |
|---|
| | 194 | except users.UserDoesNotExist: |
|---|
| | 195 | return apache.HTTP_UNAUTHORIZED |
|---|
| | 196 | |
|---|
| | 197 | # check the password and any permission given |
|---|
| | 198 | if user.check_password(req.get_basic_auth_pw()): |
|---|
| | 199 | if permission_name: |
|---|
| | 200 | if user.has_perm(permission_name): |
|---|
| | 201 | return apache.OK |
|---|
| | 202 | else: |
|---|
| | 203 | return apache.HTTP_UNAUTHORIZED |
|---|
| | 204 | else: |
|---|
| | 205 | return apache.OK |
|---|
| | 206 | else: |
|---|
| | 207 | return apache.HTTP_UNAUTHORIZED |
|---|
| | 208 | |
|---|