__init__.py 9.4 KB

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