models.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. from __future__ import unicode_literals
  2. from django.core.mail import send_mail
  3. from django.core import validators
  4. from django.db import models
  5. from django.db.models.manager import EmptyManager
  6. from django.utils.crypto import get_random_string, salted_hmac
  7. from django.utils import six
  8. from django.utils.translation import ugettext_lazy as _
  9. from django.utils import timezone
  10. from django.contrib import auth
  11. from django.contrib.auth.hashers import (
  12. check_password, make_password, is_password_usable)
  13. from django.contrib.auth.signals import user_logged_in
  14. from django.contrib.contenttypes.models import ContentType
  15. from django.utils.encoding import python_2_unicode_compatible
  16. def update_last_login(sender, user, **kwargs):
  17. """
  18. A signal receiver which updates the last_login date for
  19. the user logging in.
  20. """
  21. user.last_login = timezone.now()
  22. user.save(update_fields=['last_login'])
  23. user_logged_in.connect(update_last_login)
  24. class PermissionManager(models.Manager):
  25. def get_by_natural_key(self, codename, app_label, model):
  26. return self.get(
  27. codename=codename,
  28. content_type=ContentType.objects.get_by_natural_key(app_label,
  29. model),
  30. )
  31. @python_2_unicode_compatible
  32. class Permission(models.Model):
  33. """
  34. The permissions system provides a way to assign permissions to specific
  35. users and groups of users.
  36. The permission system is used by the Django admin site, but may also be
  37. useful in your own code. The Django admin site uses permissions as follows:
  38. - The "add" permission limits the user's ability to view the "add" form
  39. and add an object.
  40. - The "change" permission limits a user's ability to view the change
  41. list, view the "change" form and change an object.
  42. - The "delete" permission limits the ability to delete an object.
  43. Permissions are set globally per type of object, not per specific object
  44. instance. It is possible to say "Mary may change news stories," but it's
  45. not currently possible to say "Mary may change news stories, but only the
  46. ones she created herself" or "Mary may only change news stories that have a
  47. certain status or publication date."
  48. Three basic permissions -- add, change and delete -- are automatically
  49. created for each Django model.
  50. """
  51. name = models.CharField(_('name'), max_length=50)
  52. content_type = models.ForeignKey(ContentType)
  53. codename = models.CharField(_('codename'), max_length=100)
  54. objects = PermissionManager()
  55. class Meta:
  56. verbose_name = _('permission')
  57. verbose_name_plural = _('permissions')
  58. unique_together = (('content_type', 'codename'),)
  59. ordering = ('content_type__app_label', 'content_type__model',
  60. 'codename')
  61. def __str__(self):
  62. return "%s | %s | %s" % (
  63. six.text_type(self.content_type.app_label),
  64. six.text_type(self.content_type),
  65. six.text_type(self.name))
  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. def get_by_natural_key(self, name):
  74. return self.get(name=name)
  75. @python_2_unicode_compatible
  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(Permission,
  93. verbose_name=_('permissions'), blank=True)
  94. objects = GroupManager()
  95. class Meta:
  96. verbose_name = _('group')
  97. verbose_name_plural = _('groups')
  98. def __str__(self):
  99. return self.name
  100. def natural_key(self):
  101. return (self.name,)
  102. class BaseUserManager(models.Manager):
  103. @classmethod
  104. def normalize_email(cls, email):
  105. """
  106. Normalize the address by lowercasing the domain part of the email
  107. address.
  108. """
  109. email = email or ''
  110. try:
  111. email_name, domain_part = email.strip().rsplit('@', 1)
  112. except ValueError:
  113. pass
  114. else:
  115. email = '@'.join([email_name, domain_part.lower()])
  116. return email
  117. def make_random_password(self, length=10,
  118. allowed_chars='abcdefghjkmnpqrstuvwxyz'
  119. 'ABCDEFGHJKLMNPQRSTUVWXYZ'
  120. '23456789'):
  121. """
  122. Generates a random password with the given length and given
  123. allowed_chars. Note that the default value of allowed_chars does not
  124. have "I" or "O" or letters and digits that look similar -- just to
  125. avoid confusion.
  126. """
  127. return get_random_string(length, allowed_chars)
  128. def get_by_natural_key(self, username):
  129. return self.get(**{self.model.USERNAME_FIELD: username})
  130. class UserManager(BaseUserManager):
  131. def _create_user(self, username, email, password,
  132. is_staff, is_superuser, **extra_fields):
  133. """
  134. Creates and saves a User with the given username, email and password.
  135. """
  136. now = timezone.now()
  137. if not username:
  138. raise ValueError('The given username must be set')
  139. email = self.normalize_email(email)
  140. user = self.model(username=username, email=email,
  141. is_staff=is_staff, is_active=True,
  142. is_superuser=is_superuser, last_login=now,
  143. date_joined=now, **extra_fields)
  144. user.set_password(password)
  145. user.save(using=self._db)
  146. return user
  147. def create_user(self, username, email=None, password=None, **extra_fields):
  148. return self._create_user(username, email, password, False, False,
  149. **extra_fields)
  150. def create_superuser(self, username, email, password, **extra_fields):
  151. return self._create_user(username, email, password, True, True,
  152. **extra_fields)
  153. @python_2_unicode_compatible
  154. class AbstractBaseUser(models.Model):
  155. password = models.CharField(_('password'), max_length=128)
  156. last_login = models.DateTimeField(_('last login'), default=timezone.now)
  157. is_active = True
  158. REQUIRED_FIELDS = []
  159. class Meta:
  160. abstract = True
  161. def get_username(self):
  162. "Return the identifying username for this User"
  163. return getattr(self, self.USERNAME_FIELD)
  164. def __str__(self):
  165. return self.get_username()
  166. def natural_key(self):
  167. return (self.get_username(),)
  168. def is_anonymous(self):
  169. """
  170. Always returns False. This is a way of comparing User objects to
  171. anonymous users.
  172. """
  173. return False
  174. def is_authenticated(self):
  175. """
  176. Always return True. This is a way to tell if the user has been
  177. authenticated in templates.
  178. """
  179. return True
  180. def set_password(self, raw_password):
  181. self.password = make_password(raw_password)
  182. def check_password(self, raw_password):
  183. """
  184. Returns a boolean of whether the raw_password was correct. Handles
  185. hashing formats behind the scenes.
  186. """
  187. def setter(raw_password):
  188. self.set_password(raw_password)
  189. self.save(update_fields=["password"])
  190. return check_password(raw_password, self.password, setter)
  191. def set_unusable_password(self):
  192. # Sets a value that will never be a valid hash
  193. self.password = make_password(None)
  194. def has_usable_password(self):
  195. return is_password_usable(self.password)
  196. def get_full_name(self):
  197. raise NotImplementedError('subclasses of AbstractBaseUser must provide a get_full_name() method')
  198. def get_short_name(self):
  199. raise NotImplementedError('subclasses of AbstractBaseUser must provide a get_short_name() method.')
  200. def get_session_auth_hash(self):
  201. """
  202. Returns an HMAC of the password field.
  203. """
  204. key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
  205. return salted_hmac(key_salt, self.password).hexdigest()
  206. # A few helper functions for common logic between User and AnonymousUser.
  207. def _user_get_all_permissions(user, obj):
  208. permissions = set()
  209. for backend in auth.get_backends():
  210. if hasattr(backend, "get_all_permissions"):
  211. permissions.update(backend.get_all_permissions(user, obj))
  212. return permissions
  213. def _user_has_perm(user, perm, obj):
  214. for backend in auth.get_backends():
  215. if hasattr(backend, "has_perm"):
  216. if backend.has_perm(user, perm, obj):
  217. return True
  218. return False
  219. def _user_has_module_perms(user, app_label):
  220. for backend in auth.get_backends():
  221. if hasattr(backend, "has_module_perms"):
  222. if backend.has_module_perms(user, app_label):
  223. return True
  224. return False
  225. class PermissionsMixin(models.Model):
  226. """
  227. A mixin class that adds the fields and methods necessary to support
  228. Django's Group and Permission model using the ModelBackend.
  229. """
  230. is_superuser = models.BooleanField(_('superuser status'), default=False,
  231. help_text=_('Designates that this user has all permissions without '
  232. 'explicitly assigning them.'))
  233. groups = models.ManyToManyField(Group, verbose_name=_('groups'),
  234. blank=True, help_text=_('The groups this user belongs to. A user will '
  235. 'get all permissions granted to each of '
  236. 'his/her group.'),
  237. related_name="user_set", related_query_name="user")
  238. user_permissions = models.ManyToManyField(Permission,
  239. verbose_name=_('user permissions'), blank=True,
  240. help_text=_('Specific permissions for this user.'),
  241. related_name="user_set", related_query_name="user")
  242. class Meta:
  243. abstract = True
  244. def get_group_permissions(self, obj=None):
  245. """
  246. Returns a list of permission strings that this user has through their
  247. groups. This method queries all available auth backends. If an object
  248. is passed in, only permissions matching this object are returned.
  249. """
  250. permissions = set()
  251. for backend in auth.get_backends():
  252. if hasattr(backend, "get_group_permissions"):
  253. permissions.update(backend.get_group_permissions(self, obj))
  254. return permissions
  255. def get_all_permissions(self, obj=None):
  256. return _user_get_all_permissions(self, obj)
  257. def has_perm(self, perm, obj=None):
  258. """
  259. Returns True if the user has the specified permission. This method
  260. queries all available auth backends, but returns immediately if any
  261. backend returns True. Thus, a user who has permission from a single
  262. auth backend is assumed to have permission in general. If an object is
  263. provided, permissions for this specific object are checked.
  264. """
  265. # Active superusers have all permissions.
  266. if self.is_active and self.is_superuser:
  267. return True
  268. # Otherwise we need to check the backends.
  269. return _user_has_perm(self, perm, obj)
  270. def has_perms(self, perm_list, obj=None):
  271. """
  272. Returns True if the user has each of the specified permissions. If
  273. object is passed, it checks if the user has all required perms for this
  274. object.
  275. """
  276. for perm in perm_list:
  277. if not self.has_perm(perm, obj):
  278. return False
  279. return True
  280. def has_module_perms(self, app_label):
  281. """
  282. Returns True if the user has any permissions in the given app label.
  283. Uses pretty much the same logic as has_perm, above.
  284. """
  285. # Active superusers have all permissions.
  286. if self.is_active and self.is_superuser:
  287. return True
  288. return _user_has_module_perms(self, app_label)
  289. class AbstractUser(AbstractBaseUser, PermissionsMixin):
  290. """
  291. An abstract base class implementing a fully featured User model with
  292. admin-compliant permissions.
  293. Username, password and email are required. Other fields are optional.
  294. """
  295. username = models.CharField(_('username'), max_length=30, unique=True,
  296. help_text=_('Required. 30 characters or fewer. Letters, digits and '
  297. '@/./+/-/_ only.'),
  298. validators=[
  299. validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid')
  300. ])
  301. first_name = models.CharField(_('first name'), max_length=30, blank=True)
  302. last_name = models.CharField(_('last name'), max_length=30, blank=True)
  303. email = models.EmailField(_('email address'), blank=True)
  304. is_staff = models.BooleanField(_('staff status'), default=False,
  305. help_text=_('Designates whether the user can log into this admin '
  306. 'site.'))
  307. is_active = models.BooleanField(_('active'), default=True,
  308. help_text=_('Designates whether this user should be treated as '
  309. 'active. Unselect this instead of deleting accounts.'))
  310. date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
  311. objects = UserManager()
  312. USERNAME_FIELD = 'username'
  313. REQUIRED_FIELDS = ['email']
  314. class Meta:
  315. verbose_name = _('user')
  316. verbose_name_plural = _('users')
  317. abstract = True
  318. def get_full_name(self):
  319. """
  320. Returns the first_name plus the last_name, with a space in between.
  321. """
  322. full_name = '%s %s' % (self.first_name, self.last_name)
  323. return full_name.strip()
  324. def get_short_name(self):
  325. "Returns the short name for the user."
  326. return self.first_name
  327. def email_user(self, subject, message, from_email=None, **kwargs):
  328. """
  329. Sends an email to this User.
  330. """
  331. send_mail(subject, message, from_email, [self.email], **kwargs)
  332. class User(AbstractUser):
  333. """
  334. Users within the Django authentication system are represented by this
  335. model.
  336. Username, password and email are required. Other fields are optional.
  337. """
  338. class Meta(AbstractUser.Meta):
  339. swappable = 'AUTH_USER_MODEL'
  340. @python_2_unicode_compatible
  341. class AnonymousUser(object):
  342. id = None
  343. pk = None
  344. username = ''
  345. is_staff = False
  346. is_active = False
  347. is_superuser = False
  348. _groups = EmptyManager(Group)
  349. _user_permissions = EmptyManager(Permission)
  350. def __init__(self):
  351. pass
  352. def __str__(self):
  353. return 'AnonymousUser'
  354. def __eq__(self, other):
  355. return isinstance(other, self.__class__)
  356. def __ne__(self, other):
  357. return not self.__eq__(other)
  358. def __hash__(self):
  359. return 1 # instances always return the same hash value
  360. def save(self):
  361. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  362. def delete(self):
  363. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  364. def set_password(self, raw_password):
  365. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  366. def check_password(self, raw_password):
  367. raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
  368. def _get_groups(self):
  369. return self._groups
  370. groups = property(_get_groups)
  371. def _get_user_permissions(self):
  372. return self._user_permissions
  373. user_permissions = property(_get_user_permissions)
  374. def get_group_permissions(self, obj=None):
  375. return set()
  376. def get_all_permissions(self, obj=None):
  377. return _user_get_all_permissions(self, obj=obj)
  378. def has_perm(self, perm, obj=None):
  379. return _user_has_perm(self, perm, obj=obj)
  380. def has_perms(self, perm_list, obj=None):
  381. for perm in perm_list:
  382. if not self.has_perm(perm, obj):
  383. return False
  384. return True
  385. def has_module_perms(self, module):
  386. return _user_has_module_perms(self, module)
  387. def is_anonymous(self):
  388. return True
  389. def is_authenticated(self):
  390. return False