PageRenderTime 59ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/auth/models.py

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