Guest User

bino: l2auth (Second Level Auth) Models

a guest
Feb 21st, 2013
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.64 KB | None | 0 0
  1. import urllib
  2.  
  3. from django.core.exceptions import ImproperlyConfigured
  4. from django.core.mail import send_mail
  5. from django.db import models
  6. from django.db.models.manager import EmptyManager
  7. from django.utils.crypto import get_random_string
  8. from django.utils.encoding import smart_str
  9. from django.utils.translation import ugettext_lazy as _
  10. from django.utils import timezone
  11.  
  12. from django.contrib import auth
  13. # UNUSABLE_PASSWORD is still imported here for backwards compatibility
  14. from django.contrib.auth.hashers import (
  15.     check_password, make_password, is_password_usable, UNUSABLE_PASSWORD)
  16. from django.contrib.auth.signals import user_logged_in
  17. from django.contrib.auth.models import Permission, PermissionManager
  18. from django.contrib.contenttypes.models import ContentType
  19. # Create your models here.
  20.  
  21. #First, Modified the auth_permission table
  22. isdelegate = models.BooleanField('L2 Delegate', default=False)
  23. isdelegate.contribute_to_class(Permission, 'isdelegate')
  24.  
  25. class L2Company(models.Model):
  26.     BUSINESS_TYPE_CHOICE = (
  27.         (1, 'Mobile Network'),
  28.         (2, 'Site Provider'),
  29.         (3, 'Maintenance Prov.'),
  30.     )
  31.    
  32.     company_code = models.CharField('Short Name', max_length = 10, blank=False, unique=True, help_text="lowercase, allowed : a-z, 0-9, _")
  33.     is_active = models.BooleanField(default=True)
  34.     btype = models.IntegerField('Bussiness Type', default=1, choices=BUSINESS_TYPE_CHOICE)
  35.     def __unicode__(self):
  36.         return self.company_code
  37.     class Meta:
  38.         verbose_name_plural = "companies"
  39.  
  40. def L2update_last_login(sender, l2user, **kwargs):
  41.     """
  42.    A signal receiver which updates the last_login date for
  43.    the user logging in.
  44.    """
  45.     l2user.last_login = timezone.now()
  46.     l2user.save()
  47.  
  48. #user_logged_in.connect(update_last_login)
  49.  
  50.  
  51. class SiteProfileNotAvailable(Exception):
  52.     pass
  53.  
  54. class L2UserManager(models.Manager):
  55.  
  56.     @classmethod
  57.     def normalize_email(cls, email):
  58.         """
  59.        Normalize the address by lowercasing the domain part of the email
  60.        address.
  61.        """
  62.         email = email or ''
  63.         try:
  64.             email_name, domain_part = email.strip().rsplit('@', 1)
  65.         except ValueError:
  66.             pass
  67.         else:
  68.             email = '@'.join([email_name, domain_part.lower()])
  69.         return email
  70.  
  71.     def create_l2user(self, l2company, username, email=None, password=None):
  72.         """
  73.        Creates and saves a User with the given username, email and password.
  74.        """
  75.         now = timezone.now()
  76.         if not username:
  77.             raise ValueError('The given username must be set')
  78.         if not l2company:
  79.             raise ValueError('The given Comnpany Code must be set')
  80.  
  81.         email = L2UserManager.normalize_email(email)
  82.         l2user = self.model(username=username, email=email,
  83.                           is_staff=False, is_active=True, is_superuser=False,
  84.                           last_login=now, date_joined=now,l2Company=l2company)
  85.  
  86.         l2user.set_password(password)
  87.         l2user.save(using=self._db)
  88.         return l2user
  89.  
  90.     def create_superuser(self, l2company, username, email, password):
  91.         u = self.create_l2user(l2company, username, email, password)
  92.         u.is_staff = True
  93.         u.is_active = True
  94.         u.is_superuser = True
  95.         u.save(using=self._db)
  96.         return u
  97.  
  98.     def make_random_password(self, length=10,
  99.                              allowed_chars='abcdefghjkmnpqrstuvwxyz'
  100.                                            'ABCDEFGHJKLMNPQRSTUVWXYZ'
  101.                                            '23456789'):
  102.         """
  103.        Generates a random password with the given length and given
  104.        allowed_chars. Note that the default value of allowed_chars does not
  105.        have "I" or "O" or letters and digits that look similar -- just to
  106.        avoid confusion.
  107.        """
  108.         return get_random_string(length, allowed_chars)
  109.  
  110.     def get_by_natural_key(self, username):
  111.         return self.get(username=username)
  112.  
  113.  
  114. # A few helper functions for common logic between User and AnonymousUser.
  115. class L2User(models.Model):
  116.     """
  117.    Users within the Django authentication system are represented by this
  118.    model.
  119.  
  120.    Username and password are required. Other fields are optional.
  121.    """
  122.     l2company=models.ForeignKey(L2Company)
  123.     username = models.CharField(_('username'), max_length=30, blank=False,
  124.         help_text=_('Required. 30 characters or fewer. Letters, numbers and '
  125.                     '@/./+/-/_ characters'))
  126.     first_name = models.CharField(_('first name'), max_length=30, blank=True)
  127.     last_name = models.CharField(_('last name'), max_length=30, blank=True)
  128.     email = models.EmailField(_('e-mail address'), blank=True)
  129.     password = models.CharField(_('password'), max_length=128)
  130.     is_staff = models.BooleanField(_('staff status'), default=False,
  131.         help_text=_('Designates whether the user can log into this admin '
  132.                     'site.'))
  133.     is_active = models.BooleanField(_('active'), default=True,
  134.         help_text=_('Designates whether this user should be treated as '
  135.                     'active. Unselect this instead of deleting accounts.'))
  136.     is_superuser = models.BooleanField(_('superuser status'), default=False,
  137.         help_text=_('Designates that this user has all permissions without '
  138.                     'explicitly assigning them.'))
  139.     last_login = models.DateTimeField(_('last login'), default=timezone.now)
  140.     date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
  141.     groups = models.ManyToManyField(L2Group, verbose_name=_('groups'),
  142.         blank=True, help_text=_('The groups this user belongs to. A user will '
  143.                                 'get all permissions granted to each of '
  144.                                 'his/her group.'))
  145.     user_permissions = models.ManyToManyField(Permission,
  146.         limit_choices_to = {'isdelegate': True},
  147.         verbose_name=_('user permissions'), blank=True,
  148.         help_text='Specific permissions for this user.')
  149.     objects = L2UserManager()
  150.  
  151.     class Meta:
  152.         verbose_name = _('l2user')
  153.         verbose_name_plural = _('users')
  154.         unique_together = (('username', 'l2company'),)
  155.  
  156.     def __unicode__(self):
  157.         return self.username
  158.  
  159.     def natural_key(self):
  160.         return (self.username,)
  161.  
  162.     def get_absolute_url(self):
  163.         return "/%s/users/%s/" % (urllib.quote(smart_str(self.l2company)),
  164.             urllib.quote(smart_str(self.username)))
  165.  
  166.     def is_anonymous(self):
  167.         """
  168.        Always returns False. This is a way of comparing User objects to
  169.        anonymous users.
  170.        """
  171.         return False
  172.  
  173.     def is_authenticated(self):
  174.         """
  175.        Always return True. This is a way to tell if the user has been
  176.        authenticated in templates.
  177.        """
  178.         return True
  179.  
  180.     def get_full_name(self):
  181.         """
  182.        Returns the first_name plus the last_name, with a space in between.
  183.        """
  184.         full_name = u'%s %s' % (self.first_name, self.last_name)
  185.         return full_name.strip()
  186.  
  187.     def set_password(self, raw_password):
  188.         self.password = make_password(raw_password)
  189.  
  190.     def check_password(self, raw_password):
  191.         """
  192.        Returns a boolean of whether the raw_password was correct. Handles
  193.        hashing formats behind the scenes.
  194.        """
  195.         def setter(raw_password):
  196.             self.set_password(raw_password)
  197.             self.save()
  198.         return check_password(raw_password, self.password, setter)
  199.  
  200.     def set_unusable_password(self):
  201.         # Sets a value that will never be a valid hash
  202.         self.password = make_password(None)
  203.  
  204.     def has_usable_password(self):
  205.         return is_password_usable(self.password)
  206.  
  207.     def get_group_permissions(self, obj=None):
  208.         """
  209.        Returns a list of permission strings that this user has through his/her
  210.        groups. This method queries all available auth backends. If an object
  211.        is passed in, only permissions matching this object are returned.
  212.        """
  213.         permissions = set()
  214.         for backend in auth.get_backends():
  215.             if hasattr(backend, "get_group_permissions"):
  216.                 if obj is not None:
  217.                     permissions.update(backend.get_group_permissions(self,
  218.                                                                      obj))
  219.                 else:
  220.                     permissions.update(backend.get_group_permissions(self))
  221.         return permissions
  222.  
  223.     def get_all_permissions(self, obj=None):
  224.         return _user_get_all_permissions(self, obj)
  225.  
  226.     def has_perm(self, perm, obj=None):
  227.         """
  228.        Returns True if the user has the specified permission. This method
  229.        queries all available auth backends, but returns immediately if any
  230.        backend returns True. Thus, a user who has permission from a single
  231.        auth backend is assumed to have permission in general. If an object is
  232.        provided, permissions for this specific object are checked.
  233.        """
  234.  
  235.         # Active superusers have all permissions.
  236.         if self.is_active and self.is_superuser:
  237.             return True
  238.  
  239.         # Otherwise we need to check the backends.
  240.         return _user_has_perm(self, perm, obj)
  241.  
  242.     def has_perms(self, perm_list, obj=None):
  243.         """
  244.        Returns True if the user has each of the specified permissions. If
  245.        object is passed, it checks if the user has all required perms for this
  246.        object.
  247.        """
  248.         for perm in perm_list:
  249.             if not self.has_perm(perm, obj):
  250.                 return False
  251.         return True
  252.  
  253.     def has_module_perms(self, app_label):
  254.         """
  255.        Returns True if the user has any permissions in the given app label.
  256.        Uses pretty much the same logic as has_perm, above.
  257.        """
  258.         # Active superusers have all permissions.
  259.         if self.is_active and self.is_superuser:
  260.             return True
  261.  
  262.         return _user_has_module_perms(self, app_label)
  263.  
  264.     def email_user(self, subject, message, from_email=None):
  265.         """
  266.        Sends an email to this User.
  267.        """
  268.         send_mail(subject, message, from_email, [self.email])
  269.  
  270.     def get_profile(self):
  271.         """
  272.        Returns site-specific profile for this user. Raises
  273.        SiteProfileNotAvailable if this site does not allow profiles.
  274.        """
  275.         if not hasattr(self, '_profile_cache'):
  276.             from django.conf import settings
  277.             if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
  278.                 raise SiteProfileNotAvailable(
  279.                     'You need to set AUTH_PROFILE_MODULE in your project '
  280.                     'settings')
  281.             try:
  282.                 app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
  283.             except ValueError:
  284.                 raise SiteProfileNotAvailable(
  285.                     'app_label and model_name should be separated by a dot in '
  286.                     'the AUTH_PROFILE_MODULE setting')
  287.             try:
  288.                 model = models.get_model(app_label, model_name)
  289.                 if model is None:
  290.                     raise SiteProfileNotAvailable(
  291.                         'Unable to load the profile model, check '
  292.                         'AUTH_PROFILE_MODULE in your project settings')
  293.                 self._profile_cache = model._default_manager.using(
  294.                                    self._state.db).get(user__id__exact=self.id)
  295.                 self._profile_cache.user = self
  296.             except (ImportError, ImproperlyConfigured):
  297.                 raise SiteProfileNotAvailable
  298.         return self._profile_cache
Advertisement
Add Comment
Please, Sign In to add comment