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 72.2 KB
Newer Older
1
# -*- mode: python; coding: utf-8 -*-
2 3 4 5
# 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.
#
6
# Copyright © 2016-2018  Gabriel Détraz
7 8
# Copyright © 2017  Goulven Kermarec
# Copyright © 2017  Augustin Lemesle
9
# Copyright © 2018  Charlie Jacomme
10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# 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.
24 25 26
"""machines.models
The models definitions for the Machines app
"""
27

28 29
from __future__ import unicode_literals

Gabriel Detraz's avatar
Gabriel Detraz committed
30 31
from datetime import timedelta
import re
32
from ipaddress import IPv6Address
33
from itertools import chain
34
from netaddr import mac_bare, EUI, IPSet, IPRange, IPNetwork, IPAddress
35 36
import hashlib
import base64
Gabriel Detraz's avatar
Gabriel Detraz committed
37

38
from django.db import models
39
from django.db.models import Q
Gabriel Detraz's avatar
Gabriel Detraz committed
40
from django.db.models.signals import post_save, post_delete
41
from django.dispatch import receiver
42
from django.forms import ValidationError
43
from django.utils.functional import cached_property
44
from django.utils import timezone
45
from django.core.validators import MaxValueValidator, MinValueValidator
46
from django.utils.translation import ugettext_lazy as _
Gabriel Detraz's avatar
Gabriel Detraz committed
47

48
from macaddress.fields import MACAddressField
49

50
from re2o.field_permissions import FieldPermissionModelMixin
51
from re2o.mixins import AclMixin, RevMixin
52

Maël Kervella's avatar
Maël Kervella committed
53 54 55
import users.models
import preferences.models

56

57
class Machine(RevMixin, FieldPermissionModelMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
58 59
    """ Class définissant une machine, object parent user, objets fils
    interfaces"""
60
    user = models.ForeignKey('users.User', on_delete=models.PROTECT)
Gabriel Detraz's avatar
Gabriel Detraz committed
61 62
    name = models.CharField(
        max_length=255,
63
        help_text=_("Optional"),
Gabriel Detraz's avatar
Gabriel Detraz committed
64 65 66
        blank=True,
        null=True
    )
67
    active = models.BooleanField(default=True)
68

69 70
    class Meta:
        permissions = (
71
            ("view_machine", _("Can view a machine object")),
72
            ("change_machine_user",
73
             _("Can change the user of a machine")),
74
        )
75 76
        verbose_name = _("machine")
        verbose_name_plural = _("machines")
77

78 79
    @classmethod
    def get_instance(cls, machineid, *_args, **_kwargs):
80 81 82 83
        """Get the Machine instance with machineid.
        :param userid: The id
        :return: The user
        """
84
        return cls.objects.get(pk=machineid)
85

86 87 88
    def linked_objects(self):
        """Return linked objects : machine and domain.
        Usefull in history display"""
89 90 91 92 93 94
        return chain(
            self.interface_set.all(),
            Domain.objects.filter(
                interface_parent__in=self.interface_set.all()
            )
        )
95

96
    @staticmethod
97
    def can_change_user(user_request, *_args, **_kwargs):
98 99 100 101 102 103 104 105 106 107
        """Checks if an user is allowed to change the user who owns a
        Machine.

        Args:
            user_request: The user requesting to change owner.

        Returns:
            A tuple with a boolean stating if edition is allowed and an
            explanation message.
        """
108
        return (user_request.has_perm('machines.change_machine_user'),
109
                _("You don't have the right to change the machine's user."))
110

111 112
    @staticmethod
    def can_view_all(user_request, *_args, **_kwargs):
113 114 115 116 117
        """Vérifie qu'on peut bien afficher l'ensemble des machines,
        droit particulier correspondant
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
        if not user_request.has_perm('machines.view_machine'):
118 119
            return False, _("You don't have the right to view all the"
                             " machines.")
120 121
        return True, None

122 123
    @staticmethod
    def can_create(user_request, userid, *_args, **_kwargs):
124 125 126 127 128
        """Vérifie qu'un user qui fait la requète peut bien créer la machine
        et n'a pas atteint son quota, et crée bien une machine à lui
        :param user_request: Utilisateur qui fait la requête
        :param userid: id de l'user dont on va créer une machine
        :return: soit True, soit False avec la raison de l'échec"""
Maël Kervella's avatar
Maël Kervella committed
129
        try:
130
            user = users.models.User.objects.get(pk=userid)
Maël Kervella's avatar
Maël Kervella committed
131
        except users.models.User.DoesNotExist:
132
            return False, _("Nonexistent user.")
133 134 135 136
        max_lambdauser_interfaces = (preferences.models.OptionalMachine
                                     .get_cached_value(
                                         'max_lambdauser_interfaces'
                                     ))
137
        if not user_request.has_perm('machines.add_machine'):
138 139
            if not (preferences.models.OptionalMachine
                    .get_cached_value('create_machine')):
140
                return False, (_("You don't have the right to add a machine."))
Maël Kervella's avatar
Maël Kervella committed
141
            if user != user_request:
142 143
                return False, (_("You don't have the right to add a machine"
                                 " to another user."))
Maël Kervella's avatar
Maël Kervella committed
144
            if user.user_interfaces().count() >= max_lambdauser_interfaces:
145 146 147
                return False, (_("You reached the maximum number of interfaces"
                                 " that you are allowed to create yourself"
                                 " (%s)." % max_lambdauser_interfaces))
Maël Kervella's avatar
Maël Kervella committed
148 149
        return True, None

150
    def can_edit(self, user_request, *args, **kwargs):
151 152 153 154 155
        """Vérifie qu'on peut bien éditer cette instance particulière (soit
        machine de soi, soit droit particulier
        :param self: instance machine à éditer
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison le cas échéant"""
156
        if self.user != user_request:
157 158 159 160 161 162
            if (not user_request.has_perm('machines.change_interface') or
                    not self.user.can_edit(
                        self.user,
                        user_request,
                        *args,
                        **kwargs
163 164 165
                    )[0]):
                return False, (_("You don't have the right to edit a machine"
                                 " of another user."))
166 167
        return True, None

168
    def can_delete(self, user_request, *args, **kwargs):
169 170 171 172 173
        """Vérifie qu'on peut bien supprimer cette instance particulière (soit
        machine de soi, soit droit particulier
        :param self: instance machine à supprimer
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
174
        if self.user != user_request:
175 176 177 178 179 180
            if (not user_request.has_perm('machines.change_interface') or
                    not self.user.can_edit(
                        self.user,
                        user_request,
                        *args,
                        **kwargs
181 182 183
                    )[0]):
                return False, _("You don't have the right to delete a machine"
                                 " of another user.")
184 185
        return True, None

186
    def can_view(self, user_request, *_args, **_kwargs):
187 188 189 190 191
        """Vérifie qu'on peut bien voir cette instance particulière (soit
        machine de soi, soit droit particulier
        :param self: instance machine à éditer
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
192 193
        if (not user_request.has_perm('machines.view_machine') and
                self.user != user_request):
194 195
            return False, _("You don't have the right to view other machines"
                             " than yours.")
196
        return True, None
197

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    @cached_property
    def short_name(self):
        """Par defaut, renvoie le nom de la première interface
        de cette machine"""
        return str(self.interface_set.first().domain.name)

    @cached_property
    def all_short_names(self):
        """Renvoie de manière unique, le nom des interfaces de cette
        machine"""
        return Domain.objects.filter(
            interface_parent__machine=self
            ).values_list('name', flat=True).distinct()

    @cached_property
    def all_complete_names(self):
        """Renvoie tous les tls complets de la machine"""
        return [str(domain) for domain in Domain.objects.filter(
            Q(cname__interface_parent__machine=self) | Q(interface_parent__machine=self)
            )]

219 220 221
    def __init__(self, *args, **kwargs):
        super(Machine, self).__init__(*args, **kwargs)
        self.field_permissions = {
222
            'user': self.can_change_user,
223 224
        }

225
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
226 227
        return str(self.user) + ' - ' + str(self.id) + ' - ' + str(self.name)

228

229
class MachineType(RevMixin, AclMixin, models.Model):
230
    """ Type de machine, relié à un type d'ip, affecté aux interfaces"""
231
    type = models.CharField(max_length=255)
Gabriel Detraz's avatar
Gabriel Detraz committed
232 233 234 235 236 237
    ip_type = models.ForeignKey(
        'IpType',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
238

239 240
    class Meta:
        permissions = (
241 242
            ("view_machinetype", _("Can view a machine type object")),
            ("use_all_machinetype", _("Can use all machine types")),
243
        )
244 245
        verbose_name = _("machine type")
        verbose_name_plural = _("machine types")
246

247
    def all_interfaces(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
248 249
        """ Renvoie toutes les interfaces (cartes réseaux) de type
        machinetype"""
250 251
        return Interface.objects.filter(type=self)

252 253
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
254 255 256 257 258 259 260 261
        """Check if an user can use every MachineType.

        Args:
            user_request: The user requesting edition.
        Returns:
            A tuple with a boolean stating if user can acces and an explanation
            message is acces is not allowed.
        """
262
        if not user_request.has_perm('machines.use_all_machinetype'):
263 264
            return False, (_("You don't have the right to use all machine"
                             " types."))
265 266
        return True, None

267
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
268 269
        return self.type

270

271
class IpType(RevMixin, AclMixin, models.Model):
272
    """ Type d'ip, définissant un range d'ip, affecté aux machine types"""
273
    type = models.CharField(max_length=255)
274
    extension = models.ForeignKey('Extension', on_delete=models.PROTECT)
275
    need_infra = models.BooleanField(default=False)
276 277
    domaine_ip_start = models.GenericIPAddressField(protocol='IPv4')
    domaine_ip_stop = models.GenericIPAddressField(protocol='IPv4')
278 279 280 281
    domaine_ip_network = models.GenericIPAddressField(
        protocol='IPv4',
        null=True,
        blank=True,
282
        help_text=_("Network containing the domain's IPv4 range (optional)")
283 284 285 286 287 288 289
    )
    domaine_ip_netmask = models.IntegerField(
        default=24,
        validators=[
            MaxValueValidator(31),
            MinValueValidator(8)
        ],
290
        help_text=_("Netmask for the domain's IPv4 range")
291
    )
292
    reverse_v4 = models.BooleanField(
293
            default=False, 
294
            help_text=_("Enable reverse DNS for IPv4"),
295
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
296 297 298 299 300
    prefix_v6 = models.GenericIPAddressField(
        protocol='IPv6',
        null=True,
        blank=True
    )
301 302 303 304 305 306 307
    prefix_v6_length = models.IntegerField(
        default=64,
        validators=[
            MaxValueValidator(128),
            MinValueValidator(0)
        ]
        )
308
    reverse_v6 = models.BooleanField(
309
            default=False,
310
            help_text=_("Enable reverse DNS for IPv6"),
311
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
312 313 314 315 316 317 318 319 320 321 322
    vlan = models.ForeignKey(
        'Vlan',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
    ouverture_ports = models.ForeignKey(
        'OuverturePortList',
        blank=True,
        null=True
    )
323

324 325
    class Meta:
        permissions = (
326 327
            ("view_iptype", _("Can view an IP type object")),
            ("use_all_iptype", _("Can use all IP types")),
328
        )
329 330
        verbose_name = _("IP type")
        verbose_name_plural = ("IP types")
331

332
    @cached_property
333
    def ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
334 335
        """ Renvoie un objet IPRange à partir de l'objet IpType"""
        return IPRange(self.domaine_ip_start, end=self.domaine_ip_stop)
336 337 338

    @cached_property
    def ip_set(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
339
        """ Renvoie une IPSet à partir de l'iptype"""
340
        return IPSet(self.ip_range)
341 342 343

    @cached_property
    def ip_set_as_str(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
344
        """ Renvoie une liste des ip en string"""
345 346
        return [str(x) for x in self.ip_set]

347 348 349 350 351
    @cached_property
    def ip_set_cidrs_as_str(self):
        """Renvoie la liste des cidrs du range en str"""
        return [str(ip_range) for ip_range in self.ip_set.iter_cidrs()]

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    @cached_property
    def ip_set_full_info(self):
        """Iter sur les range cidr, et renvoie network, broacast , etc"""
        return [
            {
                'network': str(ip_set.network),
                'netmask': str(ip_set.netmask),
                'netmask_cidr': str(ip_set.prefixlen),
                'broadcast': str(ip_set.broadcast),
                'vlan': str(self.vlan),
                'vlan_id': self.vlan.vlan_id
            } for ip_set in self.ip_set.iter_cidrs()
        ]

    @cached_property
    def ip6_set_full_info(self):
        if self.prefix_v6:
            return {
                'network' : str(self.prefix_v6),
                'netmask' : 'ffff:ffff:ffff:ffff::',
                'netmask_cidr' : str(self.prefix_v6_length),
                'vlan': str(self.vlan),
                'vlan_id': self.vlan.vlan_id
            }
        else:
            return None

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    @cached_property
    def ip_network(self):
        """Renvoie le network parent du range start-stop, si spécifié
        Différent de ip_set_cidrs ou iP_set, car lui est supérieur ou égal"""
        if self.domaine_ip_network:
            return IPNetwork(str(self.domaine_ip_network) + '/' + str(self.domaine_ip_netmask))
        return None

    @cached_property
    def ip_net_full_info(self):
        """Renvoie les infos du network contenant du range"""
        return {
            'network' : str(self.ip_network.network),
            'netmask' : str(self.ip_network.netmask),
            'broadcast' : str(self.ip_network.broadcast),
            'netmask_cidr' : str(self.ip_network.prefixlen),
        }

397 398 399
    @cached_property
    def complete_prefixv6(self):
        """Return the complete prefix v6 as cidr"""
400 401 402 403
        if self.prefix_v6:
            return str(self.prefix_v6) + "/" + str(self.prefix_v6_length)
        else:
            return None
404

405
    def ip_objects(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
406
        """ Renvoie tous les objets ipv4 relié à ce type"""
407 408 409
        return IpList.objects.filter(ip_type=self)

    def free_ip(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
410
        """ Renvoie toutes les ip libres associées au type donné (self)"""
Gabriel Detraz's avatar
Gabriel Detraz committed
411 412 413
        return IpList.objects.filter(
            interface__isnull=True
        ).filter(ip_type=self)
414 415

    def gen_ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
416 417 418
        """ Cree les IpList associées au type self. Parcours pédestrement et
        crée les ip une par une. Si elles existent déjà, met à jour le type
        associé à l'ip"""
419
        # Creation du range d'ip dans les objets iplist
420
        ip_obj = [IpList(ip_type=self, ipv4=str(ip)) for ip in self.ip_range]
Gabriel Detraz's avatar
Gabriel Detraz committed
421
        listes_ip = IpList.objects.filter(
422
            ipv4__in=[str(ip) for ip in self.ip_range]
Gabriel Detraz's avatar
Gabriel Detraz committed
423
        )
424 425 426 427 428 429
        # Si il n'y a pas d'ip, on les crée
        if not listes_ip:
            IpList.objects.bulk_create(ip_obj)
        # Sinon on update l'ip_type
        else:
            listes_ip.update(ip_type=self)
430
        return
431 432

    def del_ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
433 434
        """ Methode dépréciée, IpList est en mode cascade et supprimé
        automatiquement"""
435
        if Interface.objects.filter(ipv4__in=self.ip_objects()):
436 437 438
            raise ValidationError(_("One or several IP addresses from the"
                                    " range are affected, impossible to delete"
                                    " the range."))
439 440 441
        for ip in self.ip_objects():
            ip.delete()

442 443 444 445 446
    def check_replace_prefixv6(self):
        """Remplace les prefixv6 des interfaces liées à ce type d'ip"""
        if not self.prefix_v6:
            return
        else:
447
            for ipv6 in Ipv6List.objects.filter(
448 449 450 451
                interface__in=Interface.objects.filter(
                    type__in=MachineType.objects.filter(ip_type=self)
                )
            ):
452 453
                ipv6.check_and_replace_prefix(prefix=self.prefix_v6)

454 455
    def get_associated_ptr_records(self):
        from re2o.utils import all_active_assigned_interfaces
456 457 458 459 460 461
        if self.reverse_v4:
            return (all_active_assigned_interfaces()
                    .filter(type__ip_type=self)
                    .filter(ipv4__isnull=False))
        else:
            return None
462 463 464

    def get_associated_ptr_v6_records(self):
        from re2o.utils import all_active_interfaces
465 466 467 468 469
        if self.reverse_v6:
            return (all_active_interfaces(full=True)
                    .filter(type__ip_type=self))
        else:
            return None
470

471
    def clean(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
472 473 474 475 476
        """ Nettoyage. Vérifie :
        - Que ip_stop est après ip_start
        - Qu'on ne crée pas plus gros qu'un /16
        - Que le range crée ne recoupe pas un range existant
        - Formate l'ipv6 donnée en /64"""
477
        if IPAddress(self.domaine_ip_start) > IPAddress(self.domaine_ip_stop):
478
            raise ValidationError(_("Range end must be after range start..."))
479 480
        # On ne crée pas plus grand qu'un /16
        if self.ip_range.size > 65536:
481 482
            raise ValidationError(_("The range is too large, you can't create"
                                    " a larger one than a /16."))
483
        # On check que les / ne se recoupent pas
484
        for element in IpType.objects.all().exclude(pk=self.pk):
485
            if not self.ip_set.isdisjoint(element.ip_set):
486 487
                raise ValidationError(_("The specified range is not disjoint"
                                        " from existing ranges."))
488 489 490
        # On formate le prefix v6
        if self.prefix_v6:
            self.prefix_v6 = str(IPNetwork(self.prefix_v6 + '/64').network)
491 492 493
        # On vérifie qu'un domaine network/netmask contiens bien le domaine ip start-stop
        if self.domaine_ip_network:
            if not self.domaine_ip_start in self.ip_network or not self.domaine_ip_stop in self.ip_network:
494 495 496
                raise ValidationError(_("If you specify a domain network or"
                                        " netmask, it must contain the"
                                        " domain's IP range."))
497 498 499 500 501 502
        return

    def save(self, *args, **kwargs):
        self.clean()
        super(IpType, self).save(*args, **kwargs)

503 504
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
505 506
        """Superdroit qui permet d'utiliser toutes les extensions sans
        restrictions
507 508
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
509
        return user_request.has_perm('machines.use_all_iptype'), None
510

511 512
    def __str__(self):
        return self.type
chirac's avatar
chirac committed
513

Gabriel Detraz's avatar
Gabriel Detraz committed
514

515
class Vlan(RevMixin, AclMixin, models.Model):
516 517 518
    """ Un vlan : vlan_id et nom
    On limite le vlan id entre 0 et 4096, comme défini par la norme"""
    vlan_id = models.PositiveIntegerField(validators=[MaxValueValidator(4095)])
519 520 521
    name = models.CharField(max_length=256)
    comment = models.CharField(max_length=256, blank=True)

522 523
    class Meta:
        permissions = (
524
            ("view_vlan", _("Can view a VLAN object")),
525
        )
526 527
        verbose_name = _("VLAN")
        verbose_name_plural = _("VLANs")
528

529 530 531
    def __str__(self):
        return self.name

Gabriel Detraz's avatar
Gabriel Detraz committed
532

533
class Nas(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
534
    """ Les nas. Associé à un machine_type.
Gabriel Detraz's avatar
Gabriel Detraz committed
535 536
    Permet aussi de régler le port_access_mode (802.1X ou mac-address) pour
    le radius. Champ autocapture de la mac à true ou false"""
537 538 539 540 541 542
    default_mode = '802.1X'
    AUTH = (
        ('802.1X', '802.1X'),
        ('Mac-address', 'Mac-address'),
    )

543
    name = models.CharField(max_length=255, unique=True)
Gabriel Detraz's avatar
Gabriel Detraz committed
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
    nas_type = models.ForeignKey(
        'MachineType',
        on_delete=models.PROTECT,
        related_name='nas_type'
    )
    machine_type = models.ForeignKey(
        'MachineType',
        on_delete=models.PROTECT,
        related_name='machinetype_on_nas'
    )
    port_access_mode = models.CharField(
        choices=AUTH,
        default=default_mode,
        max_length=32
    )
559
    autocapture_mac = models.BooleanField(default=False)
560

561 562
    class Meta:
        permissions = (
563
            ("view_nas", _("Can view a NAS device object")),
564
        )
565 566
        verbose_name = _("NAS device")
        verbose_name_plural = _("NAS devices")
567

568 569 570
    def __str__(self):
        return self.name

Gabriel Detraz's avatar
Gabriel Detraz committed
571

572
class SOA(RevMixin, AclMixin, models.Model):
573 574 575 576 577
    """
    Un enregistrement SOA associé à une extension
    Les valeurs par défault viennent des recommandations RIPE :
    https://www.ripe.net/publications/docs/ripe-203
    """
578
    name = models.CharField(max_length=255)
579
    mail = models.EmailField(
580
        help_text=_("Contact email address for the zone")
581 582
    )
    refresh = models.PositiveIntegerField(
583
        default=86400,  # 24 hours
584 585
        help_text=_("Seconds before the secondary DNS have to ask the primary"
                    " DNS serial to detect a modification")
586 587
    )
    retry = models.PositiveIntegerField(
588
        default=7200,  # 2 hours
589 590
        help_text=_("Seconds before the secondary DNS ask the serial again in"
                    " case of a primary DNS timeout")
591 592
    )
    expire = models.PositiveIntegerField(
593
        default=3600000,  # 1000 hours
594 595
        help_text=_("Seconds before the secondary DNS stop answering requests"
                    " in case of primary DNS timeout")
596 597 598
    )
    ttl = models.PositiveIntegerField(
        default=172800,  # 2 days
599
        help_text=_("Time to Live")
600 601
    )

602 603
    class Meta:
        permissions = (
604
            ("view_soa", _("Can view an SOA record object")),
605
        )
606 607
        verbose_name = _("SOA record")
        verbose_name_plural = _("SOA records")
608

609 610 611 612 613 614 615 616 617 618 619 620 621
    def __str__(self):
        return str(self.name)

    @cached_property
    def dns_soa_param(self):
        """
        Renvoie la partie de l'enregistrement SOA correspondant aux champs :
            <refresh>   ; refresh
            <retry>     ; retry
            <expire>    ; expire
            <ttl>       ; TTL
        """
        return (
622 623 624 625
            '    {refresh}; refresh\n'
            '    {retry}; retry\n'
            '    {expire}; expire\n'
            '    {ttl}; TTL'
626
        ).format(
627 628 629 630
            refresh=str(self.refresh).ljust(12),
            retry=str(self.retry).ljust(12),
            expire=str(self.expire).ljust(12),
            ttl=str(self.ttl).ljust(12)
631 632 633 634 635 636
        )

    @cached_property
    def dns_soa_mail(self):
        """ Renvoie le mail dans l'enregistrement SOA """
        mail_fields = str(self.mail).split('@')
637
        return mail_fields[0].replace('.', '\\.') + '.' + mail_fields[1] + '.'
638 639 640 641 642 643 644

    @classmethod
    def new_default_soa(cls):
        """ Fonction pour créer un SOA par défaut, utile pour les nouvelles
        extensions .
        /!\ Ne jamais supprimer ou renommer cette fonction car elle est
        utilisée dans les migrations de la BDD. """
645
        return cls.objects.get_or_create(
646
            name=_("SOA to edit"),
647 648
            mail="postmaser@example.com"
        )[0].pk
649 650


651
class Extension(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
652 653
    """ Extension dns type example.org. Précise si tout le monde peut
    l'utiliser, associé à un origin (ip d'origine)"""
Gabriel Detraz's avatar
Gabriel Detraz committed
654 655 656
    name = models.CharField(
        max_length=255,
        unique=True,
657
        help_text=_("Zone name, must begin with a dot (.example.org)")
Gabriel Detraz's avatar
Gabriel Detraz committed
658
    )
659
    need_infra = models.BooleanField(default=False)
660
    origin = models.ForeignKey(
Gabriel Detraz's avatar
Gabriel Detraz committed
661 662 663
        'IpList',
        on_delete=models.PROTECT,
        blank=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
664
        null=True,
665
        help_text=_("A record associated with the zone")
Gabriel Detraz's avatar
Gabriel Detraz committed
666
    )
667 668 669
    origin_v6 = models.GenericIPAddressField(
        protocol='IPv6',
        null=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
670
        blank=True,
671
        help_text=_("AAAA record associated with the zone")
672
    )
673 674
    soa = models.ForeignKey(
        'SOA',
675
        on_delete=models.CASCADE
676
    )
677

678 679
    class Meta:
        permissions = (
680 681
            ("view_extension", _("Can view an extension object")),
            ("use_all_extension", _("Can use all extensions")),
682
        )
683 684
        verbose_name = _("DNS extension")
        verbose_name_plural = _("DNS extensions")
685

686 687
    @cached_property
    def dns_entry(self):
688 689 690
        """ Une entrée DNS A et AAAA sur origin (zone self)"""
        entry = ""
        if self.origin:
691
            entry += "@               IN  A       " + str(self.origin)
692 693 694
        if self.origin_v6:
            if entry:
                entry += "\n"
695
            entry += "@               IN  AAAA    " + str(self.origin_v6)
696
        return entry
697

698
    def get_associated_sshfp_records(self):
699 700 701
        from re2o.utils import all_active_assigned_interfaces
        return (all_active_assigned_interfaces()
                .filter(type__ip_type__extension=self)
702
                .filter(machine__id__in=SshFp.objects.values('machine')))
703

704
    def get_associated_a_records(self):
705 706
        from re2o.utils import all_active_assigned_interfaces
        return (all_active_assigned_interfaces()
707
                .filter(type__ip_type__extension=self)
708
                .filter(ipv4__isnull=False))
709 710

    def get_associated_aaaa_records(self):
711 712 713
        from re2o.utils import all_active_interfaces
        return (all_active_interfaces(full=True)
                .filter(type__ip_type__extension=self))
714 715

    def get_associated_cname_records(self):
716
        from re2o.utils import all_active_assigned_interfaces
717 718
        return (Domain.objects
                .filter(extension=self)
Charlie Jacomme's avatar
Charlie Jacomme committed
719
                .filter(cname__interface_parent__in=all_active_assigned_interfaces())
720
                .prefetch_related('cname'))
721

722 723
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
724 725
        """Superdroit qui permet d'utiliser toutes les extensions sans
        restrictions
726 727
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
728
        return user_request.has_perm('machines.use_all_extension'), None
729

730 731
    def __str__(self):
        return self.name
chirac's avatar
chirac committed
732

733
    def clean(self, *args, **kwargs):
Gabriel Detraz's avatar
Gabriel Detraz committed
734
        if self.name and self.name[0] != '.':
735
            raise ValidationError(_("An extension must begin with a dot."))
Gabriel Detraz's avatar
Gabriel Detraz committed
736 737
        super(Extension, self).clean(*args, **kwargs)

Gabriel Detraz's avatar
Gabriel Detraz committed
738

739
class Mx(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
740 741
    """ Entrées des MX. Enregistre la zone (extension) associée et la
    priorité
Gabriel Detraz's avatar
Gabriel Detraz committed
742
    Todo : pouvoir associer un MX à une interface """
743
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
744 745
    priority = models.PositiveIntegerField()
    name = models.ForeignKey('Domain', on_delete=models.PROTECT)
746

747 748
    class Meta:
        permissions = (
749
            ("view_mx", _("Can view an MX record object")),
750
        )
751 752
        verbose_name = _("MX record")
        verbose_name_plural = _("MX records")
753

754 755
    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
756 757
        """Renvoie l'entrée DNS complète pour un MX à mettre dans les
        fichiers de zones"""
758 759
        return "@               IN  MX  {prior} {name}".format(
            prior=str(self.priority).ljust(3),
Maël Kervella's avatar
Maël Kervella committed
760
            name=str(self.name)
761
        )
762

763 764 765
    def __str__(self):
        return str(self.zone) + ' ' + str(self.priority) + ' ' + str(self.name)

Gabriel Detraz's avatar
Gabriel Detraz committed
766

767
class Ns(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
768
    """Liste des enregistrements name servers par zone considéérée"""
769
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
770
    ns = models.ForeignKey('Domain', on_delete=models.PROTECT)
771

772 773
    class Meta:
        permissions = (
774
            ("view_ns", _("Can view an NS record object")),
775
        )
776 777
        verbose_name = _("NS record")
        verbose_name_plural = _("NS records")
778

779 780
    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
781
        """Renvoie un enregistrement NS complet pour les filezones"""
782
        return "@               IN  NS      " + str(self.ns)
783

784
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
785
        return str(self.zone) + ' ' + str(self.ns)
786

Gabriel Detraz's avatar
Gabriel Detraz committed
787

788
class Txt(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
789
    """ Un enregistrement TXT associé à une extension"""
Gabriel Detraz's avatar
Gabriel Detraz committed
790 791
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
    field1 = models.CharField(max_length=255)
792
    field2 = models.TextField(max_length=2047)
Gabriel Detraz's avatar
Gabriel Detraz committed
793

794 795
    class Meta:
        permissions = (
796
            ("view_txt", _("Can view a TXT record object")),
797
        )
798 799
        verbose_name = _("TXT record")
        verbose_name_plural = _("TXT records")
800

Gabriel Detraz's avatar
Gabriel Detraz committed
801
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
802 803
        return str(self.zone) + " : " + str(self.field1) + " " +\
            str(self.field2)
Gabriel Detraz's avatar
Gabriel Detraz committed
804 805 806

    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
807
        """Renvoie l'enregistrement TXT complet pour le fichier de zone"""
808
        return str(self.field1).ljust(15) + " IN  TXT     " + str(self.field2)
Gabriel Detraz's avatar
Gabriel Detraz committed
809

Gabriel Detraz's avatar
Gabriel Detraz committed
810

Charlie Jacomme's avatar
Charlie Jacomme committed
811
class DName(RevMixin, AclMixin, models.Model):
Maël Kervella's avatar
Maël Kervella committed
812
    """A DNAME entry for the DNS."""
Charlie Jacomme's avatar
Charlie Jacomme committed
813 814 815 816 817
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
    alias = models.CharField(max_length=255)

    class Meta:
        permissions = (
818
            ("view_dname", _("Can view a DNAME record object")),
Charlie Jacomme's avatar
Charlie Jacomme committed
819
        )
820 821
        verbose_name = _("DNAME record")
        verbose_name_plural = _("DNAME records")
Charlie Jacomme's avatar
Charlie Jacomme committed
822 823 824 825 826 827

    def __str__(self):
        return str(self.zone) + " : " + str(self.alias)

    @cached_property
    def dns_entry(self):
Maël Kervella's avatar
Maël Kervella committed
828
        """Returns the DNAME record for the DNS zone file."""
chirac's avatar
chirac committed
829
        return str(self.alias).ljust(15) + " IN  DNAME   " + str(self.zone)
Charlie Jacomme's avatar
Charlie Jacomme committed
830 831


832
class Srv(RevMixin, AclMixin, models.Model):
833
    """ A SRV record """
Gabriel Detraz's avatar
Gabriel Detraz committed
834 835 836
    TCP = 'TCP'
    UDP = 'UDP'

837
    service = models.CharField(max_length=31)
Gabriel Detraz's avatar
Gabriel Detraz committed
838 839 840 841 842
    protocole = models.CharField(
        max_length=3,
        choices=(
            (TCP, 'TCP'),
            (UDP, 'UDP'),
843
        ),
Gabriel Detraz's avatar
Gabriel Detraz committed
844 845 846 847 848
        default=TCP,
    )
    extension = models.ForeignKey('Extension', on_delete=models.PROTECT)
    ttl = models.PositiveIntegerField(
        default=172800,  # 2 days
849
        help_text=_("Time to Live")
Gabriel Detraz's avatar
Gabriel Detraz committed
850 851
    )
    priority = models.PositiveIntegerField(
852
        default=0,
Gabriel Detraz's avatar
Gabriel Detraz committed
853
        validators=[MaxValueValidator(65535)],
854 855 856
        help_text=_("Priority of the target server (positive integer value,"
                    " the lower it is, the more the server will be used if"
                    " available)")
Gabriel Detraz's avatar
Gabriel Detraz committed
857 858
    )
    weight = models.PositiveIntegerField(
859
        default=0,
Gabriel Detraz's avatar
Gabriel Detraz committed
860
        validators=[MaxValueValidator(65535)],
861 862
        help_text=_("Relative weight for records with the same priority"
                     " (integer value between 0 and 65535)")
Gabriel Detraz's avatar
Gabriel Detraz committed
863 864 865
    )
    port = models.PositiveIntegerField(
        validators=[MaxValueValidator(65535)],
866
        help_text=_("TCP/UDP port")
Gabriel Detraz's avatar
Gabriel Detraz committed
867 868 869 870
    )
    target = models.ForeignKey(
        'Domain',
        on_delete=models.PROTECT,
871
        help_text=_("Target server")
Gabriel Detraz's avatar
Gabriel Detraz committed
872 873
    )

874 875
    class Meta:
        permissions = (
876
            ("view_srv", _("Can view an SRV record object")),
877
        )
878 879
        verbose_name = _("SRV record")
        verbose_name_plural = _("SRV records")
880

Gabriel Detraz's avatar
Gabriel Detraz committed
881 882 883 884 885 886 887 888 889 890 891 892 893 894
    def __str__(self):
        return str(self.service) + ' ' + str(self.protocole) + ' ' +\
            str(self.extension) + ' ' + str(self.priority) +\
            ' ' + str(self.weight) + str(self.port) + str(self.target)

    @cached_property
    def dns_entry(self):
        """Renvoie l'enregistrement SRV complet pour le fichier de zone"""
        return str(self.service) + '._' + str(self.protocole).lower() +\
            str(self.extension) + '. ' + str(self.ttl) + ' IN SRV ' +\
            str(self.priority) + ' ' + str(self.weight) + ' ' +\
            str(self.port) + ' ' + str(self.target) + '.'


895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
class SshFp(RevMixin, AclMixin, models.Model):
    """A fingerprint of an SSH public key"""

    ALGO = (
        ("ssh-rsa", "ssh-rsa"),
        ("ssh-ed25519", "ssh-ed25519"),
        ("ecdsa-sha2-nistp256", "ecdsa-sha2-nistp256"),
        ("ecdsa-sha2-nistp384", "ecdsa-sha2-nistp384"),
        ("ecdsa-sha2-nistp521", "ecdsa-sha2-nistp521"),
    )

    machine = models.ForeignKey('Machine', on_delete=models.CASCADE)
    pub_key_entry = models.TextField(
        help_text="SSH public key",
        max_length=2048
    )
    algo = models.CharField(
        choices=ALGO,
        max_length=32
    )
    comment = models.CharField(
        help_text="Comment",
        max_length=255,
        null=True,
        blank=True
    )

    @cached_property
    def algo_id(self):
        """Return the id of the algorithm for this key"""
        if "ecdsa" in self.algo:
            return 3
        elif "rsa" in self.algo:
            return 1
        else:
            return 2

    @cached_property
    def hash(self):
        """Return the hashess for the pub key with correct id
        cf RFC, 1 is sha1 , 2 sha256"""
        return {
            "1" : hashlib.sha1(base64.b64decode(self.pub_key_entry)).hexdigest(),
            "2" : hashlib.sha256(base64.b64decode(self.pub_key_entry)).hexdigest(),
        }

    class Meta:
        permissions = (
943
            ("view_sshfp", _("Can view an SSHFP record object")),
944
        )
945 946
        verbose_name = _("SSHFP record")
        verbose_name_plural = _("SSHFP records")
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961

    def can_view(self, user_request, *_args, **_kwargs):
        return self.machine.can_view(user_request, *_args, **_kwargs)

    def can_edit(self, user_request, *args, **kwargs):
        return self.machine.can_edit(user_request, *args, **kwargs)

    def can_delete(self, user_request, *args, **kwargs):
        return self.machine.can_delete(user_request, *args, **kwargs)

    def __str__(self):
        return str(self.algo) + ' ' + str(self.comment)



962
class Interface(RevMixin, AclMixin, FieldPermissionModelMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
963 964 965
    """ Une interface. Objet clef de l'application machine :
    - une address mac unique. Possibilité de la rendre unique avec le
    typemachine
Gabriel Detraz's avatar
Gabriel Detraz committed
966 967 968 969
    - une onetoone vers IpList pour attribution ipv4
    - le type parent associé au range ip et à l'extension
    - un objet domain associé contenant son nom
    - la liste des ports oiuvert"""
Gabriel Detraz's avatar
Gabriel Detraz committed
970 971 972 973 974 975
    ipv4 = models.OneToOneField(
        'IpList',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
976
    mac_address = MACAddressField(integer=False)
977
    machine = models.ForeignKey('Machine', on_delete=models.CASCADE)
978
    type = models.ForeignKey('MachineType', on_delete=models.PROTECT)
979
    details = models.CharField(max_length=255, blank=True)
980
    port_lists = models.ManyToManyField('OuverturePortList', blank=True)
chirac's avatar
chirac committed
981

982 983
    class Meta:
        permissions = (
984
            ("view_interface", _("Can view an interface object")),
985
            ("change_interface_machine",
986
             _("Can change the owner of an interface")),
987
        )
988 989
        verbose_name = _("interface")
        verbose_name_plural = _("interfaces")
990

991
    @cached_property
Dalahro's avatar
Dalahro committed
992 993 994 995
    def is_active(self):
        """ Renvoie si une interface doit avoir accès ou non """
        machine = self.machine
        user = self.machine.user
996
        return machine.active and user.has_access()
Dalahro's avatar
Dalahro committed
997

998
    @cached_property
999
    def ipv6_slaac(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1000 1001
        """ Renvoie un objet type ipv6 à partir du prefix associé à
        l'iptype parent"""
1002
        if self.type.ip_type.prefix_v6:
Gabriel Detraz's avatar
Gabriel Detraz committed
1003 1004 1005
            return EUI(self.mac_address).ipv6(
                IPNetwork(self.type.ip_type.prefix_v6).network
            )
1006 1007 1008
        else:
            return None

1009 1010 1011
    @cached_property
    def gen_ipv6_dhcpv6(self):
        """Cree une ip, à assigner avec dhcpv6 sur une machine"""
1012
        prefix_v6 = self.type.ip_type.prefix_v6.encode().decode('utf-8')
1013 1014
        if not prefix_v6:
            return None
1015 1016 1017 1018
        return IPv6Address(
            IPv6Address(prefix_v6).exploded[:20] +
            IPv6Address(self.id).exploded[20:]
        )
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

    def sync_ipv6_dhcpv6(self):
        """Affecte une ipv6 dhcpv6 calculée à partir de l'id de la machine"""
        ipv6_dhcpv6 = self.gen_ipv6_dhcpv6
        if not ipv6_dhcpv6:
            return
        ipv6 = Ipv6List.objects.filter(ipv6=str(ipv6_dhcpv6)).first()
        if not ipv6:
            ipv6 = Ipv6List(ipv6=str(ipv6_dhcpv6))
        ipv6.interface = self
        ipv6.save()
        return

1032 1033 1034 1035 1036 1037 1038 1039
    def sync_ipv6_slaac(self):
        """Cree, mets à jour et supprime si il y a lieu l'ipv6 slaac associée
        à la machine
        Sans prefixe ipv6, on return
        Si l'ip slaac n'est pas celle qu'elle devrait être, on maj"""
        ipv6_slaac = self.ipv6_slaac
        if not ipv6_slaac:
            return
1040 1041 1042
        ipv6_object = (Ipv6List.objects
                       .filter(interface=self, slaac_ip=True)
                       .first())
1043 1044 1045 1046 1047 1048
        if not ipv6_object:
            ipv6_object = Ipv6List(interface=self, slaac_ip=True)
        if ipv6_object.ipv6 != str(ipv6_slaac):
            ipv6_object.ipv6 = str(ipv6_slaac)
            ipv6_object.save()

1049 1050
    def sync_ipv6(self):
        """Cree et met à jour l'ensemble des ipv6 en fonction du mode choisi"""
1051 1052
        if (preferences.models.OptionalMachine
                .get_cached_value('ipv6_mode') == 'SLAAC'):
1053
            self.sync_ipv6_slaac()
1054 1055
        elif (preferences.models.OptionalMachine
              .get_cached_value('ipv6_mode') == 'DHCPV6'):
1056 1057 1058 1059
            self.sync_ipv6_dhcpv6()
        else:
            return

1060
    def ipv6(self):
1061
        """ Renvoie le queryset de la liste des ipv6
1062 1063 1064 1065
        On renvoie l'ipv6 slaac que si le mode slaac est activé
        (et non dhcpv6)"""
        if (preferences.models.OptionalMachine
                .get_cached_value('ipv6_mode') == 'SLAAC'):
1066
            return self.ipv6list.all()
1067 1068
        elif (preferences.models.OptionalMachine
              .get_cached_value('ipv6_mode') == 'DHCPV6'):
1069
            return self.ipv6list.filter(slaac_ip=False)
1070 1071
        else:
            return None
1072

1073
    def mac_bare(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1074
        """ Formatage de la mac type mac_bare"""
1075 1076
        return str(EUI(self.mac_address, dialect=mac_bare)).lower()

1077
    def filter_macaddress(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1078 1079
        """ Tente un formatage mac_bare, si échoue, lève une erreur de
        validation"""
1080 1081
        try:
            self.mac_address = str(EUI(self.mac_address))
Gabriel Detraz's avatar
Gabriel Detraz committed
1082
        except:
1083
            raise ValidationError(_("The given MAC address is invalid."))
1084

1085
    def clean(self, *args, **kwargs):
Gabriel Detraz's avatar
Gabriel Detraz committed
1086 1087
        """ Formate l'addresse mac en mac_bare (fonction filter_mac)
        et assigne une ipv4 dans le bon range si inexistante ou incohérente"""
1088 1089 1090 1091 1092 1093 1094
        # If type was an invalid value, django won't create an attribute type
        # but try clean() as we may be able to create it from another value
        # so even if the error as yet been detected at this point, django
        # continues because the error might not prevent us from creating the
        # instance.
        # But in our case, it's impossible to create a type value so we raise
        # the error.
1095
        if not hasattr(self, 'type'):
1096
            raise ValidationError(_("The selected IP type is invalid."))
1097
        self.filter_macaddress()
1098
        self.mac_address = str(EUI(self.mac_address)) or None
1099
        if not self.ipv4 or self.type.ip_type != self.ipv4.ip_type:
1100
            self.assign_ipv4()
1101
        super(Interface, self).clean(*args, **kwargs)
1102 1103 1104 1105 1106 1107 1108

    def assign_ipv4(self):
        """ Assigne une ip à l'interface """
        free_ips = self.type.ip_type.free_ip()
        if free_ips:
            self.ipv4 = free_ips[0]
        else:
1109 1110
            raise ValidationError(_("There is no IP address available in the"
                                    " slash."))
1111 1112 1113
        return

    def unassign_ipv4(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1114
        """ Sans commentaire, désassigne une ipv4"""
1115
        self.ipv4 = None
1116

1117 1118 1119 1120 1121
    def update_type(self):
        """ Lorsque le machinetype est changé de type d'ip, on réassigne"""
        self.clean()
        self.save()

1122
    def save(self, *args, **kwargs):
1123
        self.filter_macaddress()
1124
        # On verifie la cohérence en forçant l'extension par la méthode
1125 1126
        if self.ipv4:
            if self.type.ip_type != self.ipv4.ip_type:
1127 1128
                raise ValidationError(_("The IPv4 address and the machine type"
                                        " don't match."))
1129 1130
        super(Interface, self).save(*args, **kwargs)

1131 1132
    @staticmethod
    def can_create(user_request, machineid, *_args, **_kwargs):
1133 1134 1135 1136 1137
        """Verifie que l'user a les bons droits infra pour créer
        une interface, ou bien que la machine appartient bien à l'user
        :param macineid: Id de la machine parente de l'interface
        :param user_request: instance utilisateur qui fait la requête
        :return: soit True, soit False avec la raison de l'échec"""
1138
        try:
1139
            machine = Machine.objects.get(pk=machineid)
1140
        except Machine.DoesNotExist:
1141
            return False, _("Nonexistent machine.")
1142
        if not user_request.has_perm('machines.add_interface'):
1143 1144
            if not (preferences.models.OptionalMachine
                    .get_cached_value('create_machine')):
1145
                return False, _("You can't add a machine.")
1146 1147 1148 1149
            max_lambdauser_interfaces = (preferences.models.OptionalMachine
                                         .get_cached_value(
                                             'max_lambdauser_interfaces'
                                         ))
1150
            if machine.user != user_request:
1151 1152
                return False, _("You don't have the right to add an interface"
                                " to a machine of another user.")
1153 1154
            if (machine.user.user_interfaces().count() >=
                    max_lambdauser_interfaces):
1155 1156 1157
                return False, (_("You reached the maximum number of interfaces"
                                 " that you are allowed to create yourself"
                                 " (%s)." % max_lambdauser_interfaces))
1158 1159
        return True, None

1160
    @staticmethod
1161 1162 1163
    def can_change_machine(user_request, *_args, **_kwargs):
        """Check if a user can change the machine associated with an
        Interface object """
1164
        return (user_request.has_perm('machines.change_interface_machine'),
1165
                _("Permission required to edit the machine."))
1166

1167
    def can_edit(self, user_request, *args, **kwargs):
1168 1169 1170 1171 1172
        """Verifie que l'user a les bons droits infra pour editer
        cette instance interface, ou qu'elle lui appartient
        :param self: Instance interface à editer
        :param user_request: Utilisateur qui fait la requête
        :return: soit True, soit False avec la raison de l'échec"""
1173
        if self.machine.user != user_request:
1174 1175 1176 1177 1178
            if (not user_request.has_perm('machines.change_interface') or
                    not self.machine.user.can_edit(
                        user_request,
                        *args,
                        **kwargs
1179 1180 1181
                    )[0]):
                return False, _("You don't have the right to edit a machine of"
                                " another user.")
1182 1183
        return True, None

1184
    def can_delete(self, user_request, *args, **kwargs):
1185
        """Verifie que l'user a les bons droits delete object pour del
1186 1187 1188 1189
        cette instance interface, ou qu'elle lui appartient
        :param self: Instance interface à del
        :param user_request: Utilisateur qui fait la requête
        :return: soit True, soit False avec la raison de l'échec"""
Gabriel Detraz's avatar