Package django :: Package contrib :: Package auth :: Module models
[hide private]
[frames] | no frames]

Source Code for Module django.contrib.auth.models

  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