models.py 16 KB

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