Debian Codegraph @

django/contrib/auth/models.py

raw
1 from collections.abc import Iterable
2
3 from django.apps import apps
4 from django.contrib import auth
5 from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
6 from django.contrib.auth.hashers import make_password
7 from django.contrib.contenttypes.models import ContentType
8 from django.core.exceptions import PermissionDenied
9 from django.core.mail import send_mail
10 from django.db import models
11 from django.db.models.manager import EmptyManager
12 from django.utils import timezone
13 from django.utils.translation import gettext_lazy as _
14
15 from .validators import UnicodeUsernameValidator
16
17
18 def update_last_login(sender, user, **kwargs):
19 """
20 A signal receiver which updates the last_login date for
21 the user logging in.
22 """
23 user.last_login = timezone.now()
24 user.save(update_fields=["last_login"])
25
26
27 class PermissionManager(models.Manager):
28 use_in_migrations = True
29
30 def get_by_natural_key(self, codename, app_label, model):
31 return self.get(
32 codename=codename,
33 content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(
34 app_label, model
35 ),
36 )
37
38
39 class Permission(models.Model):
40 """
41 The permissions system provides a way to assign permissions to specific
42 users and groups of users.
43
44 The permission system is used by the Django admin site, but may also be
45 useful in your own code. The Django admin site uses permissions as follows:
46
47 - The "add" permission limits the user's ability to view the "add" form
48 and add an object.
49 - The "change" permission limits a user's ability to view the change
50 list, view the "change" form and change an object.
51 - The "delete" permission limits the ability to delete an object.
52 - The "view" permission limits the ability to view an object.
53
54 Permissions are set globally per type of object, not per specific object
55 instance. It is possible to say "Mary may change news stories," but it's
56 not currently possible to say "Mary may change news stories, but only the
57 ones she created herself" or "Mary may only change news stories that have a
58 certain status or publication date."
59
60 The permissions listed above are automatically created for each model.
61 """
62
63 name = models.CharField(_("name"), max_length=255)
64 content_type = models.ForeignKey(
65 ContentType,
66 models.CASCADE,
67 verbose_name=_("content type"),
68 )
69 codename = models.CharField(_("codename"), max_length=100)
70
71 objects = PermissionManager()
72
73 class Meta:
74 verbose_name = _("permission")
75 verbose_name_plural = _("permissions")
76 unique_together = [["content_type", "codename"]]
77 ordering = ["content_type__app_label", "content_type__model", "codename"]
78
79 def __str__(self):
80 return "%s | %s" % (self.content_type, self.name)
81
82 def natural_key(self):
83 return (self.codename,) + self.content_type.natural_key()
84
85 natural_key.dependencies = ["contenttypes.contenttype"]
86
87
88 class GroupManager(models.Manager):
89 """
90 The manager for the auth's Group model.
91 """
92
93 use_in_migrations = True
94
95 def get_by_natural_key(self, name):
96 return self.get(name=name)
97
98 async def aget_by_natural_key(self, name):
99 return await self.aget(name=name)
100
101
102 class Group(models.Model):
103 """
104 Groups are a generic way of categorizing users to apply permissions, or
105 some other label, to those users. A user can belong to any number of
106 groups.
107
108 A user in a group automatically has all the permissions granted to that
109 group. For example, if the group 'Site editors' has the permission
110 can_edit_home_page, any user in that group will have that permission.
111
112 Beyond permissions, groups are a convenient way to categorize users to
113 apply some label, or extended functionality, to them. For example, you
114 could create a group 'Special users', and you could write code that would
115 do special things to those users -- such as giving them access to a
116 members-only portion of your site, or sending them members-only email
117 messages.
118 """
119
120 name = models.CharField(_("name"), max_length=150, unique=True)
121 permissions = models.ManyToManyField(
122 Permission,
123 verbose_name=_("permissions"),
124 blank=True,
125 )
126
127 objects = GroupManager()
128
129 class Meta:
130 verbose_name = _("group")
131 verbose_name_plural = _("groups")
132
133 def __str__(self):
134 return self.name
135
136 def natural_key(self):
137 return (self.name,)
138
139
140 class UserManager(BaseUserManager):
141 use_in_migrations = True
142
143 def _create_user_object(self, username, email, password, **extra_fields):
144 if not username:
145 raise ValueError("The given username must be set")
146 email = self.normalize_email(email)
147 # Lookup the real model class from the global app registry so this
148 # manager method can be used in migrations. This is fine because
149 # managers are by definition working on the real model.
150 GlobalUserModel = apps.get_model(
151 self.model._meta.app_label, self.model._meta.object_name
152 )
153 username = GlobalUserModel.normalize_username(username)
154 user = self.model(username=username, email=email, **extra_fields)
155 user.password = make_password(password)
156 return user
157
158 def _create_user(self, username, email, password, **extra_fields):
159 """
160 Create and save a user with the given username, email, and password.
161 """
162 user = self._create_user_object(username, email, password, **extra_fields)
163 user.save(using=self._db)
164 return user
165
166 async def _acreate_user(self, username, email, password, **extra_fields):
167 """See _create_user()"""
168 user = self._create_user_object(username, email, password, **extra_fields)
169 await user.asave(using=self._db)
170 return user
171
172 def create_user(self, username, email=None, password=None, **extra_fields):
173 extra_fields.setdefault("is_staff", False)
174 extra_fields.setdefault("is_superuser", False)
175 return self._create_user(username, email, password, **extra_fields)
176
177 create_user.alters_data = True
178
179 async def acreate_user(self, username, email=None, password=None, **extra_fields):
180 extra_fields.setdefault("is_staff", False)
181 extra_fields.setdefault("is_superuser", False)
182 return await self._acreate_user(username, email, password, **extra_fields)
183
184 acreate_user.alters_data = True
185
186 def create_superuser(self, username, email=None, password=None, **extra_fields):
187 extra_fields.setdefault("is_staff", True)
188 extra_fields.setdefault("is_superuser", True)
189
190 if extra_fields.get("is_staff") is not True:
191 raise ValueError("Superuser must have is_staff=True.")
192 if extra_fields.get("is_superuser") is not True:
193 raise ValueError("Superuser must have is_superuser=True.")
194
195 return self._create_user(username, email, password, **extra_fields)
196
197 create_superuser.alters_data = True
198
199 async def acreate_superuser(
200 self, username, email=None, password=None, **extra_fields
201 ):
202 extra_fields.setdefault("is_staff", True)
203 extra_fields.setdefault("is_superuser", True)
204
205 if extra_fields.get("is_staff") is not True:
206 raise ValueError("Superuser must have is_staff=True.")
207 if extra_fields.get("is_superuser") is not True:
208 raise ValueError("Superuser must have is_superuser=True.")
209
210 return await self._acreate_user(username, email, password, **extra_fields)
211
212 acreate_superuser.alters_data = True
213
214 def with_perm(
215 self, perm, is_active=True, include_superusers=True, backend=None, obj=None
216 ):
217 if backend is None:
218 backends = auth._get_backends(return_tuples=True)
219 if len(backends) == 1:
220 backend, _ = backends[0]
221 else:
222 raise ValueError(
223 "You have multiple authentication backends configured and "
224 "therefore must provide the `backend` argument."
225 )
226 elif not isinstance(backend, str):
227 raise TypeError(
228 "backend must be a dotted import path string (got %r)." % backend
229 )
230 else:
231 backend = auth.load_backend(backend)
232 if hasattr(backend, "with_perm"):
233 return backend.with_perm(
234 perm,
235 is_active=is_active,
236 include_superusers=include_superusers,
237 obj=obj,
238 )
239 return self.none()
240
241
242 # A few helper functions for common logic between User and AnonymousUser.
243 def _user_get_permissions(user, obj, from_name):
244 permissions = set()
245 name = "get_%s_permissions" % from_name
246 for backend in auth.get_backends():
247 if hasattr(backend, name):
248 permissions.update(getattr(backend, name)(user, obj))
249 return permissions
250
251
252 async def _auser_get_permissions(user, obj, from_name):
253 permissions = set()
254 name = "aget_%s_permissions" % from_name
255 for backend in auth.get_backends():
256 if hasattr(backend, name):
257 permissions.update(await getattr(backend, name)(user, obj))
258 return permissions
259
260
261 def _user_has_perm(user, perm, obj):
262 """
263 A backend can raise `PermissionDenied` to short-circuit permission checking.
264 """
265 for backend in auth.get_backends():
266 if not hasattr(backend, "has_perm"):
267 continue
268 try:
269 if backend.has_perm(user, perm, obj):
270 return True
271 except PermissionDenied:
272 return False
273 return False
274
275
276 async def _auser_has_perm(user, perm, obj):
277 """See _user_has_perm()"""
278 for backend in auth.get_backends():
279 if not hasattr(backend, "ahas_perm"):
280 continue
281 try:
282 if await backend.ahas_perm(user, perm, obj):
283 return True
284 except PermissionDenied:
285 return False
286 return False
287
288
289 def _user_has_module_perms(user, app_label):
290 """
291 A backend can raise `PermissionDenied` to short-circuit permission checking.
292 """
293 for backend in auth.get_backends():
294 if not hasattr(backend, "has_module_perms"):
295 continue
296 try:
297 if backend.has_module_perms(user, app_label):
298 return True
299 except PermissionDenied:
300 return False
301 return False
302
303
304 async def _auser_has_module_perms(user, app_label):
305 """See _user_has_module_perms()"""
306 for backend in auth.get_backends():
307 if not hasattr(backend, "ahas_module_perms"):
308 continue
309 try:
310 if await backend.ahas_module_perms(user, app_label):
311 return True
312 except PermissionDenied:
313 return False
314 return False
315
316
317 class PermissionsMixin(models.Model):
318 """
319 Add the fields and methods necessary to support the Group and Permission
320 models using the ModelBackend.
321 """
322
323 is_superuser = models.BooleanField(
324 _("superuser status"),
325 default=False,
326 help_text=_(
327 "Designates that this user has all permissions without "
328 "explicitly assigning them."
329 ),
330 )
331 groups = models.ManyToManyField(
332 Group,
333 verbose_name=_("groups"),
334 blank=True,
335 help_text=_(
336 "The groups this user belongs to. A user will get all permissions "
337 "granted to each of their groups."
338 ),
339 related_name="user_set",
340 related_query_name="user",
341 )
342 user_permissions = models.ManyToManyField(
343 Permission,
344 verbose_name=_("user permissions"),
345 blank=True,
346 help_text=_("Specific permissions for this user."),
347 related_name="user_set",
348 related_query_name="user",
349 )
350
351 class Meta:
352 abstract = True
353
354 def get_user_permissions(self, obj=None):
355 """
356 Return a list of permission strings that this user has directly.
357 Query all available auth backends. If an object is passed in,
358 return only permissions matching this object.
359 """
360 return _user_get_permissions(self, obj, "user")
361
362 async def aget_user_permissions(self, obj=None):
363 """See get_user_permissions()"""
364 return await _auser_get_permissions(self, obj, "user")
365
366 def get_group_permissions(self, obj=None):
367 """
368 Return a list of permission strings that this user has through their
369 groups. Query all available auth backends. If an object is passed in,
370 return only permissions matching this object.
371 """
372 return _user_get_permissions(self, obj, "group")
373
374 async def aget_group_permissions(self, obj=None):
375 """See get_group_permissions()"""
376 return await _auser_get_permissions(self, obj, "group")
377
378 def get_all_permissions(self, obj=None):
379 return _user_get_permissions(self, obj, "all")
380
381 async def aget_all_permissions(self, obj=None):
382 return await _auser_get_permissions(self, obj, "all")
383
384 def has_perm(self, perm, obj=None):
385 """
386 Return True if the user has the specified permission. Query all
387 available auth backends, but return immediately if any backend returns
388 True. Thus, a user who has permission from a single auth backend is
389 assumed to have permission in general. If an object is provided, check
390 permissions for that object.
391 """
392 # Active superusers have all permissions.
393 if self.is_active and self.is_superuser:
394 return True
395
396 # Otherwise we need to check the backends.
397 return _user_has_perm(self, perm, obj)
398
399 async def ahas_perm(self, perm, obj=None):
400 """See has_perm()"""
401 # Active superusers have all permissions.
402 if self.is_active and self.is_superuser:
403 return True
404
405 # Otherwise we need to check the backends.
406 return await _auser_has_perm(self, perm, obj)
407
408 def has_perms(self, perm_list, obj=None):
409 """
410 Return True if the user has each of the specified permissions. If
411 object is passed, check if the user has all required perms for it.
412 """
413 if not isinstance(perm_list, Iterable) or isinstance(perm_list, str):
414 raise ValueError("perm_list must be an iterable of permissions.")
415 return all(self.has_perm(perm, obj) for perm in perm_list)
416
417 async def ahas_perms(self, perm_list, obj=None):
418 """See has_perms()"""
419 if not isinstance(perm_list, Iterable) or isinstance(perm_list, str):
420 raise ValueError("perm_list must be an iterable of permissions.")
421 for perm in perm_list:
422 if not await self.ahas_perm(perm, obj):
423 return False
424 return True
425
426 def has_module_perms(self, app_label):
427 """
428 Return True if the user has any permissions in the given app label.
429 Use similar logic as has_perm(), above.
430 """
431 # Active superusers have all permissions.
432 if self.is_active and self.is_superuser:
433 return True
434
435 return _user_has_module_perms(self, app_label)
436
437 async def ahas_module_perms(self, app_label):
438 """See has_module_perms()"""
439 # Active superusers have all permissions.
440 if self.is_active and self.is_superuser:
441 return True
442
443 return await _auser_has_module_perms(self, app_label)
444
445
446 class AbstractUser(AbstractBaseUser, PermissionsMixin):
447 """
448 An abstract base class implementing a fully featured User model with
449 admin-compliant permissions.
450
451 Username and password are required. Other fields are optional.
452 """
453
454 username_validator = UnicodeUsernameValidator()
455
456 username = models.CharField(
457 _("username"),
458 max_length=150,
459 unique=True,
460 help_text=_(
461 "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
462 ),
463 validators=[username_validator],
464 error_messages={
465 "unique": _("A user with that username already exists."),
466 },
467 )
468 first_name = models.CharField(_("first name"), max_length=150, blank=True)
469 last_name = models.CharField(_("last name"), max_length=150, blank=True)
470 email = models.EmailField(_("email address"), blank=True)
471 is_staff = models.BooleanField(
472 _("staff status"),
473 default=False,
474 help_text=_("Designates whether the user can log into this admin site."),
475 )
476 is_active = models.BooleanField(
477 _("active"),
478 default=True,
479 help_text=_(
480 "Designates whether this user should be treated as active. "
481 "Unselect this instead of deleting accounts."
482 ),
483 )
484 date_joined = models.DateTimeField(_("date joined"), default=timezone.now)
485
486 objects = UserManager()
487
488 EMAIL_FIELD = "email"
489 USERNAME_FIELD = "username"
490 REQUIRED_FIELDS = ["email"]
491
492 class Meta:
493 verbose_name = _("user")
494 verbose_name_plural = _("users")
495 abstract = True
496
497 def clean(self):
498 super().clean()
499 self.email = self.__class__.objects.normalize_email(self.email)
500
501 def get_full_name(self):
502 """
503 Return the first_name plus the last_name, with a space in between.
504 """
505 full_name = "%s %s" % (self.first_name, self.last_name)
506 return full_name.strip()
507
508 def get_short_name(self):
509 """Return the short name for the user."""
510 return self.first_name
511
512 def email_user(self, subject, message, from_email=None, **kwargs):
513 """Send an email to this user."""
514 send_mail(subject, message, from_email, [self.email], **kwargs)
515
516
517 class User(AbstractUser):
518 """
519 Users within the Django authentication system are represented by this
520 model.
521
522 Username and password are required. Other fields are optional.
523 """
524
525 class Meta(AbstractUser.Meta):
526 swappable = "AUTH_USER_MODEL"
527
528
529 class AnonymousUser:
530 id = None
531 pk = None
532 username = ""
533 is_staff = False
534 is_active = False
535 is_superuser = False
536 _groups = EmptyManager(Group)
537 _user_permissions = EmptyManager(Permission)
538
539 def __str__(self):
540 return "AnonymousUser"
541
542 def __eq__(self, other):
543 return isinstance(other, self.__class__)
544
545 def __hash__(self):
546 return 1 # instances always return the same hash value
547
548 def __int__(self):
549 raise TypeError(
550 "Cannot cast AnonymousUser to int. Are you trying to use it in place of "
551 "User?"
552 )
553
554 def save(self):
555 raise NotImplementedError(
556 "Django doesn't provide a DB representation for AnonymousUser."
557 )
558
559 def delete(self):
560 raise NotImplementedError(
561 "Django doesn't provide a DB representation for AnonymousUser."
562 )
563
564 def set_password(self, raw_password):
565 raise NotImplementedError(
566 "Django doesn't provide a DB representation for AnonymousUser."
567 )
568
569 def check_password(self, raw_password):
570 raise NotImplementedError(
571 "Django doesn't provide a DB representation for AnonymousUser."
572 )
573
574 @property
575 def groups(self):
576 return self._groups
577
578 @property
579 def user_permissions(self):
580 return self._user_permissions
581
582 def get_user_permissions(self, obj=None):
583 return _user_get_permissions(self, obj, "user")
584
585 async def aget_user_permissions(self, obj=None):
586 return await _auser_get_permissions(self, obj, "user")
587
588 def get_group_permissions(self, obj=None):
589 return set()
590
591 async def aget_group_permissions(self, obj=None):
592 return self.get_group_permissions(obj)
593
594 def get_all_permissions(self, obj=None):
595 return _user_get_permissions(self, obj, "all")
596
597 async def aget_all_permissions(self, obj=None):
598 return await _auser_get_permissions(self, obj, "all")
599
600 def has_perm(self, perm, obj=None):
601 return _user_has_perm(self, perm, obj=obj)
602
603 async def ahas_perm(self, perm, obj=None):
604 return await _auser_has_perm(self, perm, obj=obj)
605
606 def has_perms(self, perm_list, obj=None):
607 if not isinstance(perm_list, Iterable) or isinstance(perm_list, str):
608 raise ValueError("perm_list must be an iterable of permissions.")
609 return all(self.has_perm(perm, obj) for perm in perm_list)
610
611 async def ahas_perms(self, perm_list, obj=None):
612 if not isinstance(perm_list, Iterable) or isinstance(perm_list, str):
613 raise ValueError("perm_list must be an iterable of permissions.")
614 for perm in perm_list:
615 if not await self.ahas_perm(perm, obj):
616 return False
617 return True
618
619 def has_module_perms(self, module):
620 return _user_has_module_perms(self, module)
621
622 async def ahas_module_perms(self, module):
623 return await _auser_has_module_perms(self, module)
624
625 @property
626 def is_anonymous(self):
627 return True
628
629 @property
630 def is_authenticated(self):
631 return False
632
633 def get_username(self):
634 return self.username