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