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 = '!'
13
14 try:
15 set
16 except NameError:
17 from sets import Set as set
18
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
32
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
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
59
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
82
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
100
103
106
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
122
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 can log into the Django admin. 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
150
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
165
168
170 "Always returns False. This is a way of comparing User objects to anonymous users."
171 return False
172
174 """Always return True. This is a way to tell if the user has been authenticated in templates.
175 """
176 return True
177
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
189
191 """
192 Returns a boolean of whether the raw_password was correct. Handles
193 encryption formats behind the scenes.
194 """
195
196
197 if '$' not in self.password:
198 is_correct = (self.password == get_hexdigest('md5', '', raw_password))
199 if is_correct:
200
201 self.set_password(raw_password)
202 self.save()
203 return is_correct
204 return check_password(raw_password, self.password)
205
209
212
223
230
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
239 if not self.is_active:
240 return False
241
242
243 if self.is_superuser:
244 return True
245
246
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
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
276
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):
288
305
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
320
382