models.py 14 KB

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