app/django/contrib/auth/models.py
changeset 54 03e267d67478
child 323 ff1a9aa48cfd
equal deleted inserted replaced
53:57b4279d8c4e 54:03e267d67478
       
     1 from django.contrib import auth
       
     2 from django.core import validators
       
     3 from django.core.exceptions import ImproperlyConfigured
       
     4 from django.db import models
       
     5 from django.db.models.manager import EmptyManager
       
     6 from django.contrib.contenttypes.models import ContentType
       
     7 from django.utils.encoding import smart_str
       
     8 from django.utils.translation import ugettext_lazy as _
       
     9 import datetime
       
    10 import urllib
       
    11 
       
    12 UNUSABLE_PASSWORD = '!' # This will never be a valid hash
       
    13 
       
    14 try:
       
    15     set
       
    16 except NameError:
       
    17     from sets import Set as set   # Python 2.3 fallback
       
    18 
       
    19 def get_hexdigest(algorithm, salt, raw_password):
       
    20     """
       
    21     Returns a string of the hexdigest of the given plaintext password and salt
       
    22     using the given algorithm ('md5', 'sha1' or 'crypt').
       
    23     """
       
    24     raw_password, salt = smart_str(raw_password), smart_str(salt)
       
    25     if algorithm == 'crypt':
       
    26         try:
       
    27             import crypt
       
    28         except ImportError:
       
    29             raise ValueError('"crypt" password algorithm not supported in this environment')
       
    30         return crypt.crypt(raw_password, salt)
       
    31     # The rest of the supported algorithms are supported by hashlib, but
       
    32     # hashlib is only available in Python 2.5.
       
    33     try:
       
    34         import hashlib
       
    35     except ImportError:
       
    36         if algorithm == 'md5':
       
    37             import md5
       
    38             return md5.new(salt + raw_password).hexdigest()
       
    39         elif algorithm == 'sha1':
       
    40             import sha
       
    41             return sha.new(salt + raw_password).hexdigest()
       
    42     else:
       
    43         if algorithm == 'md5':
       
    44             return hashlib.md5(salt + raw_password).hexdigest()
       
    45         elif algorithm == 'sha1':
       
    46             return hashlib.sha1(salt + raw_password).hexdigest()
       
    47     raise ValueError("Got unknown password algorithm type in password.")
       
    48 
       
    49 def check_password(raw_password, enc_password):
       
    50     """
       
    51     Returns a boolean of whether the raw_password was correct. Handles
       
    52     encryption formats behind the scenes.
       
    53     """
       
    54     algo, salt, hsh = enc_password.split('$')
       
    55     return hsh == get_hexdigest(algo, salt, raw_password)
       
    56 
       
    57 class SiteProfileNotAvailable(Exception):
       
    58     pass
       
    59 
       
    60 class Permission(models.Model):
       
    61     """The permissions system provides a way to assign permissions to specific users and groups of users.
       
    62 
       
    63     The permission system is used by the Django admin site, but may also be useful in your own code. The Django admin site uses permissions as follows:
       
    64 
       
    65         - The "add" permission limits the user's ability to view the "add" form and add an object.
       
    66         - The "change" permission limits a user's ability to view the change list, view the "change" form and change an object.
       
    67         - The "delete" permission limits the ability to delete an object.
       
    68 
       
    69     Permissions are set globally per type of object, not per specific object instance. It is possible to say "Mary may change news stories," but it's not currently possible to say "Mary may change news stories, but only the ones she created herself" or "Mary may only change news stories that have a certain status or publication date."
       
    70 
       
    71     Three basic permissions -- add, change and delete -- are automatically created for each Django model.
       
    72     """
       
    73     name = models.CharField(_('name'), max_length=50)
       
    74     content_type = models.ForeignKey(ContentType)
       
    75     codename = models.CharField(_('codename'), max_length=100)
       
    76 
       
    77     class Meta:
       
    78         verbose_name = _('permission')
       
    79         verbose_name_plural = _('permissions')
       
    80         unique_together = (('content_type', 'codename'),)
       
    81         ordering = ('content_type', 'codename')
       
    82 
       
    83     def __unicode__(self):
       
    84         return u"%s | %s | %s" % (self.content_type.app_label, self.content_type, self.name)
       
    85 
       
    86 class Group(models.Model):
       
    87     """Groups are a generic way of categorizing users to apply permissions, or some other label, to those users. A user can belong to any number of groups.
       
    88 
       
    89     A user in a group automatically has all the permissions granted to that group. For example, if the group Site editors has the permission can_edit_home_page, any user in that group will have that permission.
       
    90 
       
    91     Beyond permissions, groups are a convenient way to categorize users to apply some label, or extended functionality, to them. For example, you could create a group 'Special users', and you could write code that would do special things to those users -- such as giving them access to a members-only portion of your site, or sending them members-only e-mail messages.
       
    92     """
       
    93     name = models.CharField(_('name'), max_length=80, unique=True)
       
    94     permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True, filter_interface=models.HORIZONTAL)
       
    95 
       
    96     class Meta:
       
    97         verbose_name = _('group')
       
    98         verbose_name_plural = _('groups')
       
    99         ordering = ('name',)
       
   100 
       
   101     class Admin:
       
   102         search_fields = ('name',)
       
   103 
       
   104     def __unicode__(self):
       
   105         return self.name
       
   106 
       
   107 class UserManager(models.Manager):
       
   108     def create_user(self, username, email, password=None):
       
   109         "Creates and saves a User with the given username, e-mail and password."
       
   110         now = datetime.datetime.now()
       
   111         user = self.model(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now)
       
   112         if password:
       
   113             user.set_password(password)
       
   114         else:
       
   115             user.set_unusable_password()
       
   116         user.save()
       
   117         return user
       
   118 
       
   119     def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
       
   120         "Generates a random password with the given length and given allowed_chars"
       
   121         # Note that default value of allowed_chars does not have "I" or letters
       
   122         # that look like it -- just to avoid confusion.
       
   123         from random import choice
       
   124         return ''.join([choice(allowed_chars) for i in range(length)])
       
   125 
       
   126 class User(models.Model):
       
   127     """Users within the Django authentication system are represented by this model.
       
   128 
       
   129     Username and password are required. Other fields are optional.
       
   130     """
       
   131     username = models.CharField(_('username'), max_length=30, unique=True, validator_list=[validators.isAlphaNumeric], help_text=_("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."))
       
   132     first_name = models.CharField(_('first name'), max_length=30, blank=True)
       
   133     last_name = models.CharField(_('last name'), max_length=30, blank=True)
       
   134     email = models.EmailField(_('e-mail address'), blank=True)
       
   135     password = models.CharField(_('password'), max_length=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>."))
       
   136     is_staff = models.BooleanField(_('staff status'), default=False, help_text=_("Designates whether the user can log into this admin site."))
       
   137     is_active = models.BooleanField(_('active'), default=True, help_text=_("Designates whether this user should be treated as active. Unselect this instead of deleting accounts."))
       
   138     is_superuser = models.BooleanField(_('superuser status'), default=False, help_text=_("Designates that this user has all permissions without explicitly assigning them."))
       
   139     last_login = models.DateTimeField(_('last login'), default=datetime.datetime.now)
       
   140     date_joined = models.DateTimeField(_('date joined'), default=datetime.datetime.now)
       
   141     groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True,
       
   142         help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in."))
       
   143     user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True, filter_interface=models.HORIZONTAL)
       
   144     objects = UserManager()
       
   145 
       
   146     class Meta:
       
   147         verbose_name = _('user')
       
   148         verbose_name_plural = _('users')
       
   149         ordering = ('username',)
       
   150 
       
   151     class Admin:
       
   152         fields = (
       
   153             (None, {'fields': ('username', 'password')}),
       
   154             (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
       
   155             (_('Permissions'), {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}),
       
   156             (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
       
   157             (_('Groups'), {'fields': ('groups',)}),
       
   158         )
       
   159         list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
       
   160         list_filter = ('is_staff', 'is_superuser')
       
   161         search_fields = ('username', 'first_name', 'last_name', 'email')
       
   162 
       
   163     def __unicode__(self):
       
   164         return self.username
       
   165 
       
   166     def get_absolute_url(self):
       
   167         return "/users/%s/" % urllib.quote(smart_str(self.username))
       
   168 
       
   169     def is_anonymous(self):
       
   170         "Always returns False. This is a way of comparing User objects to anonymous users."
       
   171         return False
       
   172 
       
   173     def is_authenticated(self):
       
   174         """Always return True. This is a way to tell if the user has been authenticated in templates.
       
   175         """
       
   176         return True
       
   177 
       
   178     def get_full_name(self):
       
   179         "Returns the first_name plus the last_name, with a space in between."
       
   180         full_name = u'%s %s' % (self.first_name, self.last_name)
       
   181         return full_name.strip()
       
   182 
       
   183     def set_password(self, raw_password):
       
   184         import random
       
   185         algo = 'sha1'
       
   186         salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
       
   187         hsh = get_hexdigest(algo, salt, raw_password)
       
   188         self.password = '%s$%s$%s' % (algo, salt, hsh)
       
   189 
       
   190     def check_password(self, raw_password):
       
   191         """
       
   192         Returns a boolean of whether the raw_password was correct. Handles
       
   193         encryption formats behind the scenes.
       
   194         """
       
   195         # Backwards-compatibility check. Older passwords won't include the
       
   196         # algorithm or salt.
       
   197         if '$' not in self.password:
       
   198             is_correct = (self.password == get_hexdigest('md5', '', raw_password))
       
   199             if is_correct:
       
   200                 # Convert the password to the new, more secure format.
       
   201                 self.set_password(raw_password)
       
   202                 self.save()
       
   203             return is_correct
       
   204         return check_password(raw_password, self.password)
       
   205 
       
   206     def set_unusable_password(self):
       
   207         # Sets a value that will never be a valid hash
       
   208         self.password = UNUSABLE_PASSWORD
       
   209 
       
   210     def has_usable_password(self):
       
   211         return self.password != UNUSABLE_PASSWORD
       
   212 
       
   213     def get_group_permissions(self):
       
   214         """
       
   215         Returns a list of permission strings that this user has through
       
   216         his/her groups. This method queries all available auth backends.
       
   217         """
       
   218         permissions = set()
       
   219         for backend in auth.get_backends():
       
   220             if hasattr(backend, "get_group_permissions"):
       
   221                 permissions.update(backend.get_group_permissions(self))
       
   222         return permissions
       
   223 
       
   224     def get_all_permissions(self):
       
   225         permissions = set()
       
   226         for backend in auth.get_backends():
       
   227             if hasattr(backend, "get_all_permissions"):
       
   228                 permissions.update(backend.get_all_permissions(self))
       
   229         return permissions
       
   230 
       
   231     def has_perm(self, perm):
       
   232         """
       
   233         Returns True if the user has the specified permission. This method
       
   234         queries all available auth backends, but returns immediately if any
       
   235         backend returns True. Thus, a user who has permission from a single
       
   236         auth backend is assumed to have permission in general.
       
   237         """
       
   238         # Inactive users have no permissions.
       
   239         if not self.is_active:
       
   240             return False
       
   241 
       
   242         # Superusers have all permissions.
       
   243         if self.is_superuser:
       
   244             return True
       
   245 
       
   246         # Otherwise we need to check the backends.
       
   247         for backend in auth.get_backends():
       
   248             if hasattr(backend, "has_perm"):
       
   249                 if backend.has_perm(self, perm):
       
   250                     return True
       
   251         return False
       
   252 
       
   253     def has_perms(self, perm_list):
       
   254         """Returns True if the user has each of the specified permissions."""
       
   255         for perm in perm_list:
       
   256             if not self.has_perm(perm):
       
   257                 return False
       
   258         return True
       
   259 
       
   260     def has_module_perms(self, app_label):
       
   261         """
       
   262         Returns True if the user has any permissions in the given app
       
   263         label. Uses pretty much the same logic as has_perm, above.
       
   264         """
       
   265         if not self.is_active:
       
   266             return False
       
   267 
       
   268         if self.is_superuser:
       
   269             return True
       
   270 
       
   271         for backend in auth.get_backends():
       
   272             if hasattr(backend, "has_module_perms"):
       
   273                 if backend.has_module_perms(self, app_label):
       
   274                     return True
       
   275         return False
       
   276 
       
   277     def get_and_delete_messages(self):
       
   278         messages = []
       
   279         for m in self.message_set.all():
       
   280             messages.append(m.message)
       
   281             m.delete()
       
   282         return messages
       
   283 
       
   284     def email_user(self, subject, message, from_email=None):
       
   285         "Sends an e-mail to this User."
       
   286         from django.core.mail import send_mail
       
   287         send_mail(subject, message, from_email, [self.email])
       
   288 
       
   289     def get_profile(self):
       
   290         """
       
   291         Returns site-specific profile for this user. Raises
       
   292         SiteProfileNotAvailable if this site does not allow profiles.
       
   293         """
       
   294         if not hasattr(self, '_profile_cache'):
       
   295             from django.conf import settings
       
   296             if not settings.AUTH_PROFILE_MODULE:
       
   297                 raise SiteProfileNotAvailable
       
   298             try:
       
   299                 app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
       
   300                 model = models.get_model(app_label, model_name)
       
   301                 self._profile_cache = model._default_manager.get(user__id__exact=self.id)
       
   302             except (ImportError, ImproperlyConfigured):
       
   303                 raise SiteProfileNotAvailable
       
   304         return self._profile_cache
       
   305 
       
   306 class Message(models.Model):
       
   307     """
       
   308     The message system is a lightweight way to queue messages for given
       
   309     users. A message is associated with a User instance (so it is only
       
   310     applicable for registered users). There's no concept of expiration or
       
   311     timestamps. Messages are created by the Django admin after successful
       
   312     actions. For example, "The poll Foo was created successfully." is a
       
   313     message.
       
   314     """
       
   315     user = models.ForeignKey(User)
       
   316     message = models.TextField(_('message'))
       
   317 
       
   318     def __unicode__(self):
       
   319         return self.message
       
   320 
       
   321 class AnonymousUser(object):
       
   322     id = None
       
   323     username = ''
       
   324     is_staff = False
       
   325     is_active = False
       
   326     is_superuser = False
       
   327     _groups = EmptyManager()
       
   328     _user_permissions = EmptyManager()
       
   329 
       
   330     def __init__(self):
       
   331         pass
       
   332 
       
   333     def __unicode__(self):
       
   334         return 'AnonymousUser'
       
   335 
       
   336     def __str__(self):
       
   337         return unicode(self).encode('utf-8')
       
   338 
       
   339     def __eq__(self, other):
       
   340         return isinstance(other, self.__class__)
       
   341 
       
   342     def __ne__(self, other):
       
   343         return not self.__eq__(other)
       
   344 
       
   345     def __hash__(self):
       
   346         return 1 # instances always return the same hash value
       
   347 
       
   348     def save(self):
       
   349         raise NotImplementedError
       
   350 
       
   351     def delete(self):
       
   352         raise NotImplementedError
       
   353 
       
   354     def set_password(self, raw_password):
       
   355         raise NotImplementedError
       
   356 
       
   357     def check_password(self, raw_password):
       
   358         raise NotImplementedError
       
   359 
       
   360     def _get_groups(self):
       
   361         return self._groups
       
   362     groups = property(_get_groups)
       
   363 
       
   364     def _get_user_permissions(self):
       
   365         return self._user_permissions
       
   366     user_permissions = property(_get_user_permissions)
       
   367 
       
   368     def has_perm(self, perm):
       
   369         return False
       
   370 
       
   371     def has_module_perms(self, module):
       
   372         return False
       
   373 
       
   374     def get_and_delete_messages(self):
       
   375         return []
       
   376 
       
   377     def is_anonymous(self):
       
   378         return True
       
   379 
       
   380     def is_authenticated(self):
       
   381         return False