Ce serveur Gitlab sera éteint le 30 juin 2020, pensez à migrer vos projets vers les serveurs gitlab-research.centralesupelec.fr et gitlab-student.centralesupelec.fr !

models.py 52.2 KB
Newer Older
1
# -*- mode: python; coding: utf-8 -*-
chirac's avatar
chirac committed
2 3 4
# Re2o est un logiciel d'administration développé initiallement au rezometz.
# Il  se veut agnostique au réseau considéré, de manière à être installable
# en quelques clics.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# Copyright © 2017  Gabriel Détraz
# Copyright © 2017  Goulven Kermarec
# Copyright © 2017  Augustin Lemesle
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
chirac's avatar
chirac committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
"""
Models de l'application users.

On défini ici des models django classiques:
- users, qui hérite de l'abstract base user de django. Permet de définit
un utilisateur du site (login, passwd, chambre, adresse, etc)
- les whiteslist
- les bannissements
- les établissements d'enseignement (school)
- les droits (right et listright)
- les utilisateurs de service (pour connexion automatique)

On défini aussi des models qui héritent de django-ldapdb :
- ldapuser
- ldapgroup
- ldapserviceuser

Ces utilisateurs ldap sont synchronisés à partir des objets
models sql classiques. Seuls certains champs essentiels sont
dupliqués.
"""

45

46 47
from __future__ import unicode_literals

chirac's avatar
chirac committed
48 49 50 51
import re
import uuid
import datetime

lhark's avatar
lhark committed
52
from django.db import models
53
from django.db.models import Q
54
from django import forms
55 56
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
57
from django.utils.functional import cached_property
chirac's avatar
chirac committed
58
from django.template import Context, loader
59 60
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
chirac's avatar
chirac committed
61 62
from django.db import transaction
from django.utils import timezone
63 64
from django.contrib.auth.models import (
    AbstractBaseUser,
65
    BaseUserManager,
66 67
    PermissionsMixin,
    Group
68
)
chirac's avatar
chirac committed
69
from django.core.validators import RegexValidator
70

71 72
from reversion import revisions as reversion

73 74 75
import ldapdb.models
import ldapdb.models.fields

chirac's avatar
chirac committed
76
from re2o.settings import LDAP, GID_RANGES, UID_RANGES
77
from re2o.login import hashNT
78
from re2o.field_permissions import FieldPermissionModelMixin
79
from re2o.mixins import AclMixin, RevMixin
lhark's avatar
lhark committed
80

chibrac's avatar
chibrac committed
81
from cotisations.models import Cotisation, Facture, Paiement, Vente
chirac's avatar
chirac committed
82 83 84
from machines.models import Domain, Interface, Machine, regen
from preferences.models import GeneralOption, AssoOption, OptionalUser
from preferences.models import OptionalMachine, MailMessageOption
85

chirac's avatar
chirac committed
86

chirac's avatar
chirac committed
87
# Utilitaires généraux
chirac's avatar
chirac committed
88

89 90

def linux_user_check(login):
chirac's avatar
chirac committed
91
    """ Validation du pseudo pour respecter les contraintes unix"""
92
    UNIX_LOGIN_PATTERN = re.compile("^[a-zA-Z0-9-]*[$]?$")
93 94 95 96
    return UNIX_LOGIN_PATTERN.match(login)


def linux_user_validator(login):
chirac's avatar
chirac committed
97
    """ Retourne une erreur de validation si le login ne respecte
chirac's avatar
chirac committed
98
    pas les contraintes unix (maj, min, chiffres ou tiret)"""
99
    if not linux_user_check(login):
chirac's avatar
chirac committed
100
        raise forms.ValidationError(
chirac's avatar
chirac committed
101 102
            ", ce pseudo ('%(label)s') contient des carractères interdits",
            params={'label': login},
chirac's avatar
chirac committed
103 104
        )

chirac's avatar
chirac committed
105

106
def get_fresh_user_uid():
chirac's avatar
chirac committed
107
    """ Renvoie le plus petit uid non pris. Fonction très paresseuse """
chirac's avatar
chirac committed
108 109 110 111
    uids = list(range(
        int(min(UID_RANGES['users'])),
        int(max(UID_RANGES['users']))
    ))
112
    try:
113
        used_uids = list(User.objects.values_list('uid_number', flat=True))
114 115
    except:
        used_uids = []
chirac's avatar
chirac committed
116
    free_uids = [id for id in uids if id not in used_uids]
117 118
    return min(free_uids)

chirac's avatar
chirac committed
119

120
def get_fresh_gid():
chirac's avatar
chirac committed
121
    """ Renvoie le plus petit gid libre  """
chirac's avatar
chirac committed
122 123 124 125
    gids = list(range(
        int(min(GID_RANGES['posix'])),
        int(max(GID_RANGES['posix']))
    ))
126
    used_gids = list(ListRight.objects.values_list('gid', flat=True))
chirac's avatar
chirac committed
127
    free_gids = [id for id in gids if id not in used_gids]
128
    return min(free_gids)
129

chirac's avatar
chirac committed
130

131
class UserManager(BaseUserManager):
chirac's avatar
chirac committed
132 133 134 135 136 137 138 139 140
    """User manager basique de django"""
    def _create_user(
            self,
            pseudo,
            surname,
            email,
            password=None,
            su=False
    ):
141 142 143 144
        if not pseudo:
            raise ValueError('Users must have an username')

        if not linux_user_check(pseudo):
145
            raise ValueError('Username shall only contain [a-z0-9-]')
146

147
        user = Adherent(
148 149
            pseudo=pseudo,
            surname=surname,
150
            name=surname,
151 152 153 154 155
            email=self.normalize_email(email),
        )

        user.set_password(password)
        if su:
156
            user.is_superuser = True
157
        user.save(using=self._db)
158 159
        return user

160
    def create_user(self, pseudo, surname, email, password=None):
161 162 163 164
        """
        Creates and saves a User with the given pseudo, name, surname, email,
        and password.
        """
165
        return self._create_user(pseudo, surname, email, password, False)
166

167
    def create_superuser(self, pseudo, surname, email, password):
168 169 170 171
        """
        Creates and saves a superuser with the given pseudo, name, surname,
        email, and password.
        """
172
        return self._create_user(pseudo, surname, email, password, True)
173

174 175 176

class User(RevMixin, FieldPermissionModelMixin, AbstractBaseUser,
           PermissionsMixin, AclMixin):
chirac's avatar
chirac committed
177 178 179
    """ Definition de l'utilisateur de base.
    Champs principaux : name, surnname, pseudo, email, room, password
    Herite du django BaseUser et du système d'auth django"""
Gabriel Detraz's avatar
Gabriel Detraz committed
180
    PRETTY_NAME = "Utilisateurs (clubs et adhérents)"
lhark's avatar
lhark committed
181
    STATE_ACTIVE = 0
chirac's avatar
chirac committed
182 183
    STATE_DISABLED = 1
    STATE_ARCHIVE = 2
lhark's avatar
lhark committed
184
    STATES = (
chirac's avatar
chirac committed
185 186 187 188
        (0, 'STATE_ACTIVE'),
        (1, 'STATE_DISABLED'),
        (2, 'STATE_ARCHIVE'),
    )
lhark's avatar
lhark committed
189 190

    surname = models.CharField(max_length=255)
chirac's avatar
chirac committed
191 192 193 194 195 196
    pseudo = models.CharField(
        max_length=32,
        unique=True,
        help_text="Doit contenir uniquement des lettres, chiffres, ou tirets",
        validators=[linux_user_validator]
    )
lhark's avatar
lhark committed
197
    email = models.EmailField()
chirac's avatar
chirac committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    school = models.ForeignKey(
        'School',
        on_delete=models.PROTECT,
        null=True,
        blank=True
    )
    shell = models.ForeignKey(
        'ListShell',
        on_delete=models.PROTECT,
        null=True,
        blank=True
    )
    comment = models.CharField(
        help_text="Commentaire, promo",
        max_length=255,
        blank=True
    )
lhark's avatar
lhark committed
215
    pwd_ntlm = models.CharField(max_length=255)
216
    state = models.IntegerField(choices=STATES, default=STATE_ACTIVE)
217
    registered = models.DateTimeField(auto_now_add=True)
218
    telephone = models.CharField(max_length=15, blank=True, null=True)
219 220 221 222
    uid_number = models.PositiveIntegerField(
        default=get_fresh_user_uid,
        unique=True
    )
223 224 225 226 227
    rezo_rez_uid = models.PositiveIntegerField(
        unique=True,
        blank=True,
        null=True
    )
lhark's avatar
lhark committed
228

229
    USERNAME_FIELD = 'pseudo'
230
    REQUIRED_FIELDS = ['surname', 'email']
231 232 233

    objects = UserManager()

234 235
    class Meta:
        permissions = (
236 237
            ("change_user_password",
             "Peut changer le mot de passe d'un user"),
238 239 240
            ("change_user_state", "Peut éditer l'etat d'un user"),
            ("change_user_force", "Peut forcer un déménagement"),
            ("change_user_shell", "Peut éditer le shell d'un user"),
241 242 243 244 245 246 247
            ("change_user_groups",
             "Peut éditer les groupes d'un user ! Permission critique"),
            ("change_all_users",
             "Peut éditer tous les users, y compris ceux dotés de droits. "
             "Superdroit"),
            ("view_user",
             "Peut voir un objet user quelquonque"),
248 249
        )

250 251 252 253 254 255 256 257
    @cached_property
    def name(self):
        """Si il s'agit d'un adhérent, on renvoie le prénom"""
        if self.is_class_adherent:
            return self.adherent.name
        else:
            return ''

258 259 260 261 262 263 264 265 266 267
    @cached_property
    def room(self):
        """Alias vers room """
        if self.is_class_adherent:
            return self.adherent.room
        elif self.is_class_club:
            return self.club.room
        else:
            raise NotImplementedError("Type inconnu")

268 269 270 271
    @cached_property
    def class_name(self):
        """Renvoie si il s'agit d'un adhérent ou d'un club"""
        if hasattr(self, 'adherent'):
Gabriel Detraz's avatar
Gabriel Detraz committed
272
            return "Adherent"
273 274 275 276 277 278 279
        elif hasattr(self, 'club'):
            return "Club"
        else:
            raise NotImplementedError("Type inconnu")

    @cached_property
    def is_class_club(self):
280 281
        """ Returns True if the object is a Club (subclassing User) """
        # TODO : change to isinstance (cleaner)
282 283 284 285
        return hasattr(self, 'club')

    @cached_property
    def is_class_adherent(self):
286 287
        """ Returns True if the object is a Adherent (subclassing User) """
        # TODO : change to isinstance (cleaner)
288 289
        return hasattr(self, 'adherent')

290 291
    @property
    def is_active(self):
chirac's avatar
chirac committed
292
        """ Renvoie si l'user est à l'état actif"""
293 294 295 296
        return self.state == self.STATE_ACTIVE

    @property
    def is_staff(self):
chirac's avatar
chirac committed
297
        """ Fonction de base django, renvoie si l'user est admin"""
298 299 300 301
        return self.is_admin

    @property
    def is_admin(self):
chirac's avatar
chirac committed
302
        """ Renvoie si l'user est admin"""
303
        admin, _ = Group.objects.get_or_create(name="admin")
304
        return self.is_superuser or admin in self.groups.all()
305 306

    def get_full_name(self):
chirac's avatar
chirac committed
307
        """ Renvoie le nom complet de l'user formaté nom/prénom"""
308 309 310 311 312
        name = self.name
        if name:
            return '%s %s' % (name, self.surname)
        else:
            return self.surname
313 314

    def get_short_name(self):
chirac's avatar
chirac committed
315
        """ Renvoie seulement le nom"""
316
        return self.surname
317

318 319 320 321 322 323
    @property
    def get_shell(self):
        """ A utiliser de préférence, prend le shell par défaut
        si il n'est pas défini"""
        return self.shell or OptionalUser.get_cached_value('shell_default')

324
    def end_adhesion(self):
chirac's avatar
chirac committed
325 326
        """ Renvoie la date de fin d'adhésion d'un user. Examine les objets
        cotisation"""
chirac's avatar
chirac committed
327 328 329 330 331 332
        date_max = Cotisation.objects.filter(
            vente__in=Vente.objects.filter(
                facture__in=Facture.objects.filter(
                    user=self
                ).exclude(valid=False)
            )
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        ).filter(
            Q(type_cotisation='All') | Q(type_cotisation='Adhesion')
        ).aggregate(models.Max('date_end'))['date_end__max']
        return date_max

    def end_connexion(self):
        """ Renvoie la date de fin de connexion d'un user. Examine les objets
        cotisation"""
        date_max = Cotisation.objects.filter(
            vente__in=Vente.objects.filter(
                facture__in=Facture.objects.filter(
                    user=self
                ).exclude(valid=False)
            )
        ).filter(
            Q(type_cotisation='All') | Q(type_cotisation='Connexion')
chirac's avatar
chirac committed
349
        ).aggregate(models.Max('date_end'))['date_end__max']
350 351 352
        return date_max

    def is_adherent(self):
chirac's avatar
chirac committed
353 354
        """ Renvoie True si l'user est adhérent : si
        self.end_adhesion()>now"""
355
        end = self.end_adhesion()
356 357
        if not end:
            return False
358
        elif end < timezone.now():
359 360 361 362
            return False
        else:
            return True

363 364 365 366 367 368
    def is_connected(self):
        """ Renvoie True si l'user est adhérent : si
        self.end_adhesion()>now et end_connexion>now"""
        end = self.end_connexion()
        if not end:
            return False
369
        elif end < timezone.now():
370 371 372 373
            return False
        else:
            return self.is_adherent()

374 375
    def end_ban(self):
        """ Renvoie la date de fin de ban d'un user, False sinon """
chirac's avatar
chirac committed
376 377 378
        date_max = Ban.objects.filter(
            user=self
        ).aggregate(models.Max('date_end'))['date_end__max']
379 380 381
        return date_max

    def end_whitelist(self):
382
        """ Renvoie la date de fin de whitelist d'un user, False sinon """
chirac's avatar
chirac committed
383 384 385
        date_max = Whitelist.objects.filter(
            user=self
        ).aggregate(models.Max('date_end'))['date_end__max']
386 387 388 389
        return date_max

    def is_ban(self):
        """ Renvoie si un user est banni ou non """
390
        end = self.end_ban()
391 392
        if not end:
            return False
393
        elif end < timezone.now():
394 395 396 397 398 399
            return False
        else:
            return True

    def is_whitelisted(self):
        """ Renvoie si un user est whitelisté ou non """
400
        end = self.end_whitelist()
401 402
        if not end:
            return False
403
        elif end < timezone.now():
404 405 406 407 408 409
            return False
        else:
            return True

    def has_access(self):
        """ Renvoie si un utilisateur a accès à internet """
410 411 412
        return (self.state == User.STATE_ACTIVE and
                not self.is_ban() and
                (self.is_connected() or self.is_whitelisted()))
413

414 415
    def end_access(self):
        """ Renvoie la date de fin normale d'accès (adhésion ou whiteliste)"""
416
        if not self.end_connexion():
417
            if not self.end_whitelist():
418 419
                return None
            else:
420
                return self.end_whitelist()
421
        else:
422
            if not self.end_whitelist():
423
                return self.end_connexion()
chirac's avatar
chirac committed
424
            else:
425
                return max(self.end_connexion(), self.end_whitelist())
426

chibrac's avatar
chibrac committed
427 428
    @cached_property
    def solde(self):
chirac's avatar
chirac committed
429 430
        """ Renvoie le solde d'un user. Vérifie que l'option solde est
        activé, retourne 0 sinon.
chirac's avatar
chirac committed
431
        Somme les crédits de solde et retire les débit payés par solde"""
432
        user_solde = OptionalUser.get_cached_value('user_solde')
chibrac's avatar
chibrac committed
433
        if user_solde:
434
            solde_objects = Paiement.objects.filter(moyen='Solde')
chirac's avatar
chirac committed
435 436 437
            somme_debit = Vente.objects.filter(
                facture__in=Facture.objects.filter(
                    user=self,
438 439
                    paiement__in=solde_objects,
                    valid=True
chirac's avatar
chirac committed
440 441 442 443 444 445 446 447
                )
            ).aggregate(
                total=models.Sum(
                    models.F('prix')*models.F('number'),
                    output_field=models.FloatField()
                )
            )['total'] or 0
            somme_credit = Vente.objects.filter(
448
                facture__in=Facture.objects.filter(user=self, valid=True),
chirac's avatar
chirac committed
449 450 451 452 453 454 455
                name="solde"
            ).aggregate(
                total=models.Sum(
                    models.F('prix')*models.F('number'),
                    output_field=models.FloatField()
                )
            )['total'] or 0
chibrac's avatar
chibrac committed
456 457 458 459
            return somme_credit - somme_debit
        else:
            return 0

chirac's avatar
chirac committed
460
    def user_interfaces(self, active=True):
chirac's avatar
chirac committed
461 462 463 464 465
        """ Renvoie toutes les interfaces dont les machines appartiennent à
        self. Par defaut ne prend que les interfaces actives"""
        return Interface.objects.filter(
            machine__in=Machine.objects.filter(user=self, active=active)
        ).select_related('domain__extension')
466

467 468 469 470 471 472 473 474 475 476 477
    def assign_ips(self):
        """ Assign une ipv4 aux machines d'un user """
        interfaces = self.user_interfaces()
        for interface in interfaces:
            if not interface.ipv4:
                with transaction.atomic(), reversion.create_revision():
                    interface.assign_ipv4()
                    reversion.set_comment("Assignation ipv4")
                    interface.save()

    def unassign_ips(self):
chirac's avatar
chirac committed
478
        """ Désassigne les ipv4 aux machines de l'user"""
479 480 481 482 483 484 485 486
        interfaces = self.user_interfaces()
        for interface in interfaces:
            with transaction.atomic(), reversion.create_revision():
                interface.unassign_ipv4()
                reversion.set_comment("Désassignation ipv4")
                interface.save()

    def archive(self):
chirac's avatar
chirac committed
487 488
        """ Archive l'user : appelle unassign_ips() puis passe state à
        ARCHIVE"""
489
        self.unassign_ips()
chirac's avatar
chirac committed
490
        self.state = User.STATE_ARCHIVE
491 492

    def unarchive(self):
chirac's avatar
chirac committed
493 494
        """ Désarchive l'user : réassigne ses ip et le passe en state
        ACTIVE"""
495 496 497
        self.assign_ips()
        self.state = User.STATE_ACTIVE

498 499
    def ldap_sync(self, base=True, access_refresh=True, mac_refresh=True,
                  group_refresh=False):
chirac's avatar
chirac committed
500 501 502 503 504 505
        """ Synchronisation du ldap. Synchronise dans le ldap les attributs de
        self
        Options : base : synchronise tous les attributs de base - nom, prenom,
        mail, password, shell, home
        access_refresh : synchronise le dialup_access notant si l'user a accès
        aux services
506
        mac_refresh : synchronise les machines de l'user
507
        group_refresh : synchronise les group de l'user
508
        Si l'instance n'existe pas, on crée le ldapuser correspondant"""
chirac's avatar
chirac committed
509
        self.refresh_from_db()
510
        try:
root's avatar
root committed
511
            user_ldap = LdapUser.objects.get(uidNumber=self.uid_number)
512
        except LdapUser.DoesNotExist:
root's avatar
root committed
513
            user_ldap = LdapUser(uidNumber=self.uid_number)
514 515 516
            base = True
            access_refresh = True
            mac_refresh = True
517
        if base:
chirac's avatar
chirac committed
518
            user_ldap.name = self.pseudo
519
            user_ldap.sn = self.pseudo
520
            user_ldap.dialupAccess = str(self.has_access())
521 522
            user_ldap.home_directory = '/home/' + self.pseudo
            user_ldap.mail = self.email
chirac's avatar
chirac committed
523 524
            user_ldap.given_name = self.surname.lower() + '_'\
                + self.name.lower()[:3]
525
            user_ldap.gid = LDAP['user_gid']
526
            user_ldap.user_password = self.password[:6] + self.password[7:]
Gabriel Detraz's avatar
Gabriel Detraz committed
527
            user_ldap.sambat_nt_password = self.pwd_ntlm.upper()
528 529
            if self.get_shell:
                user_ldap.login_shell = str(self.get_shell)
chibrac's avatar
chibrac committed
530 531 532 533
            if self.state == self.STATE_DISABLED:
                user_ldap.shadowexpire = str(0)
            else:
                user_ldap.shadowexpire = None
534
        if access_refresh:
535
            user_ldap.dialupAccess = str(self.has_access())
536
        if mac_refresh:
537 538 539
            user_ldap.macs = [str(mac) for mac in Interface.objects.filter(
                machine__user=self
            ).values_list('mac_address', flat=True).distinct()]
540
        if group_refresh:
541 542 543
            for group in self.groups.all():
                if hasattr(group, 'listright'):
                    group.listright.ldap_sync()
544 545 546
        user_ldap.save()

    def ldap_del(self):
chirac's avatar
chirac committed
547
        """ Supprime la version ldap de l'user"""
548 549 550 551 552 553
        try:
            user_ldap = LdapUser.objects.get(name=self.pseudo)
            user_ldap.delete()
        except LdapUser.DoesNotExist:
            pass

554 555
    def notif_inscription(self):
        """ Prend en argument un objet user, envoie un mail de bienvenue """
chirac's avatar
chirac committed
556 557 558 559
        template = loader.get_template('users/email_welcome')
        mailmessageoptions, _created = MailMessageOption\
            .objects.get_or_create()
        context = Context({
560
            'nom': self.get_full_name(),
561 562
            'asso_name': AssoOption.get_cached_value('name'),
            'asso_email': AssoOption.get_cached_value('contact'),
chirac's avatar
chirac committed
563 564 565
            'welcome_mail_fr': mailmessageoptions.welcome_mail_fr,
            'welcome_mail_en': mailmessageoptions.welcome_mail_en,
            'pseudo': self.pseudo,
566
        })
567 568 569 570 571 572 573 574 575
        send_mail(
            'Bienvenue au %(name)s / Welcome to %(name)s' % {
                'name': AssoOption.get_cached_value('name')
                },
            '',
            GeneralOption.get_cached_value('email_from'),
            [self.email],
            html_message=template.render(context)
        )
576 577 578
        return

    def reset_passwd_mail(self, request):
chirac's avatar
chirac committed
579 580
        """ Prend en argument un request, envoie un mail de
        réinitialisation de mot de pass """
581 582 583 584
        req = Request()
        req.type = Request.PASSWD
        req.user = self
        req.save()
chirac's avatar
chirac committed
585 586
        template = loader.get_template('users/email_passwd_request')
        context = {
587
            'name': req.user.get_full_name(),
588 589
            'asso': AssoOption.get_cached_value('name'),
            'asso_mail': AssoOption.get_cached_value('contact'),
590
            'site_name': GeneralOption.get_cached_value('site_name'),
591
            'url': request.build_absolute_uri(
592 593 594 595 596 597
                reverse('users:process', kwargs={'token': req.token})
            ),
            'expire_in': str(
                GeneralOption.get_cached_value('req_expire_hrs')
            ) + ' heures',
        }
598
        send_mail(
599 600
            'Changement de mot de passe du %(name)s / Password renewal for '
            '%(name)s' % {'name': AssoOption.get_cached_value('name')},
601 602 603 604 605
            template.render(context),
            GeneralOption.get_cached_value('email_from'),
            [req.user.email],
            fail_silently=False
        )
606 607
        return

608
    def autoregister_machine(self, mac_address, nas_type):
chirac's avatar
chirac committed
609 610
        """ Fonction appellée par freeradius. Enregistre la mac pour
        une machine inconnue sur le compte de l'user"""
chirac's avatar
chirac committed
611
        all_interfaces = self.user_interfaces(active=False)
612
        if all_interfaces.count() > OptionalMachine.get_cached_value(
613 614
                'max_lambdauser_interfaces'
            ):
615
            return False, "Maximum de machines enregistrees atteinte"
616
        if not nas_type:
chirac's avatar
chirac committed
617 618
            return False, "Re2o ne sait pas à quel machinetype affecter cette\
            machine"
619
        machine_type_cible = nas_type.machine_type
620 621 622 623 624
        try:
            machine_parent = Machine()
            machine_parent.user = self
            interface_cible = Interface()
            interface_cible.mac_address = mac_address
625
            interface_cible.type = machine_type_cible
626 627 628
            interface_cible.clean()
            machine_parent.clean()
            domain = Domain()
629
            domain.name = self.get_next_domain_name()
630 631
            domain.interface_parent = interface_cible
            domain.clean()
632 633 634 635 636 637
            machine_parent.save()
            interface_cible.machine = machine_parent
            interface_cible.save()
            domain.interface_parent = interface_cible
            domain.clean()
            domain.save()
638
            self.notif_auto_newmachine(interface_cible)
chirac's avatar
chirac committed
639 640
        except Exception as error:
            return False, error
641 642
        return True, "Ok"

643 644 645 646 647 648
    def notif_auto_newmachine(self, interface):
        """Notification mail lorsque une machine est automatiquement
        ajoutée par le radius"""
        template = loader.get_template('users/email_auto_newmachine')
        context = Context({
            'nom': self.get_full_name(),
649
            'mac_address': interface.mac_address,
650
            'asso_name': AssoOption.get_cached_value('name'),
651
            'interface_name': interface.domain,
652
            'asso_email': AssoOption.get_cached_value('contact'),
653 654 655 656 657
            'pseudo': self.pseudo,
        })
        send_mail(
            "Ajout automatique d'une machine / New machine autoregistered",
            '',
658
            GeneralOption.get_cached_value('email_from'),
659 660 661 662 663
            [self.email],
            html_message=template.render(context)
        )
        return

664
    def set_password(self, password):
chirac's avatar
chirac committed
665
        """ A utiliser de préférence, set le password en hash courrant et
chirac's avatar
chirac committed
666
        dans la version ntlm"""
667
        super().set_password(password)
668 669 670
        self.pwd_ntlm = hashNT(password)
        return

671 672 673
    def get_next_domain_name(self):
        """Look for an available name for a new interface for
        this user by trying "pseudo0", "pseudo1", "pseudo2", ...
chirac's avatar
chirac committed
674 675 676

        Recherche un nom disponible, pour une machine. Doit-être
        unique, concatène le nom, le pseudo et le numero de machine
677 678 679
        """

        def simple_pseudo():
chirac's avatar
chirac committed
680
            """Renvoie le pseudo sans underscore (compat dns)"""
681 682
            return self.pseudo.replace('_', '-').lower()

chirac's avatar
chirac committed
683 684 685
        def composed_pseudo(name):
            """Renvoie le resultat de simplepseudo et rajoute le nom"""
            return simple_pseudo() + str(name)
686 687

        num = 0
chirac's avatar
chirac committed
688
        while Domain.objects.filter(name=composed_pseudo(num)):
689 690 691
            num += 1
        return composed_pseudo(num)

692 693
    def can_edit(self, user_request, *_args, **_kwargs):
        """Check if a user can edit a user object.
694 695 696 697

        :param self: The user which is to be edited.
        :param user_request: The user who requests to edit self.
        :return: a message and a boolean which is True if self is a club and
698 699
            user_request one of its member, or if user_request is self, or if
            user_request has the 'cableur' right.
700
        """
701
        if self.is_class_club and user_request.is_class_adherent:
702 703 704
            if (self == user_request or
                    user_request.has_perm('users.change_user') or
                    user_request.adherent in self.club.administrators.all()):
705 706 707
                return True, None
            else:
                return False, u"Vous n'avez pas le droit d'éditer ce club"
708
        else:
709 710 711 712 713 714
            if self == user_request:
                return True, None
            elif user_request.has_perm('users.change_all_users'):
                return True, None
            elif user_request.has_perm('users.change_user'):
                if self.groups.filter(listright__critical=True):
715 716
                    return False, (u"Utilisateurs avec droits critiques, ne "
                                   "peut etre édité")
717
                elif self == AssoOption.get_cached_value('utilisateur_asso'):
718 719
                    return False, (u"Impossible d'éditer l'utilisateur asso "
                                   "sans droit change_all_users")
720 721 722
                else:
                    return True, None
            elif user_request.has_perm('users.change_all_users'):
723 724
                return True, None
            else:
725 726
                return False, (u"Vous ne pouvez éditer un autre utilisateur "
                               "que vous même")
727

728 729 730 731 732 733 734 735 736
    def can_change_password(self, user_request, *_args, **_kwargs):
        """Check if a user can change a user's password

        :param self: The user which is to be edited
        :param user_request: The user who request to edit self
        :returns: a message and a boolean which is True if self is a club
            and user_request one of it's admins, or if user_request is self,
            or if user_request has the right to change other's password
        """
737
        if self.is_class_club and user_request.is_class_adherent:
738 739 740
            if (self == user_request or
                    user_request.has_perm('users.change_user_password') or
                    user_request.adherent in self.club.administrators.all()):
741 742 743 744
                return True, None
            else:
                return False, u"Vous n'avez pas le droit d'éditer ce club"
        else:
745 746 747 748
            if (self == user_request or
                    user_request.has_perm('users.change_user_groups')):
                # Peut éditer les groupes d'un user,
                # c'est un privilège élevé, True
749
                return True, None
750 751
            elif (user_request.has_perm('users.change_user') and
                  not self.groups.all()):
752 753
                return True, None
            else:
754 755
                return False, (u"Vous ne pouvez éditer un autre utilisateur "
                               "que vous même")
756

757 758 759 760
    def check_selfpasswd(self, user_request, *_args, **_kwargs):
        """ Returns (True, None) if user_request is self, else returns
        (False, None)
        """
761 762
        return user_request == self, None

763
    @staticmethod
764 765 766 767 768 769 770
    def can_change_state(user_request, *_args, **_kwargs):
        """ Check if a user can change a state

        :param user_request: The user who request
        :returns: a message and a boolean which is True if the user has
        the right to change a state
        """
771 772 773 774
        return (
            user_request.has_perm('users.change_user_state'),
            "Droit requis pour changer l'état"
        )
775

776
    @staticmethod
777 778 779 780 781 782 783
    def can_change_shell(user_request, *_args, **_kwargs):
        """ Check if a user can change a shell

        :param user_request: The user who request
        :returns: a message and a boolean which is True if the user has
        the right to change a shell
        """
784 785 786 787
        return (
            user_request.has_perm('users.change_user_shell'),
            "Droit requis pour changer le shell"
        )
788

789
    @staticmethod
790 791 792 793 794 795 796
    def can_change_force(user_request, *_args, **_kwargs):
        """ Check if a user can change a force

        :param user_request: The user who request
        :returns: a message and a boolean which is True if the user has
        the right to change a force
        """
797 798 799 800
        return (
            user_request.has_perm('users.change_user_force'),
            "Droit requis pour forcer le déménagement"
        )
801 802

    @staticmethod
803 804 805 806 807 808 809
    def can_change_groups(user_request, *_args, **_kwargs):
        """ Check if a user can change a group

        :param user_request: The user who request
        :returns: a message and a boolean which is True if the user has
        the right to change a group
        """
810 811 812 813
        return (
            user_request.has_perm('users.change_user_groups'),
            "Droit requis pour éditer les groupes de l'user"
        )
814

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
815 816 817 818 819 820 821 822 823 824 825 826
    @staticmethod
    def can_change_is_superuser(user_request, *_args, **_kwargs):
        """ Check if an user can change a is_superuser flag

        :param user_request: The user who request
        :returns: a message and a boolean which is True if permission is granted.
        """
        return (
            user_request.is_superuser,
            "Droit superuser requis pour éditer le flag superuser"
        )

827
    def can_view(self, user_request, *_args, **_kwargs):
828 829 830 831 832
        """Check if an user can view an user object.

        :param self: The targeted user.
        :param user_request: The user who ask for viewing the target.
        :return: A boolean telling if the acces is granted and an explanation
833
            text
834
        """
835
        if self.is_class_club and user_request.is_class_adherent:
836 837 838 839
            if (self == user_request or
                    user_request.has_perm('users.view_user') or
                    user_request.adherent in self.club.administrators.all() or
                    user_request.adherent in self.club.members.all()):
840 841 842
                return True, None
            else:
                return False, u"Vous n'avez pas le droit de voir ce club"
843
        else:
844 845
            if (self == user_request or
                    user_request.has_perm('users.view_user')):
846 847
                return True, None
            else:
848 849
                return False, (u"Vous ne pouvez voir un autre utilisateur "
                               "que vous même")
850

851 852
    @staticmethod
    def can_view_all(user_request, *_args, **_kwargs):
853 854 855
        """Check if an user can access to the list of every user objects

        :param user_request: The user who wants to view the list.
856 857
        :return: True if the user can view the list and an explanation
            message.
858
        """
859 860 861 862
        return (
            user_request.has_perm('users.view_user'),
            u"Vous n'avez pas accès à la liste des utilisateurs."
        )
863

864
    def can_delete(self, user_request, *_args, **_kwargs):
865 866 867 868
        """Check if an user can delete an user object.

        :param self: The user who is to be deleted.
        :param user_request: The user who requests deletion.
869 870
        :return: True if user_request has the right 'bureau', and a
            message.
871
        """
872 873 874 875
        return (
            user_request.has_perm('users.delete_user'),
            u"Vous ne pouvez pas supprimer cet utilisateur."
        )
876

877 878 879
    def __init__(self, *args, **kwargs):
        super(User, self).__init__(*args, **kwargs)
        self.field_permissions = {
880 881 882
            'shell': self.can_change_shell,
            'force': self.can_change_force,
            'selfpasswd': self.check_selfpasswd,
883 884
        }

885
    def __str__(self):
886
        return self.pseudo
lhark's avatar
lhark committed
887

chirac's avatar
chirac committed
888

889
class Adherent(User):
890 891
    """ A class representing a member (it's a user with special
    informations) """
Gabriel Detraz's avatar
Gabriel Detraz committed
892
    PRETTY_NAME = "Adhérents"
893
    name = models.CharField(max_length=255)
894 895 896 897 898 899
    room = models.OneToOneField(
        'topologie.Room',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
900

901 902
    @classmethod
    def get_instance(cls, adherentid, *_args, **_kwargs):
903
        """Try to find an instance of `Adherent` with the given id.
904

905 906 907
        :param adherentid: The id of the adherent we are looking for.
        :return: An adherent.
        """
908
        return cls.objects.get(pk=adherentid)
909

910 911
    @staticmethod
    def can_create(user_request, *_args, **_kwargs):
912 913 914 915
        """Check if an user can create an user object.

        :param user_request: The user who wants to create a user object.
        :return: a message and a boolean which is True if the user can create
916
            a user or if the `options.all_can_create` is set.
917
        """
918 919
        if (not user_request.is_authenticated and
                not OptionalUser.get_cached_value('self_adhesion')):
920 921
            return False, None
        else:
922 923
            if (OptionalUser.get_cached_value('all_can_create_adherent') or
                    OptionalUser.get_cached_value('self_adhesion')):
924 925
                return True, None
            else:
926 927 928 929
                return (
                    user_request.has_perm('users.add_user'),
                    u"Vous n'avez pas le droit de créer un utilisateur"
                )
930

931

932
class Club(User):
933 934
    """ A class representing a club (it is considered as a user
    with special informations) """
Gabriel Detraz's avatar
Gabriel Detraz committed
935
    PRETTY_NAME = "Clubs"
936 937 938 939 940 941
    room = models.ForeignKey(
        'topologie.Room',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
942 943 944 945 946 947 948 949 950 951
    administrators = models.ManyToManyField(
        blank=True,
        to='users.Adherent',
        related_name='club_administrator'
    )
    members = models.ManyToManyField(
        blank=True,
        to='users.Adherent',
        related_name='club_members'
    )
952
    mailing = models.BooleanField(
953
        default=False
954
    )
955

956 957
    @staticmethod
    def can_create(user_request, *_args, **_kwargs):
958 959 960 961
        """Check if an user can create an user object.

        :param user_request: The user who wants to create a user object.
        :return: a message and a boolean which is True if the user can create
962
            an user or if the `options.all_can_create` is set.
963 964 965 966 967 968 969
        """
        if not user_request.is_authenticated:
            return False, None
        else:
            if OptionalUser.get_cached_value('all_can_create_club'):
                return True, None
            else:
970 971 972 973
                return (
                    user_request.has_perm('users.add_user'),
                    u"Vous n'avez pas le droit de créer un club"
                )
974

975 976
    @staticmethod
    def can_view_all(user_request, *_args, **_kwargs):
977 978 979
        """Check if an user can access to the list of every user objects

        :param user_request: The user who wants to view the list.
980 981
        :return: True if the user can view the list and an explanation
            message.
982
        """
983
        if user_request.has_perm('users.view_user'):
984
            return True, None
985 986 987 988
        if (hasattr(user_request, 'is_class_adherent') and
                user_request.is_class_adherent):
            if (user_request.adherent.club_administrator.all() or
                    user_request.adherent.club_members.all()):
989 990 991
                return True, None
        return False, u"Vous n'avez pas accès à la liste des utilisateurs."

992 993
    @classmethod
    def get_instance(cls, clubid, *_args, **_kwargs):
994
        """Try to find an instance of `Club` with the given id.
995

996 997 998
        :param clubid: The id of the adherent we are looking for.
        :return: A club.
        """
999
        return cls.objects.get(pk=clubid)
1000

1001

1002 1003
@receiver(post_save, sender=Adherent)
@receiver(post_save, sender=Club)
1004
@receiver(post_save, sender=User)
1005
def user_post_save(**kwargs):
chirac's avatar
chirac committed
1006 1007
    """ Synchronisation post_save : envoie le mail de bienvenue si creation
    Synchronise le ldap"""
1008
    is_created = kwargs['created']
1009
    user = kwargs['instance']
1010 1011
    if is_created:
        user.notif_inscription()
1012 1013 1014 1015 1016 1017
    user.ldap_sync(
        base=True,
        access_refresh=True,
        mac_refresh=False,
        group_refresh=True
    )
1018
    regen('mailing')
1019

chirac's avatar
chirac committed
1020

1021 1022
@receiver(post_delete, sender=Adherent)
@receiver(post_delete, sender=Club)
1023
@receiver(post_delete, sender=User)
1024
def user_post_delete(**kwargs):
chirac's avatar
chirac committed
1025
    """Post delete d'un user, on supprime son instance ldap"""
1026
    user = kwargs['instance']
1027
    user.ldap_del()
1028
    regen('mailing')
1029

1030

1031
class ServiceUser(RevMixin, AclMixin, AbstractBaseUser):
chirac's avatar
chirac committed
1032
    """ Classe des users daemons, règle leurs accès au ldap"""
1033 1034
    readonly = 'readonly'
    ACCESS = (
chirac's avatar
chirac committed
1035 1036 1037 1038
        ('auth', 'auth'),
        ('readonly', 'readonly'),
        ('usermgmt', 'usermgmt'),
    )
1039

1040
    PRETTY_NAME = "Utilisateurs de service"
chirac's avatar
chirac committed
1041

chirac's avatar
chirac committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    pseudo = models.CharField(
        max_length=32,
        unique=True,
        help_text="Doit contenir uniquement des lettres, chiffres, ou tirets",
        validators=[linux_user_validator]
    )
    access_group = models.CharField(
        choices=ACCESS,
        default=readonly,
        max_length=32
    )
    comment = models.CharField(
        help_text="Commentaire",
        max_length=255,
        blank=True
    )
chirac's avatar
chirac committed
1058 1059 1060 1061

    USERNAME_FIELD = 'pseudo'
    objects = UserManager()

1062 1063 1064 1065 1066
    class Meta:
        permissions = (
            ("view_serviceuser", "Peut voir un objet serviceuser"),
        )

1067 1068 1069 1070 1071 1072 1073 1074
    def get_full_name(self):
        """ Renvoie le nom complet du serviceUser formaté nom/prénom"""
        return "ServiceUser <{name}>".format(name=self.pseudo)

    def get_short_name(self):
        """ Renvoie seulement le nom"""
        return self.pseudo

chirac's avatar
chirac committed
1075
    def ldap_sync(self):
chirac's avatar
chirac committed
1076
        """ Synchronisation du ServiceUser dans sa version ldap"""
chirac's avatar
chirac committed
1077 1078 1079 1080
        try:
            user_ldap = LdapServiceUser.objects.get(name=self.pseudo)
        except LdapServiceUser.DoesNotExist:
            user_ldap = LdapServiceUser(name=self.pseudo)
1081
        user_ldap.user_password = self.password[:6] + self.password[7:]
chirac's avatar
chirac committed
1082
        user_ldap.save()
1083
        self.serviceuser_group_sync()
chirac's avatar
chirac committed
1084 1085

    def ldap_del(self):
chirac's avatar
chirac committed
1086
        """Suppression de l'instance ldap d'un service user"""
chirac's avatar
chirac committed
1087 1088 1089 1090 1091
        try:
            user_ldap = LdapServiceUser.objects.get(name=self.pseudo)
            user_ldap.delete()
        except LdapUser.DoesNotExist:
            pass
1092 1093 1094
        self.serviceuser_group_sync()

    def serviceuser_group_sync(self):
chirac's avatar
chirac committed
1095
        """Synchronise le groupe et les droits de groupe dans le ldap"""
1096 1097 1098 1099
        try:
            group = LdapServiceUserGroup.objects.get(name=self.access_group)
        except:
            group = LdapServiceUserGroup(name=self.access_group)
chirac's avatar
chirac committed
1100 1101 1102 1103
        group.members = list(LdapServiceUser.objects.filter(
            name__in=[user.pseudo for user in ServiceUser.objects.filter(
                access_group=self.access_group
            )]).values_list('dn', flat=True))
1104
        group.save()
chirac's avatar
chirac committed
1105

1106 1107
    def __str__(self):
        return self.pseudo
chirac's avatar
chirac committed
1108

1109

chirac's avatar
chirac committed
1110
@receiver(post_save, sender=ServiceUser)
1111
def service_user_post_save(**kwargs):
chirac's avatar
chirac committed
1112
    """ Synchronise un service user ldap après modification django"""
chirac's avatar
chirac committed
1113
    service_user = kwargs['instance']
1114
    service_user.ldap_sync()
chirac's avatar
chirac committed
1115

chirac's avatar
chirac committed
1116

chirac's avatar
chirac committed
1117
@receiver(post_delete, sender=ServiceUser)
1118
def service_user_post_delete(**kwargs):
chirac's avatar
chirac committed
1119
    """ Supprime un service user ldap après suppression django"""
chirac's avatar
chirac committed
1120
    service_user = kwargs['instance']
1121
    service_user.ldap_del()
chirac's avatar
chirac committed
1122

chirac's avatar
chirac committed
1123

1124
class School(RevMixin, AclMixin, models.Model):
chirac's avatar
chirac committed
1125
    """ Etablissement d'enseignement"""
Gabriel Detraz's avatar
Gabriel Detraz committed
1126
    PRETTY_NAME = "Établissements enregistrés"
1127

lhark's avatar
lhark committed
1128 1129
    name = models.CharField(max_length=255)

1130 1131 1132 1133 1134
    class Meta:
        permissions = (
            ("view_school", "Peut voir un objet school"),
        )

1135 1136 1137
    def __str__(self):
        return self.name

1138

1139
class ListRight(RevMixin, AclMixin, Group):
chirac's avatar
chirac committed
1140 1141
    """ Ensemble des droits existants. Chaque droit crée un groupe
    ldap synchronisé, avec gid.
chirac's avatar
chirac committed
1142
    Permet de gérer facilement les accès serveurs et autres
chirac's avatar
chirac committed
1143 1144
    La clef de recherche est le gid, pour cette raison là
    il n'est plus modifiable après creation"""
1145 1146
    PRETTY_NAME = "Liste des droits existants"

1147
    unix_name = models.CharField(
chirac's avatar
chirac committed
1148 1149 1150 1151
        max_length=255,
        unique=True,
        validators=[RegexValidator(
            '^[a-z]+$',
1152 1153
            message=("Les groupes unix ne peuvent contenir que des lettres "
                     "minuscules")
chirac's avatar
chirac committed
1154 1155
        )]
    )
1156
    gid = models.PositiveIntegerField(unique=True, null=True)
1157
    critical = models.BooleanField(default=False)
chirac's avatar
chirac committed
1158 1159 1160 1161 1162
    details = models.CharField(
        help_text="Description",
        max_length=255,
        blank=True
    )
1163

1164 1165 1166 1167 1168
    class Meta:
        permissions = (
            ("view_listright", "Peut voir un objet Group/ListRight"),
        )

1169
    def __str__(self):
1170
        return self.name
1171

1172
    def ldap_sync(self):
chirac's avatar
chirac committed
1173
        """Sychronise les groups ldap avec le model listright coté django"""
1174 1175 1176 1177 1178
        try:
            group_ldap = LdapUserGroup.objects.get(gid=self.gid)
        except LdapUserGroup.DoesNotExist:
            group_ldap = LdapUserGroup(gid=self.gid)
        group_ldap.name = self.listright
1179 1180
        group_ldap.members = [user.pseudo for user
                              in self.user_set.all()]
1181 1182 1183
        group_ldap.save()

    def ldap_del(self):
chirac's avatar
chirac committed
1184
        """Supprime un groupe ldap"""
1185 1186 1187 1188 1189 1190
        try:
            group_ldap = LdapUserGroup.objects.get(gid=self.gid)
            group_ldap.delete()
        except LdapUserGroup.DoesNotExist:
            pass

chirac's avatar
chirac committed
1191

1192
@receiver(post_save, sender=ListRight)
1193
def listright_post_save(**kwargs):
chirac's avatar
chirac committed
1194
    """ Synchronise le droit ldap quand il est modifié"""
1195
    right = kwargs['instance']
1196
    right.ldap_sync()
1197

chirac's avatar
chirac committed
1198

1199
@receiver(post_delete, sender=ListRight)
1200
def listright_post_delete(**kwargs):
chirac's avatar
chirac committed
1201
    """Suppression d'un groupe ldap après suppression coté django"""
1202
    right = kwargs['instance']
1203
    right.ldap_del()
1204

chirac's avatar
chirac committed
1205

1206
class ListShell(RevMixin, AclMixin, models.Model):
chirac's avatar
chirac committed
1207 1208
    """Un shell possible. Pas de check si ce shell existe, les
    admin sont des grands"""
1209 1210
    PRETTY_NAME = "Liste des shells disponibles"

1211 1212
    shell = models.CharField(max_length=255, unique=True)

1213 1214 1215 1216 1217
    class Meta:
        permissions = (
            ("view_listshell", "Peut voir un objet shell quelqu'il soit"),
        )

Krokmou's avatar
Krokmou committed
1218 1219 1220 1221
    def get_pretty_name(self):
        """Return the canonical name of the shell"""
        return self.shell.split("/")[-1]

1222 1223
    def __str__(self):
        return self.shell
1224

chirac's avatar
chirac committed
1225

1226
class Ban(RevMixin, AclMixin, models.Model):
chirac's avatar
chirac committed
1227 1228
    """ Bannissement. Actuellement a un effet tout ou rien.
    Gagnerait à être granulaire"""
1229 1230
    PRETTY_NAME = "Liste des bannissements"

1231 1232 1233 1234
    STATE_HARD = 0
    STATE_SOFT = 1
    STATE_BRIDAGE = 2
    STATES = (
chirac's avatar
chirac committed
1235 1236 1237 1238
        (0, 'HARD (aucun accès)'),
        (1, 'SOFT (accès local seulement)'),
        (2, 'BRIDAGE (bridage du débit)'),
    )
1239

chirac's avatar
chirac committed
1240 1241
    user = models.ForeignKey('User', on_delete=models.PROTECT)
    raison = models.CharField(max_length=255)
1242