Debian Codegraph @

django/contrib/auth/__init__.py

raw
1 import re
2 import warnings
3
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.deprecation import RemovedInDjango61Warning
10 from django.utils.inspect import signature
11 from django.utils.module_loading import import_string
12 from django.views.decorators.debug import sensitive_variables
13
14 from .signals import user_logged_in, user_logged_out, user_login_failed
15
16 SESSION_KEY = "_auth_user_id"
17 BACKEND_SESSION_KEY = "_auth_user_backend"
18 HASH_SESSION_KEY = "_auth_user_hash"
19 REDIRECT_FIELD_NAME = "next"
20
21
22 def load_backend(path):
23 return import_string(path)()
24
25
26 def _get_backends(return_tuples=False):
27 backends = []
28 for backend_path in settings.AUTHENTICATION_BACKENDS:
29 backend = load_backend(backend_path)
30 backends.append((backend, backend_path) if return_tuples else backend)
31 if not backends:
32 raise ImproperlyConfigured(
33 "No authentication backends have been defined. Does "
34 "AUTHENTICATION_BACKENDS contain anything?"
35 )
36 return backends
37
38
39 def get_backends():
40 return _get_backends(return_tuples=False)
41
42
43 def _get_compatible_backends(request, **credentials):
44 for backend, backend_path in _get_backends(return_tuples=True):
45 backend_signature = signature(backend.authenticate)
46 try:
47 backend_signature.bind(request, **credentials)
48 except TypeError:
49 # This backend doesn't accept these credentials as arguments. Try
50 # the next one.
51 continue
52 yield backend, backend_path
53
54
55 def _get_backend_from_user(user, backend=None):
56 try:
57 backend = backend or user.backend
58 except AttributeError:
59 backends = _get_backends(return_tuples=True)
60 if len(backends) == 1:
61 _, backend = backends[0]
62 else:
63 raise ValueError(
64 "You have multiple authentication backends configured and "
65 "therefore must provide the `backend` argument or set the "
66 "`backend` attribute on the user."
67 )
68 else:
69 if not isinstance(backend, str):
70 raise TypeError(
71 "backend must be a dotted import path string (got %r)." % backend
72 )
73 return backend
74
75
76 @sensitive_variables("credentials")
77 def _clean_credentials(credentials):
78 """
79 Clean a dictionary of credentials of potentially sensitive info before
80 sending to less secure functions.
81
82 Not comprehensive - intended for user_login_failed signal
83 """
84 SENSITIVE_CREDENTIALS = re.compile("api|token|key|secret|password|signature", re.I)
85 CLEANSED_SUBSTITUTE = "********************"
86 for key in credentials:
87 if SENSITIVE_CREDENTIALS.search(key):
88 credentials[key] = CLEANSED_SUBSTITUTE
89 return credentials
90
91
92 def _get_user_session_key(request):
93 # This value in the session is always serialized to a string, so we need
94 # to convert it back to Python whenever we access it.
95 return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
96
97
98 async def _aget_user_session_key(request):
99 # This value in the session is always serialized to a string, so we need
100 # to convert it back to Python whenever we access it.
101 session_key = await request.session.aget(SESSION_KEY)
102 if session_key is None:
103 raise KeyError()
104 return get_user_model()._meta.pk.to_python(session_key)
105
106
107 @sensitive_variables("credentials")
108 def authenticate(request=None, **credentials):
109 """
110 If the given credentials are valid, return a User object.
111 """
112 for backend, backend_path in _get_compatible_backends(request, **credentials):
113 try:
114 user = backend.authenticate(request, **credentials)
115 except PermissionDenied:
116 # This backend says to stop in our tracks - this user should not be
117 # allowed in at all.
118 break
119 if user is None:
120 continue
121 # Annotate the user object with the path of the backend.
122 user.backend = backend_path
123 return user
124
125 # The credentials supplied are invalid to all backends, fire signal
126 user_login_failed.send(
127 sender=__name__, credentials=_clean_credentials(credentials), request=request
128 )
129
130
131 @sensitive_variables("credentials")
132 async def aauthenticate(request=None, **credentials):
133 """See authenticate()."""
134 for backend, backend_path in _get_compatible_backends(request, **credentials):
135 try:
136 user = await backend.aauthenticate(request, **credentials)
137 except PermissionDenied:
138 # This backend says to stop in our tracks - this user should not be
139 # allowed in at all.
140 break
141 if user is None:
142 continue
143 # Annotate the user object with the path of the backend.
144 user.backend = backend_path
145 return user
146
147 # The credentials supplied are invalid to all backends, fire signal.
148 await user_login_failed.asend(
149 sender=__name__, credentials=_clean_credentials(credentials), request=request
150 )
151
152
153 def login(request, user, backend=None):
154 """
155 Persist a user id and a backend in the request. This way a user doesn't
156 have to reauthenticate on every request. Note that data set during
157 the anonymous session is retained when the user logs in.
158 """
159 # RemovedInDjango61Warning: When the deprecation ends, replace with:
160 # session_auth_hash = user.get_session_auth_hash()
161 session_auth_hash = ""
162 # RemovedInDjango61Warning.
163 if user is None:
164 user = request.user
165 warnings.warn(
166 "Fallback to request.user when user is None will be removed.",
167 RemovedInDjango61Warning,
168 stacklevel=2,
169 )
170
171 # RemovedInDjango61Warning.
172 if hasattr(user, "get_session_auth_hash"):
173 session_auth_hash = user.get_session_auth_hash()
174
175 if SESSION_KEY in request.session:
176 if _get_user_session_key(request) != user.pk or (
177 session_auth_hash
178 and not constant_time_compare(
179 request.session.get(HASH_SESSION_KEY, ""), session_auth_hash
180 )
181 ):
182 # To avoid reusing another user's session, create a new, empty
183 # session if the existing session corresponds to a different
184 # authenticated user.
185 request.session.flush()
186 else:
187 request.session.cycle_key()
188
189 backend = _get_backend_from_user(user=user, backend=backend)
190
191 request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
192 request.session[BACKEND_SESSION_KEY] = backend
193 request.session[HASH_SESSION_KEY] = session_auth_hash
194 if hasattr(request, "user"):
195 request.user = user
196 rotate_token(request)
197 user_logged_in.send(sender=user.__class__, request=request, user=user)
198
199
200 async def alogin(request, user, backend=None):
201 """See login()."""
202 # RemovedInDjango61Warning: When the deprecation ends, replace with:
203 # session_auth_hash = user.get_session_auth_hash()
204 session_auth_hash = ""
205 # RemovedInDjango61Warning.
206 if user is None:
207 warnings.warn(
208 "Fallback to request.auser() when user is None will be removed.",
209 RemovedInDjango61Warning,
210 stacklevel=2,
211 )
212 user = await request.auser()
213 # RemovedInDjango61Warning.
214 if hasattr(user, "get_session_auth_hash"):
215 session_auth_hash = user.get_session_auth_hash()
216
217 if await request.session.ahas_key(SESSION_KEY):
218 if await _aget_user_session_key(request) != user.pk or (
219 session_auth_hash
220 and not constant_time_compare(
221 await request.session.aget(HASH_SESSION_KEY, ""),
222 session_auth_hash,
223 )
224 ):
225 # To avoid reusing another user's session, create a new, empty
226 # session if the existing session corresponds to a different
227 # authenticated user.
228 await request.session.aflush()
229 else:
230 await request.session.acycle_key()
231
232 backend = _get_backend_from_user(user=user, backend=backend)
233
234 await request.session.aset(SESSION_KEY, user._meta.pk.value_to_string(user))
235 await request.session.aset(BACKEND_SESSION_KEY, backend)
236 await request.session.aset(HASH_SESSION_KEY, session_auth_hash)
237 if hasattr(request, "user"):
238 request.user = user
239 rotate_token(request)
240 await user_logged_in.asend(sender=user.__class__, request=request, user=user)
241
242
243 def logout(request):
244 """
245 Remove the authenticated user's ID from the request and flush their session
246 data.
247 """
248 # Dispatch the signal before the user is logged out so the receivers have a
249 # chance to find out *who* logged out.
250 user = getattr(request, "user", None)
251 if not getattr(user, "is_authenticated", True):
252 user = None
253 user_logged_out.send(sender=user.__class__, request=request, user=user)
254 request.session.flush()
255 if hasattr(request, "user"):
256 from django.contrib.auth.models import AnonymousUser
257
258 request.user = AnonymousUser()
259
260
261 async def alogout(request):
262 """See logout()."""
263 # Dispatch the signal before the user is logged out so the receivers have a
264 # chance to find out *who* logged out.
265 user = getattr(request, "auser", None)
266 if user is not None:
267 user = await user()
268 if not getattr(user, "is_authenticated", True):
269 user = None
270 await user_logged_out.asend(sender=user.__class__, request=request, user=user)
271 await request.session.aflush()
272 if hasattr(request, "user"):
273 from django.contrib.auth.models import AnonymousUser
274
275 request.user = AnonymousUser()
276
277
278 def get_user_model():
279 """
280 Return the User model that is active in this project.
281 """
282 try:
283 return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
284 except ValueError:
285 raise ImproperlyConfigured(
286 "AUTH_USER_MODEL must be of the form 'app_label.model_name'"
287 )
288 except LookupError:
289 raise ImproperlyConfigured(
290 "AUTH_USER_MODEL refers to model '%s' that has not been installed"
291 % settings.AUTH_USER_MODEL
292 )
293
294
295 def get_user(request):
296 """
297 Return the user model instance associated with the given request session.
298 If no user is retrieved, return an instance of `AnonymousUser`.
299 """
300 from .models import AnonymousUser
301
302 user = None
303 try:
304 user_id = _get_user_session_key(request)
305 backend_path = request.session[BACKEND_SESSION_KEY]
306 except KeyError:
307 pass
308 else:
309 if backend_path in settings.AUTHENTICATION_BACKENDS:
310 backend = load_backend(backend_path)
311 user = backend.get_user(user_id)
312 # Verify the session
313 if hasattr(user, "get_session_auth_hash"):
314 session_hash = request.session.get(HASH_SESSION_KEY)
315 if not session_hash:
316 session_hash_verified = False
317 else:
318 session_auth_hash = user.get_session_auth_hash()
319 session_hash_verified = constant_time_compare(
320 session_hash, session_auth_hash
321 )
322 if not session_hash_verified:
323 # If the current secret does not verify the session, try
324 # with the fallback secrets and stop when a matching one is
325 # found.
326 if session_hash and any(
327 constant_time_compare(session_hash, fallback_auth_hash)
328 for fallback_auth_hash in user.get_session_auth_fallback_hash()
329 ):
330 request.session.cycle_key()
331 request.session[HASH_SESSION_KEY] = session_auth_hash
332 else:
333 request.session.flush()
334 user = None
335
336 return user or AnonymousUser()
337
338
339 async def aget_user(request):
340 """See get_user()."""
341 from .models import AnonymousUser
342
343 user = None
344 try:
345 user_id = await _aget_user_session_key(request)
346 backend_path = await request.session.aget(BACKEND_SESSION_KEY)
347 except KeyError:
348 pass
349 else:
350 if backend_path in settings.AUTHENTICATION_BACKENDS:
351 backend = load_backend(backend_path)
352 user = await backend.aget_user(user_id)
353 # Verify the session
354 if hasattr(user, "get_session_auth_hash"):
355 session_hash = await request.session.aget(HASH_SESSION_KEY)
356 if not session_hash:
357 session_hash_verified = False
358 else:
359 session_auth_hash = user.get_session_auth_hash()
360 session_hash_verified = session_hash and constant_time_compare(
361 session_hash, user.get_session_auth_hash()
362 )
363 if not session_hash_verified:
364 # If the current secret does not verify the session, try
365 # with the fallback secrets and stop when a matching one is
366 # found.
367 if session_hash and any(
368 constant_time_compare(session_hash, fallback_auth_hash)
369 for fallback_auth_hash in user.get_session_auth_fallback_hash()
370 ):
371 await request.session.acycle_key()
372 await request.session.aset(HASH_SESSION_KEY, session_auth_hash)
373 else:
374 await request.session.aflush()
375 user = None
376
377 return user or AnonymousUser()
378
379
380 def get_permission_codename(action, opts):
381 """
382 Return the codename of the permission for the specified action.
383 """
384 return "%s_%s" % (action, opts.model_name)
385
386
387 def update_session_auth_hash(request, user):
388 """
389 Updating a user's password logs out all sessions for the user.
390
391 Take the current request and the updated user object from which the new
392 session hash will be derived and update the session hash appropriately to
393 prevent a password change from logging out the session from which the
394 password was changed.
395 """
396 request.session.cycle_key()
397 if hasattr(user, "get_session_auth_hash") and request.user == user:
398 request.session[HASH_SESSION_KEY] = user.get_session_auth_hash()
399
400
401 async def aupdate_session_auth_hash(request, user):
402 """See update_session_auth_hash()."""
403 await request.session.acycle_key()
404 if hasattr(user, "get_session_auth_hash") and request.user == user:
405 await request.session.aset(HASH_SESSION_KEY, user.get_session_auth_hash())