models.py 8.5 KB
Newer Older
Gabriel Detraz's avatar
Gabriel Detraz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
from django.db import models
from django.db.models import Q
from django.forms import ModelForm, Form
from django import forms
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver


from amap.settings import RIGHTS_LINK, REQ_EXPIRE_HRS
import re, uuid
import datetime

from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

16 17
from panier.models import Credit, Commande

Gabriel Detraz's avatar
Gabriel Detraz committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
def get_admin_right():
    try:
        admin_right = ListRight.objects.get(listright="admin")
    except ListRight.DoesNotExist:
        admin_right = ListRight(listright="admin")
        admin_right.save()
    return admin_right


class UserManager(BaseUserManager):
    def _create_user(self, pseudo, name, surname, email, password=None, su=False):
        if not pseudo:
            raise ValueError('Users must have an username')

        user = self.model(
            pseudo=pseudo,
            name=name,
            surname=surname,
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        if su:
            user.make_admin()
        return user

    def create_user(self, pseudo, name, surname, email, password=None):
        """
        Creates and saves a User with the given pseudo, name, surname, email,
        and password.
        """
        return self._create_user(pseudo, name, surname, email, password, False)

    def create_superuser(self, pseudo, name, surname, email, password):
        """
        Creates and saves a superuser with the given pseudo, name, surname,
        email, and password.
        """
        return self._create_user(pseudo, name, surname, email, password, True)


class User(AbstractBaseUser):
    STATE_ACTIVE = 0
    STATE_DEACTIVATED = 1
    STATE_ARCHIVED = 2
    STATES = (
            (0, 'STATE_ACTIVE'),
            (1, 'STATE_DEACTIVATED'),
            (2, 'STATE_ARCHIVED'),
            )

    def auto_uid():
        uids = list(range(int(min(UID_RANGES['users'])),int(max(UID_RANGES['users']))))
        used_uids = [ user.uid_number for user in User.objects.all()]
        free_uids = [ id for id in uids if id not in used_uids]
        return min(free_uids)

    name = models.CharField(max_length=255)
    surname = models.CharField(max_length=255)
    pseudo = models.CharField(max_length=32, unique=True, help_text="Doit contenir uniquement des lettres, chiffres, ou tirets. ")
    email = models.EmailField()
80
    telephone = models.CharField(max_length=15)
Gabriel Detraz's avatar
Gabriel Detraz committed
81
    comment = models.CharField(help_text="Commentaire, promo", max_length=255, blank=True)
82
    is_ens = models.BooleanField(default=True) 
Gabriel Detraz's avatar
Gabriel Detraz committed
83 84 85 86
    state = models.IntegerField(choices=STATES, default=STATE_ACTIVE)
    registered = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'pseudo'
87
    REQUIRED_FIELDS = ['name', 'surname', 'email', 'telephone']
Gabriel Detraz's avatar
Gabriel Detraz committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

    objects = UserManager()

    @property
    def is_active(self):
        return self.state == self.STATE_ACTIVE

    @property
    def is_staff(self):
        return self.is_admin

    @property
    def is_admin(self):
        try:
            Right.objects.get(user=self, right__listright='admin')
        except Right.DoesNotExist:
            return False
        return True

    @is_admin.setter
    def is_admin(self, value):
        if value and not self.is_admin:
            self.make_admin()
        elif not value and self.is_admin:
            self.un_admin()

    def get_full_name(self):
        return '%s %s' % (self.name, self.surname)

    def get_short_name(self):
        return self.name

    def has_perms(self, perms, obj=None):
        for perm in perms:
            if perm in RIGHTS_LINK:
                query = Q()
                for right in RIGHTS_LINK[perm]:
                    query = query | Q(right__listright=right)
                if Right.objects.filter(Q(user=self) & query):
                    return True 
            try:
                Right.objects.get(user=self, right__listright=perm)
            except Right.DoesNotExist:
                return False
        return True

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

    def has_module_perms(self, app_label):
        # Simplest version again
        return True

    def make_admin(self):
        """ Make User admin """
        user_admin_right = Right(user=self, right=get_admin_right())
        user_admin_right.save()

    def un_admin(self):
        try:
            user_right = Right.objects.get(user=self,right=get_admin_right())
        except Right.DoesNotExist:
            return
        user_right.delete()

153 154 155 156 157 158
    def solde(self):
        """ Renvoie le solde dynamiquement"""
        credit = sum(credit.montant for credit in Credit.objects.filter(user=self) if credit.validite)
        debit = sum(commande.prix_unitaire*commande.quantite for commande in Commande.objects.filter(user=self))
        return credit-debit

Gabriel Detraz's avatar
Gabriel Detraz committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    def __str__(self):
        return self.pseudo

class Right(models.Model):
    user = models.ForeignKey('User', on_delete=models.PROTECT)
    right = models.ForeignKey('ListRight', on_delete=models.PROTECT)

    class Meta:
        unique_together = ("user", "right")

    def __str__(self):
        return str(self.user) + " - " + str(self.right)

class ListRight(models.Model):
    listright = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.listright

class Request(models.Model):
    PASSWD = 'PW'
    EMAIL = 'EM'
    TYPE_CHOICES = (
        (PASSWD, 'Mot de passe'),
        (EMAIL, 'Email'),
    )
    type = models.CharField(max_length=2, choices=TYPE_CHOICES)
    token = models.CharField(max_length=32)
    user = models.ForeignKey('User', on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    expires_at = models.DateTimeField()

    def save(self):
        if not self.expires_at:
            self.expires_at = timezone.now() \
                + datetime.timedelta(hours=REQ_EXPIRE_HRS)
        if not self.token:
            self.token = str(uuid.uuid4()).replace('-', '')  # remove hyphens
        super(Request, self).save()

class BaseInfoForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(BaseInfoForm, self).__init__(*args, **kwargs)
        self.fields['name'].label = 'Prénom'
        self.fields['surname'].label = 'Nom'
        self.fields['comment'].label = 'Commentaire'
205
        self.fields['is_ens'].label = 'Eleve ou personnel ENS Paris-Saclay'
Gabriel Detraz's avatar
Gabriel Detraz committed
206 207 208 209 210 211 212 213

    class Meta:
        model = User
        fields = [
            'name',
            'surname',
            'pseudo',
            'email',
214
            'telephone',
Gabriel Detraz's avatar
Gabriel Detraz committed
215
            'comment',
216
            'is_ens',
Gabriel Detraz's avatar
Gabriel Detraz committed
217 218 219 220 221 222 223 224 225
        ]

class EditInfoForm(BaseInfoForm):
    class Meta(BaseInfoForm.Meta):
        fields = [
            'name',
            'surname',
            'pseudo',
            'email',
226
            'telephone',
Gabriel Detraz's avatar
Gabriel Detraz committed
227
            'comment',
228
            'is_ens',
Gabriel Detraz's avatar
Gabriel Detraz committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        ]

class UserForm(BaseInfoForm):
    class Meta(BaseInfoForm.Meta):
        fields = '__all__'

class PasswordForm(ModelForm):
    class Meta:
        model = User
        fields = ['password']


class StateForm(ModelForm):
    class Meta:
        model = User
        fields = ['state']

class ListRightForm(ModelForm):
    class Meta:
        model = ListRight
        fields = ['listright']

    def __init__(self, *args, **kwargs):
        super(ListRightForm, self).__init__(*args, **kwargs)
        self.fields['listright'].label = 'Nom du droit/groupe'

class NewListRightForm(ListRightForm):
    class Meta(ListRightForm.Meta):
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(NewListRightForm, self).__init__(*args, **kwargs)

class DelListRightForm(ModelForm):
    listrights = forms.ModelMultipleChoiceField(queryset=ListRight.objects.all(), label="Droits actuels",  widget=forms.CheckboxSelectMultiple)

    class Meta:
266
        exclude = ['listright']
Gabriel Detraz's avatar
Gabriel Detraz committed
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        model = ListRight

class RightForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(RightForm, self).__init__(*args, **kwargs)
        self.fields['right'].label = 'Droit'
        self.fields['right'].empty_label = "Choisir un nouveau droit"

    class Meta:
        model = Right
        fields = ['right']


class DelRightForm(ModelForm):
    rights = forms.ModelMultipleChoiceField(queryset=Right.objects.all(), label="Droits actuels",  widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Right
        exclude = ['user', 'right']

class ProfilForm(Form):
    user = forms.CharField(label='Ok', max_length=100)