models.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. from django.apps import apps
  2. from django.contrib import auth
  3. from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  4. from django.contrib.auth.hashers import make_password
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.core.exceptions import PermissionDenied
  7. from django.core.mail import send_mail
  8. from django.db import models
  9. from django.db.models.manager import EmptyManager
  10. from django.utils import timezone
  11. from django.utils.translation import gettext_lazy as _
  12. from .validators import UnicodeUsernameValidator
  13. def update_last_login(sender, user, **kwargs):
  14. """
  15. A signal receiver which updates the last_login date for
  16. the user logging in.
  17. """
  18. user.last_login = timezone.now()
  19. user.save(update_fields=['last_login'])
  20. class PermissionManager(models.Manager):
  21. use_in_migrations = True
  22. def get_by_natural_key(self, codename, app_label, model):
  23. return self.get(
  24. codename=codename,
  25. content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(app_label, model),
  26. )
  27. class Permission(models.Model):
  28. """
  29. The permissions system provides a way to assign permissions to specific
  30. users and groups of users.
  31. The permission system is used by the Django admin site, but may also be
  32. useful in your own code. The Django admin site uses permissions as follows:
  33. - The "add" permission limits the user's ability to view the "add" form
  34. and add an object.
  35. - The "change" permission limits a user's ability to view the change
  36. list, view the "change" form and change an object.
  37. - The "delete" permission limits the ability to delete an object.
  38. - The "view" permission limits the ability to view an object.
  39. Permissions are set globally per type of object, not per specific object
  40. instance. It is possible to say "Mary may change news stories," but it's
  41. not currently possible to say "Mary may change news stories, but only the
  42. ones she created herself" or "Mary may only change news stories that have a
  43. certain status or publication date."
  44. The permissions listed above are automatically created for each model.
  45. """
  46. name = models.CharField(_('name'), max_length=255)
  47. content_type = models.ForeignKey(
  48. ContentType,
  49. models.CASCADE,
  50. verbose_name=_('content type'),
  51. )
  52. codename = models.CharField(_('codename'), max_length=100)
  53. objects = PermissionManager()
  54. class Meta:
  55. verbose_name = _('permission')
  56. verbose_name_plural = _('permissions')
  57. unique_together = [['content_type', 'codename']]
  58. ordering = ['content_type__app_label', 'content_type__model', 'codename']
  59. def __str__(self):
  60. return '%s | %s' % (self.content_type, self.name)
  61. def natural_key(self):
  62. return (self.codename,) + self.content_type.natural_key()
  63. natural_key.dependencies = ['contenttypes.contenttype']
  64. class GroupManager(models.Manager):
  65. """
  66. The manager for the auth's Group model.
  67. """
  68. use_in_migrations = True
  69. def get_by_natural_key(self, name):
  70. return self.get(name=name)
  71. class Group(models.Model):
  72. """
  73. Groups are a generic way of categorizing users to apply permissions, or
  74. some other label, to those users. A user can belong to any number of
  75. groups.
  76. A user in a group automatically has all the permissions granted to that
  77. group. For example, if the group 'Site editors' has the permission
  78. can_edit_home_page, any user in that group will have that permission.
  79. Beyond permissions, groups are a convenient way to categorize users to
  80. apply some label, or extended functionality, to them. For example, you
  81. could create a group 'Special users', and you could write code that would
  82. do special things to those users -- such as giving them access to a
  83. members-only portion of your site, or sending them members-only email
  84. messages.
  85. """
  86. name = models.CharField(_('name'), max_length=150, unique=True)
  87. permissions = models.ManyToManyField(
  88. Permission,
  89. verbose_name=_('permissions'),
  90. blank=True,
  91. )
  92. objects = GroupManager()
  93. class Meta:
  94. verbose_name = _('group')
  95. verbose_name_plural = _('groups')
  96. def __str__(self):
  97. return self.name
  98. def natural_key(self):
  99. return (self.name,)
  100. class UserManager(BaseUserManager):
  101. use_in_migrations = True
  102. def _create_user(self, username, email, password, **extra_fields):
  103. """
  104. Create and save a user with the given username, email, and password.
  105. """
  106. if not username:
  107. raise ValueError('The given username must be set')
  108. email = self.normalize_email(email)
  109. # Lookup the real model class from the global app registry so this
  110. # manager method can be used in migrations. This is fine because
  111. # managers are by definition working on the real model.
  112. GlobalUserModel = apps.get_model(self.model._meta.app_label, self.model._meta.object_name)
  113. username = GlobalUserModel.normalize_username(username)
  114. user = self.model(username=username, email=email, **extra_fields)
  115. user.password = make_password(password)
  116. user.save(using=self._db)
  117. return user
  118. def create_user(self, username, email=None, password=None, **extra_fields):
  119. extra_fields.setdefault('is_staff', False)
  120. extra_fields.setdefault('is_superuser', False)
  121. return self._create_user(username, email, password, **extra_fields)
  122. def create_superuser(self, username, email=None, password=None, **extra_fields):
  123. extra_fields.setdefault('is_staff', True)
  124. extra_fields.setdefault('is_superuser', True)
  125. if extra_fields.get('is_staff') is not True:
  126. raise ValueError('Superuser must have is_staff=True.')
  127. if extra_fields.get('is_superuser') is not True:
  128. raise ValueError('Superuser must have is_superuser=True.')
  129. return self._create_user(username, email, password, **extra_fields)
  130. def with_perm(self, perm, is_active=True, include_superusers=True, backend=None, obj=None):
  131. if backend is None:
  132. backends = auth._get_backends(return_tuples=True)
  133. if len(backends) == 1:
  134. backend, _ = backends[0]
  135. else:
  136. raise ValueError(
  137. 'You have multiple authentication backends configured and '
  138. 'therefore must provide the `backend` argument.'
  139. )
  140. elif not isinstance(backend, str):
  141. raise TypeError(
  142. 'backend must be a dotted import path string (got %r).'
  143. % backend
  144. )
  145. else:
  146. backend = auth.load_backend(backend)
  147. if hasattr(backend, 'with_perm'):
  148. return backend.with_perm(
  149. perm,
  150. is_active=is_active,
  151. include_superusers=include_superusers,
  152. obj=obj,
  153. )
  154. return self.none()
  155. # A few helper functions for common logic between User and AnonymousUser.
  156. def _user_get_permissions(user, obj, from_name):
  157. permissions = set()
  158. name = 'get_%s_permissions' % from_name
  159. for backend in auth.get_backends():
  160. if hasattr(backend, name):
  161. permissions.update(getattr(backend, name)(user, obj))
  162. return permissions
  163. def _user_has_perm(user, perm, obj):
  164. """
  165. A backend can raise `PermissionDenied` to short-circuit permission checking.
  166. """
  167. for backend in auth.get_backends():
  168. if not hasattr(backend, 'has_perm'):
  169. continue
  170. try:
  171. if backend.has_perm(user, perm, obj):
  172. return True
  173. except PermissionDenied:
  174. return False
  175. return False
  176. def _user_has_module_perms(user, app_label):
  177. """
  178. A backend can raise `PermissionDenied` to short-circuit permission checking.
  179. """
  180. for backend in auth.get_backends():
  181. if not hasattr(backend, 'has_module_perms'):
  182. continue
  183. try:
  184. if backend.has_module_perms(user, app_label):
  185. return True
  186. except PermissionDenied:
  187. return False
  188. return False
  189. class PermissionsMixin(models.Model):
  190. """
  191. Add the fields and methods necessary to support the Group and Permission
  192. models using the ModelBackend.
  193. """
  194. is_superuser = models.BooleanField(
  195. _('superuser status'),
  196. default=False,
  197. help_text=_(
  198. 'Designates that this user has all permissions without '
  199. 'explicitly assigning them.'
  200. ),
  201. )
  202. groups = models.ManyToManyField(
  203. Group,
  204. verbose_name=_('groups'),
  205. blank=True,
  206. help_text=_(
  207. 'The groups this user belongs to. A user will get all permissions '
  208. 'granted to each of their groups.'
  209. ),
  210. related_name="user_set",
  211. related_query_name="user",
  212. )
  213. user_permissions = models.ManyToManyField(
  214. Permission,
  215. verbose_name=_('user permissions'),
  216. blank=True,
  217. help_text=_('Specific permissions for this user.'),
  218. related_name="user_set",
  219. related_query_name="user",
  220. )
  221. class Meta:
  222. abstract = True
  223. def get_user_permissions(self, obj=None):
  224. """
  225. Return a list of permission strings that this user has directly.
  226. Query all available auth backends. If an object is passed in,
  227. return only permissions matching this object.
  228. """
  229. return _user_get_permissions(self, obj, 'user')
  230. def get_group_permissions(self, obj=None):
  231. """
  232. Return a list of permission strings that this user has through their
  233. groups. Query all available auth backends. If an object is passed in,
  234. return only permissions matching this object.
  235. """
  236. return _user_get_permissions(self, obj, 'group')
  237. def get_all_permissions(self, obj=None):
  238. return _user_get_permissions(self, obj, 'all')
  239. def has_perm(self, perm, obj=None):
  240. """
  241. Return True if the user has the specified permission. Query all
  242. available auth backends, but return immediately if any backend returns
  243. True. Thus, a user who has permission from a single auth backend is
  244. assumed to have permission in general. If an object is provided, check
  245. permissions for that object.
  246. """
  247. # Active superusers have all permissions.
  248. if self.is_active and self.is_superuser:
  249. return True
  250. # Otherwise we need to check the backends.
  251. return _user_has_perm(self, perm, obj)
  252. def has_perms(self, perm_list, obj=None):
  253. """
  254. Return True if the user has each of the specified permissions. If
  255. object is passed, check if the user has all required perms for it.
  256. """
  257. return all(self.has_perm(perm, obj) for perm in perm_list)
  258. def has_module_perms(self, app_label):
  259. """
  260. Return True if the user has any permissions in the given app label.
  261. Use similar logic as has_perm(), above.
  262. """
  263. # Active superusers have all permissions.
  264. if self.is_active and self.is_superuser:
  265. return True
  266. return _user_has_module_perms(self, app_label)
  267. class AbstractUser(AbstractBaseUser, PermissionsMixin):
  268. """
  269. An abstract base class implementing a fully featured User model with
  270. admin-compliant permissions.
  271. Username and password are required. Other fields are optional.
  272. """
  273. username_validator = UnicodeUsernameValidator()
  274. username = models.CharField(
  275. _('username'),
  276. max_length=150,
  277. unique=True,
  278. help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
  279. validators=[username_validator],
  280. error_messages={
  281. 'unique': _("A user with that username already exists."),
  282. },
  283. )
  284. first_name = models.CharField(_('first name'), max_length=150, blank=True)
  285. last_name = models.CharField(_('last name'), max_length=150, blank=True)
  286. email = models.EmailField(_('email address'), blank=True)
  287. is_staff = models.BooleanField(
  288. _('staff status'),
  289. default=False,
  290. help_text=_('Designates whether the user can log into this admin site.'),
  291. )
  292. is_active = models.BooleanField(
  293. _('active'),
  294. default=True,
  295. help_text=_(
  296. 'Designates whether this user should be treated as active. '
  297. 'Unselect this instead of deleting accounts.'
  298. ),
  299. )
  300. date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
  301. objects = UserManager()
  302. EMAIL_FIELD = 'email'
  303. USERNAME_FIELD = 'username'
  304. REQUIRED_FIELDS = ['email']
  305. class Meta:
  306. verbose_name = _('user')
  307. verbose_name_plural = _('users')
  308. abstract = True
  309. def clean(self):
  310. super().clean()
  311. self.email = self.__class__.objects.normalize_email(self.email)
  312. def get_full_name(self):
  313. """
  314. Return the first_name plus the last_name, with a space in between.
  315. """
  316. full_name = '%s %s' % (self.first_name, self.last_name)
  317. return full_name.strip()
  318. def get_short_name(self):
  319. """Return the short name for the user."""
  320. return self.first_name
  321. def email_user(self, subject, message, from_email=None, **kwargs):
  322. """Send an email to this user."""
  323. send_mail(subject, message, from_email, [self.email], **kwargs)
  324. class User(AbstractUser):
  325. """
  326. Users within the Django authentication system are represented by this
  327. model.
  328. Username and password are required. Other fields are optional.
  329. """
  330. class Meta(AbstractUser.Meta):
  331. swappable = 'AUTH_USER_MODEL'
  332. class AnonymousUser:
  333. id = None
  334. pk = None
  335. username = ''
  336. is_staff = False
  337. is_active = False
  338. is_superuser = False
  339. _groups = EmptyManager(Group)
  340. _user_permissions = EmptyManager(Permission)
  341. def __str__(self):
  342. return 'AnonymousUser'
  343. def __eq__(self, other):
  344. return isinstance(other, self.__class__)
  345. def __hash__(self):
  346. return 1 # instances always return the same hash value
  347. def __int__(self):
  348. raise TypeError('Cannot cast AnonymousUser to int. Are you trying to use it in place of User?')
  349. def save(self):
  350. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  351. def delete(self):
  352. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  353. def set_password(self, raw_password):
  354. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  355. def check_password(self, raw_password):
  356. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  357. @property
  358. def groups(self):
  359. return self._groups
  360. @property
  361. def user_permissions(self):
  362. return self._user_permissions
  363. def get_user_permissions(self, obj=None):
  364. return _user_get_permissions(self, obj, 'user')
  365. def get_group_permissions(self, obj=None):
  366. return set()
  367. def get_all_permissions(self, obj=None):
  368. return _user_get_permissions(self, obj, 'all')
  369. def has_perm(self, perm, obj=None):
  370. return _user_has_perm(self, perm, obj=obj)
  371. def has_perms(self, perm_list, obj=None):
  372. return all(self.has_perm(perm, obj) for perm in perm_list)
  373. def has_module_perms(self, module):
  374. return _user_has_module_perms(self, module)
  375. @property
  376. def is_anonymous(self):
  377. return True
  378. @property
  379. def is_authenticated(self):
  380. return False
  381. def get_username(self):
  382. return self.username