You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

449 lines
14 KiB

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