| 1 |
from django import db |
| 2 |
from django.contrib import auth |
| 3 |
|
| 4 |
UserModel = auth.get_user_model() |
| 5 |
|
| 6 |
|
| 7 |
def _get_user(username): |
| 8 |
""" |
| 9 |
Return the UserModel instance for `username`. |
| 10 |
|
| 11 |
If no matching user exists, or if the user is inactive, return None, in |
| 12 |
which case the default password hasher is run to mitigate timing attacks. |
| 13 |
""" |
| 14 |
try: |
| 15 |
user = UserModel._default_manager.get_by_natural_key(username) |
| 16 |
except UserModel.DoesNotExist: |
| 17 |
user = None |
| 18 |
else: |
| 19 |
if not user.is_active: |
| 20 |
user = None |
| 21 |
|
| 22 |
if user is None: |
| 23 |
# Run the default password hasher once to reduce the timing difference |
| 24 |
# between existing/active and nonexistent/inactive users (#20760). |
| 25 |
UserModel().set_password("") |
| 26 |
|
| 27 |
return user |
| 28 |
|
| 29 |
|
| 30 |
def check_password(environ, username, password): |
| 31 |
""" |
| 32 |
Authenticate against Django's auth database. |
| 33 |
|
| 34 |
mod_wsgi docs specify None, True, False as return value depending |
| 35 |
on whether the user exists and authenticates. |
| 36 |
|
| 37 |
Return None if the user does not exist, return False if the user exists but |
| 38 |
password is not correct, and return True otherwise. |
| 39 |
|
| 40 |
""" |
| 41 |
# db connection state is managed similarly to the wsgi handler |
| 42 |
# as mod_wsgi may call these functions outside of a request/response cycle |
| 43 |
db.reset_queries() |
| 44 |
try: |
| 45 |
user = _get_user(username) |
| 46 |
if user: |
| 47 |
return user.check_password(password) |
| 48 |
finally: |
| 49 |
db.close_old_connections() |
| 50 |
|
| 51 |
|
| 52 |
def groups_for_user(environ, username): |
| 53 |
""" |
| 54 |
Authorize a user based on groups |
| 55 |
""" |
| 56 |
db.reset_queries() |
| 57 |
try: |
| 58 |
try: |
| 59 |
user = UserModel._default_manager.get_by_natural_key(username) |
| 60 |
except UserModel.DoesNotExist: |
| 61 |
return [] |
| 62 |
if not user.is_active: |
| 63 |
return [] |
| 64 |
return [group.name.encode() for group in user.groups.all()] |
| 65 |
finally: |
| 66 |
db.close_old_connections() |