Django

Code

root/django/branches/newforms-admin/django/contrib/auth/models.py

Revision 7953, 14.6 kB (checked in by brosner, 5 months ago)

newforms-admin: Moved contrib ModelAdmin? classes to an admin.py file in their respective apps. This is allowed since [7872].

  • Property svn:eol-style set to native
Line 
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)
95
96     class Meta:
97         verbose_name = _('group')
98         verbose_name_plural = _('groups')
99        
100     def __unicode__(self):
101         return self.name
102
103 class UserManager(models.Manager):
104     def create_user(self, username, email, password=None):
105         "Creates and saves a User with the given username, e-mail and password."
106         now = datetime.datetime.now()
107         user = self.model(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now)
108         if password:
109             user.set_password(password)
110         else:
111             user.set_unusable_password()
112         user.save()
113         return user
114
115     def create_superuser(self, username, email, password):
116         u = self.create_user(username, email, password)
117         u.is_staff = True
118         u.is_active = True
119         u.is_superuser = True
120         u.save()
121
122     def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
123         "Generates a random password with the given length and given allowed_chars"
124         # Note that default value of allowed_chars does not have "I" or letters
125         # that look like it -- just to avoid confusion.
126         from random import choice
127         return ''.join([choice(allowed_chars) for i in range(length)])
128
129 class User(models.Model):
130     """Users within the Django authentication system are represented by this model.
131
132     Username and password are required. Other fields are optional.
133     """
134     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)."))
135     first_name = models.CharField(_('first name'), max_length=30, blank=True)
136     last_name = models.CharField(_('last name'), max_length=30, blank=True)
137     email = models.EmailField(_('e-mail address'), blank=True)
138     password = models.CharField(_('password'), max_length=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>."))
139     is_staff = models.BooleanField(_('staff status'), default=False, help_text=_("Designates whether the user can log into this admin site."))
140     is_active = models.BooleanField(_('active'), default=True, help_text=_("Designates whether this user should be treated as active. Unselect this instead of deleting accounts."))
141     is_superuser = models.BooleanField(_('superuser status'), default=False, help_text=_("Designates that this user has all permissions without explicitly assigning them."))
142     last_login = models.DateTimeField(_('last login'), default=datetime.datetime.now)
143     date_joined = models.DateTimeField(_('date joined'), default=datetime.datetime.now)
144     groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True,
145         help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in."))
146     user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True)
147     objects = UserManager()
148
149     class Meta:
150         verbose_name = _('user')
151         verbose_name_plural = _('users')
152        
153     def __unicode__(self):
154         return self.username
155
156     def get_absolute_url(self):
157         return "/users/%s/" % urllib.quote(smart_str(self.username))
158
159     def is_anonymous(self):
160         "Always returns False. This is a way of comparing User objects to anonymous users."
161         return False
162
163     def is_authenticated(self):
164         """Always return True. This is a way to tell if the user has been authenticated in templates.
165         """
166         return True
167
168     def get_full_name(self):
169         "Returns the first_name plus the last_name, with a space in between."
170         full_name = u'%s %s' % (self.first_name, self.last_name)
171         return full_name.strip()
172
173     def set_password(self, raw_password):
174         import random
175         algo = 'sha1'
176         salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
177         hsh = get_hexdigest(algo, salt, raw_password)
178         self.password = '%s$%s$%s' % (algo, salt, hsh)
179
180     def check_password(self, raw_password):
181         """
182         Returns a boolean of whether the raw_password was correct. Handles
183         encryption formats behind the scenes.
184         """
185         # Backwards-compatibility check. Older passwords won't include the
186         # algorithm or salt.
187         if '$' not in self.password:
188             is_correct = (self.password == get_hexdigest('md5', '', raw_password))
189             if is_correct:
190                 # Convert the password to the new, more secure format.
191                 self.set_password(raw_password)
192                 self.save()
193             return is_correct
194         return check_password(raw_password, self.password)
195
196     def set_unusable_password(self):
197         # Sets a value that will never be a valid hash
198         self.password = UNUSABLE_PASSWORD
199
200     def has_usable_password(self):
201         return self.password != UNUSABLE_PASSWORD
202
203     def get_group_permissions(self):
204         """
205         Returns a list of permission strings that this user has through
206         his/her groups. This method queries all available auth backends.
207         """
208         permissions = set()
209         for backend in auth.get_backends():
210             if hasattr(backend, "get_group_permissions"):
211                 permissions.update(backend.get_group_permissions(self))
212         return permissions
213
214     def get_all_permissions(self):
215         permissions = set()
216         for backend in auth.get_backends():
217             if hasattr(backend, "get_all_permissions"):
218                 permissions.update(backend.get_all_permissions(self))
219         return permissions
220
221     def has_perm(self, perm):
222         """
223         Returns True if the user has the specified permission. This method
224         queries all available auth backends, but returns immediately if any
225         backend returns True. Thus, a user who has permission from a single
226         auth backend is assumed to have permission in general.
227         """
228         # Inactive users have no permissions.
229         if not self.is_active:
230             return False
231
232         # Superusers have all permissions.
233         if self.is_superuser:
234             return True
235
236         # Otherwise we need to check the backends.
237         for backend in auth.get_backends():
238             if hasattr(backend, "has_perm"):
239                 if backend.has_perm(self, perm):
240                     return True
241         return False
242
243     def has_perms(self, perm_list):
244         """Returns True if the user has each of the specified permissions."""
245         for perm in perm_list:
246             if not self.has_perm(perm):
247                 return False
248         return True
249
250     def has_module_perms(self, app_label):
251         """
252         Returns True if the user has any permissions in the given app
253         label. Uses pretty much the same logic as has_perm, above.
254         """
255         if not self.is_active:
256             return False
257
258         if self.is_superuser:
259             return True
260
261         for backend in auth.get_backends():
262             if hasattr(backend, "has_module_perms"):
263                 if backend.has_module_perms(self, app_label):
264                     return True
265         return False
266
267     def get_and_delete_messages(self):
268         messages = []
269         for m in self.message_set.all():
270             messages.append(m.message)
271             m.delete()
272         return messages
273
274     def email_user(self, subject, message, from_email=None):
275         "Sends an e-mail to this User."
276         from django.core.mail import send_mail
277         send_mail(subject, message, from_email, [self.email])
278
279     def get_profile(self):
280         """
281         Returns site-specific profile for this user. Raises
282         SiteProfileNotAvailable if this site does not allow profiles.
283         """
284         if not hasattr(self, '_profile_cache'):
285             from django.conf import settings
286             if not settings.AUTH_PROFILE_MODULE:
287                 raise SiteProfileNotAvailable
288             try:
289                 app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
290                 model = models.get_model(app_label, model_name)
291                 self._profile_cache = model._default_manager.get(user__id__exact=self.id)
292             except (ImportError, ImproperlyConfigured):
293                 raise SiteProfileNotAvailable
294         return self._profile_cache
295
296 class Message(models.Model):
297     """
298     The message system is a lightweight way to queue messages for given
299     users. A message is associated with a User instance (so it is only
300     applicable for registered users). There's no concept of expiration or
301     timestamps. Messages are created by the Django admin after successful
302     actions. For example, "The poll Foo was created successfully." is a
303     message.
304     """
305     user = models.ForeignKey(User)
306     message = models.TextField(_('message'))
307
308     def __unicode__(self):
309         return self.message
310
311 class AnonymousUser(object):
312     id = None
313     username = ''
314     is_staff = False
315     is_active = False
316     is_superuser = False
317     _groups = EmptyManager()
318     _user_permissions = EmptyManager()
319
320     def __init__(self):
321         pass
322
323     def __unicode__(self):
324         return 'AnonymousUser'
325
326     def __str__(self):
327         return unicode(self).encode('utf-8')
328
329     def __eq__(self, other):
330         return isinstance(other, self.__class__)
331
332     def __ne__(self, other):
333         return not self.__eq__(other)
334
335     def __hash__(self):
336         return 1 # instances always return the same hash value
337
338     def save(self):
339         raise NotImplementedError
340
341     def delete(self):
342         raise NotImplementedError
343
344     def set_password(self, raw_password):
345         raise NotImplementedError
346
347     def check_password(self, raw_password):
348         raise NotImplementedError
349
350     def _get_groups(self):
351         return self._groups
352     groups = property(_get_groups)
353
354     def _get_user_permissions(self):
355         return self._user_permissions
356     user_permissions = property(_get_user_permissions)
357
358     def has_perm(self, perm):
359         return False
360
361     def has_module_perms(self, module):
362         return False
363
364     def get_and_delete_messages(self):
365         return []
366
367     def is_anonymous(self):
368         return True
369
370     def is_authenticated(self):
371         return False
Note: See TracBrowser for help on using the browser.