Source

django-swingcms / swingcms / custodian / models.py

Full commit
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime, random

from django.db import models
from django.utils.translation import ugettext_lazy as _



###########################
##  PERMISSIONS CLASSES  ##
###########################


class Permission(models.Model):
    """
    Represent global, on model, on object permission.
    """
    type = models.CharField(_('type'), max_length=16,
                            choices=(('GLOBAL', 'GLOBAL'), ('MODEL', 'MODEL'), ('SPECIFIC', 'SPECIFIC')))
    mode = models.CharField(_('mode'), default='CAN', max_length=8,
                            choices=(('CAN', 'CAN'), ('CANNOT', 'CANNOT')))
    action = models.CharField(_('action'), max_length=64)
    object_name = models.CharField(_('object name'), default=None, max_length=64, null=True)
    object_id = models.IntegerField(_('object id'), default=None, null=True)

    class Meta:

        verbose_name = _('permission')
        verbose_name_plural = _('permissions')

    def __unicode__(self):

        if self.type == 'GLOBAL':
            if self.object_name:
                return "%s %s %s" % (self.mode, self.action, self.object_name)
            else:
                return "%s %s" % (self.mode, self.action)
        elif self.type == 'MODEL':
            return "%s %s %s" % (self.mode, self.action, self.object_name)
        elif self.type == 'SPECIFIC':
            return "%s %s %s %s" % (self.mode, self.action, self.object_name, self.object_id)


##############################
##  USER AND GROUP CLASSES  ##
##############################

# TO-DO: implement locking capability but from cms.code import BasePadlock raise circular import

class Group(models.Model):

    name = models.CharField(_('name'), max_length=64, unique=True)
    is_active = models.BooleanField(_('active'), default=True)
    permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True)

    class Meta:

        verbose_name = _('group')
        verbose_name_plural = _('groups')

    def __unicode__(self):

        return self.name


class UserManager(models.Manager):

    def create_user(self, username, email, password=None):
        """
        Creates and saves a User with the given username, e-mail and password.
        """
        now = datetime.datetime.now()
        user = self.model(username=username,
                          email=email,
                          is_active=True,
                          is_superuser=False,
                          last_login=now,
                          date_joined=now)
        user.set_password(password)
        user.save()

        return user

    def create_superuser(self, username, email, password):
        """
        Superuser has some default attributes.
        """
        superuser = self.create_user(username, email, password)
        superuser.is_active = True
        superuser.is_superuser = True
        superuser.save()

        return superuser

    def make_random_password(self, length=10, allowed_chars="abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"):
        """
        Generates a random password with the given length and given allowed_chars (without 'I' char).
        """
        from random import choice

        return ''.join([choice(allowed_chars) for i in range(length)])


class User(models.Model):

    username = models.CharField(_('username'), max_length=32, unique=True)
    first_name = models.CharField(_('first name'), max_length=32, blank=True, null=True)
    last_name = models.CharField(_('last name'), max_length=32, blank=True, null=True)
    email = models.OneToOneField('mailserver.Email', verbose_name=_('email'),
                                 on_delete=models.SET_NULL, blank=True, null=True)
    password = models.CharField(_('password'), max_length=128)
    is_active = models.BooleanField(_('is active'), default=True)
    is_superuser = models.BooleanField(_('is superuser'), default=False)
    last_login = models.DateTimeField(_('last login'), default=datetime.datetime.now)
    date_joined = models.DateTimeField(_('date joined'), default=datetime.datetime.now)
    groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True, null=True)
    permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True,
                                         null=True)

    objects = UserManager()

    class Meta:

        verbose_name = _('user')
        verbose_name_plural = _('users')

    def __unicode__(self):

        return self.username

    def is_anonymous(self):

        return False

    def is_authenticated(self):

        return True

    def get_full_name(self):

        return u"%s %s" % (self.first_name.capitalize(), self.last_name.capitalize())

    def set_password(self, password):

        from cms.code import get_hexdigest

        self.password = get_hexdigest('sha1', password)

    def check_password(self, password):

        return check_password(password, self.password)

    def has_perm(self, perm, obj=None):

        from custodian.code import has_perm

        return has_perm(self, perm, obj=obj)

    def has_perms(self, perm_list, obj=None):

        for perm in perm_list:
            if not self.has_perm(perm, obj=obj):
                return False
        return True

    def email_user(self, subject, message, from_email=None):

        from mailserver import send_mail

        send_mail(subject, message, from_email, [self.email])


class AnonymousUser(object):

    id = None
    username = ''
    is_active = False
    is_superuser = False
    groups = models.manager.EmptyManager()
    permissions = models.manager.EmptyManager()

    def __init__(self):

        pass

    def __unicode__(self):

        return "AnonymousUser"

    def __str__(self):

        return unicode(self).encode('utf-8')

    def __eq__(self, other):

        return isinstance(other, self.__class__)

    def __ne__(self, other):

        return not self.__eq__(other)

    def __hash__(self):

        return 1 # instances always return the same hash value

    def is_anonymous(self):

        return True

    def is_authenticated(self):

        return False

    def save(self):

        raise NotImplementedError

    def delete(self):

        raise NotImplementedError

    def set_password(self, password):

        raise NotImplementedError

    def check_password(self, password):

        raise NotImplementedError

    def has_perm(self, perm, obj=None):

        from custodian.code import has_perm

        return has_perm(self, perm, obj=obj)

    def has_perms(self, perm_list, obj=None):

        for perm in perm_list:
            if not self.has_perm(perm, obj):
                return False
        return True