__init__.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import inspect
  2. import re
  3. from django.apps import apps as django_apps
  4. from django.conf import settings
  5. from django.core.exceptions import ImproperlyConfigured, PermissionDenied
  6. from django.middleware.csrf import rotate_token
  7. from django.utils.crypto import constant_time_compare
  8. from django.utils.module_loading import import_string
  9. from .signals import user_logged_in, user_logged_out, user_login_failed
  10. SESSION_KEY = '_auth_user_id'
  11. BACKEND_SESSION_KEY = '_auth_user_backend'
  12. HASH_SESSION_KEY = '_auth_user_hash'
  13. REDIRECT_FIELD_NAME = 'next'
  14. def load_backend(path):
  15. return import_string(path)()
  16. def _get_backends(return_tuples=False):
  17. backends = []
  18. for backend_path in settings.AUTHENTICATION_BACKENDS:
  19. backend = load_backend(backend_path)
  20. backends.append((backend, backend_path) if return_tuples else backend)
  21. if not backends:
  22. raise ImproperlyConfigured(
  23. 'No authentication backends have been defined. Does '
  24. 'AUTHENTICATION_BACKENDS contain anything?'
  25. )
  26. return backends
  27. def get_backends():
  28. return _get_backends(return_tuples=False)
  29. def _clean_credentials(credentials):
  30. """
  31. Clean a dictionary of credentials of potentially sensitive info before
  32. sending to less secure functions.
  33. Not comprehensive - intended for user_login_failed signal
  34. """
  35. SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I)
  36. CLEANSED_SUBSTITUTE = '********************'
  37. for key in credentials:
  38. if SENSITIVE_CREDENTIALS.search(key):
  39. credentials[key] = CLEANSED_SUBSTITUTE
  40. return credentials
  41. def _get_user_session_key(request):
  42. # This value in the session is always serialized to a string, so we need
  43. # to convert it back to Python whenever we access it.
  44. return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
  45. def authenticate(request=None, **credentials):
  46. """
  47. If the given credentials are valid, return a User object.
  48. """
  49. for backend, backend_path in _get_backends(return_tuples=True):
  50. try:
  51. inspect.getcallargs(backend.authenticate, request, **credentials)
  52. except TypeError:
  53. # This backend doesn't accept these credentials as arguments. Try the next one.
  54. continue
  55. try:
  56. user = backend.authenticate(request, **credentials)
  57. except PermissionDenied:
  58. # This backend says to stop in our tracks - this user should not be allowed in at all.
  59. break
  60. if user is None:
  61. continue
  62. # Annotate the user object with the path of the backend.
  63. user.backend = backend_path
  64. return user
  65. # The credentials supplied are invalid to all backends, fire signal
  66. user_login_failed.send(sender=__name__, credentials=_clean_credentials(credentials), request=request)
  67. def login(request, user, backend=None):
  68. """
  69. Persist a user id and a backend in the request. This way a user doesn't
  70. have to reauthenticate on every request. Note that data set during
  71. the anonymous session is retained when the user logs in.
  72. """
  73. session_auth_hash = ''
  74. if user is None:
  75. user = request.user
  76. if hasattr(user, 'get_session_auth_hash'):
  77. session_auth_hash = user.get_session_auth_hash()
  78. if SESSION_KEY in request.session:
  79. if _get_user_session_key(request) != user.pk or (
  80. session_auth_hash and
  81. not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)):
  82. # To avoid reusing another user's session, create a new, empty
  83. # session if the existing session corresponds to a different
  84. # authenticated user.
  85. request.session.flush()
  86. else:
  87. request.session.cycle_key()
  88. try:
  89. backend = backend or user.backend
  90. except AttributeError:
  91. backends = _get_backends(return_tuples=True)
  92. if len(backends) == 1:
  93. _, backend = backends[0]
  94. else:
  95. raise ValueError(
  96. 'You have multiple authentication backends configured and '
  97. 'therefore must provide the `backend` argument or set the '
  98. '`backend` attribute on the user.'
  99. )
  100. else:
  101. if not isinstance(backend, str):
  102. raise TypeError('backend must be a dotted import path string (got %r).' % backend)
  103. request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
  104. request.session[BACKEND_SESSION_KEY] = backend
  105. request.session[HASH_SESSION_KEY] = session_auth_hash
  106. if hasattr(request, 'user'):
  107. request.user = user
  108. rotate_token(request)
  109. user_logged_in.send(sender=user.__class__, request=request, user=user)
  110. def logout(request):
  111. """
  112. Remove the authenticated user's ID from the request and flush their session
  113. data.
  114. """
  115. # Dispatch the signal before the user is logged out so the receivers have a
  116. # chance to find out *who* logged out.
  117. user = getattr(request, 'user', None)
  118. if not getattr(user, 'is_authenticated', True):
  119. user = None
  120. user_logged_out.send(sender=user.__class__, request=request, user=user)
  121. request.session.flush()
  122. if hasattr(request, 'user'):
  123. from django.contrib.auth.models import AnonymousUser
  124. request.user = AnonymousUser()
  125. def get_user_model():
  126. """
  127. Return the User model that is active in this project.
  128. """
  129. try:
  130. return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
  131. except ValueError:
  132. raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
  133. except LookupError:
  134. raise ImproperlyConfigured(
  135. "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
  136. )
  137. def get_user(request):
  138. """
  139. Return the user model instance associated with the given request session.
  140. If no user is retrieved, return an instance of `AnonymousUser`.
  141. """
  142. from .models import AnonymousUser
  143. user = None
  144. try:
  145. user_id = _get_user_session_key(request)
  146. backend_path = request.session[BACKEND_SESSION_KEY]
  147. except KeyError:
  148. pass
  149. else:
  150. if backend_path in settings.AUTHENTICATION_BACKENDS:
  151. backend = load_backend(backend_path)
  152. user = backend.get_user(user_id)
  153. # Verify the session
  154. if hasattr(user, 'get_session_auth_hash'):
  155. session_hash = request.session.get(HASH_SESSION_KEY)
  156. session_hash_verified = session_hash and constant_time_compare(
  157. session_hash,
  158. user.get_session_auth_hash()
  159. )
  160. if not session_hash_verified:
  161. request.session.flush()
  162. user = None
  163. return user or AnonymousUser()
  164. def get_permission_codename(action, opts):
  165. """
  166. Return the codename of the permission for the specified action.
  167. """
  168. return '%s_%s' % (action, opts.model_name)
  169. def update_session_auth_hash(request, user):
  170. """
  171. Updating a user's password logs out all sessions for the user.
  172. Take the current request and the updated user object from which the new
  173. session hash will be derived and update the session hash appropriately to
  174. prevent a password change from logging out the session from which the
  175. password was changed.
  176. """
  177. request.session.cycle_key()
  178. if hasattr(user, 'get_session_auth_hash') and request.user == user:
  179. request.session[HASH_SESSION_KEY] = user.get_session_auth_hash()
  180. default_app_config = 'django.contrib.auth.apps.AuthConfig'