django.contrib.auth.models: 244 total statements, 0.0% covered

Generated: Wed 2013-03-13 10:33 CET

Source file: /media/Envs/Envs/filer-gallery/lib/python2.7/site-packages/django/contrib/auth/models.py

Stats: 0 executed, 220 missed, 24 excluded, 232 ignored

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