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 12 KB
Newer Older
1
# -*- mode: python; coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# Re2o 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.
#
# 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.
23 24 25
"""
Reglages généraux, machines, utilisateurs, mail, general pour l'application.
"""
26
from __future__ import unicode_literals
27

28
from django.utils.functional import cached_property
29
from django.db import models
30
from django.db.models.signals import post_save
31
from django.dispatch import receiver
32
from django.core.cache import cache
33
from django.forms import ValidationError
34
from django.utils.translation import ugettext_lazy as _
35

36
import machines.models
chirac's avatar
chirac committed
37
from re2o.mixins import AclMixin
38

Maël Kervella's avatar
Maël Kervella committed
39

Gabriel Detraz's avatar
Gabriel Detraz committed
40
class PreferencesModel(models.Model):
41 42 43
    """ Base object for the Preferences objects
    Defines methods to handle the cache of the settings (they should
    not change a lot) """
Gabriel Detraz's avatar
Gabriel Detraz committed
44 45
    @classmethod
    def set_in_cache(cls):
46
        """ Save the preferences in a server-side cache """
Gabriel Detraz's avatar
Gabriel Detraz committed
47 48 49 50 51 52
        instance, _created = cls.objects.get_or_create()
        cache.set(cls().__class__.__name__.lower(), instance, None)
        return instance

    @classmethod
    def get_cached_value(cls, key):
53
        """ Get the preferences from the server-side cache """
Gabriel Detraz's avatar
Gabriel Detraz committed
54
        instance = cache.get(cls().__class__.__name__.lower())
Maël Kervella's avatar
Maël Kervella committed
55
        if instance is None:
56
            instance = cls.set_in_cache()
Gabriel Detraz's avatar
Gabriel Detraz committed
57 58 59 60 61 62
        return getattr(instance, key)

    class Meta:
        abstract = True


chirac's avatar
chirac committed
63
class OptionalUser(AclMixin, PreferencesModel):
64 65
    """Options pour l'user : obligation ou nom du telephone,
    activation ou non du solde, autorisation du negatif, fingerprint etc"""
66

67 68
    is_tel_mandatory = models.BooleanField(default=True)
    gpg_fingerprint = models.BooleanField(default=True)
69
    all_can_create_club = models.BooleanField(
70
        default=False,
71
        help_text=_("Users can create a club")
72 73 74
    )
    all_can_create_adherent = models.BooleanField(
        default=False,
75
        help_text=_("Users can create a member"),
76
    )
77 78
    self_adhesion = models.BooleanField(
        default=False,
79
        help_text=_("A new user can create their account on Re2o")
80
    )
81 82 83 84 85 86
    shell_default = models.OneToOneField(
        'users.ListShell',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
87 88
    self_change_shell = models.BooleanField(
        default=False,
89
        help_text=_("Users can edit their shell")
90
    )
91
    local_email_accounts_enabled = models.BooleanField(
92
        default=False,
93
        help_text=_("Enable local email accounts for users")
94
    )
95
    local_email_domain = models.CharField(
96 97 98
        max_length=32,
        default="@example.org",
        help_text=_("Domain to use for local email accounts")
99
    )
100
    max_email_address = models.IntegerField(
101 102 103
        default=15,
        help_text=_("Maximum number of local email addresses for a standard"
                    " user")
104
    )
105

106 107
    class Meta:
        permissions = (
108
            ("view_optionaluser", _("Can view the user options")),
109
        )
110
        verbose_name = _("user options")
111

112
    def clean(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
113 114
        """Clean model:
        Check the mail_extension
115
        """
116
        if self.local_email_domain[0] != "@":
117
            raise ValidationError(_("Email domain must begin with @"))
118

119

120
@receiver(post_save, sender=OptionalUser)
121
def optionaluser_post_save(**kwargs):
122
    """Ecriture dans le cache"""
123 124 125 126
    user_pref = kwargs['instance']
    user_pref.set_in_cache()


chirac's avatar
chirac committed
127
class OptionalMachine(AclMixin, PreferencesModel):
128 129
    """Options pour les machines : maximum de machines ou d'alias par user
    sans droit, activation de l'ipv6"""
130

131 132 133 134
    SLAAC = 'SLAAC'
    DHCPV6 = 'DHCPV6'
    DISABLED = 'DISABLED'
    CHOICE_IPV6 = (
135 136 137
        (SLAAC, _("Autoconfiguration by RA")),
        (DHCPV6, _("IP addresses assigning by DHCPv6")),
        (DISABLED, _("Disabled")),
138 139
    )

140 141 142
    password_machine = models.BooleanField(default=False)
    max_lambdauser_interfaces = models.IntegerField(default=10)
    max_lambdauser_aliases = models.IntegerField(default=10)
143 144 145 146 147
    ipv6_mode = models.CharField(
        max_length=32,
        choices=CHOICE_IPV6,
        default='DISABLED'
    )
148
    create_machine = models.BooleanField(
149
        default=True
150
    )
151 152 153

    @cached_property
    def ipv6(self):
154
        """ Check if the IPv6 option is activated """
Maël Kervella's avatar
Maël Kervella committed
155
        return not self.get_cached_value('ipv6_mode') == 'DISABLED'
156

157 158
    class Meta:
        permissions = (
159
            ("view_optionalmachine", _("Can view the machine options")),
160
        )
161
        verbose_name = _("machine options")
162

163

164
@receiver(post_save, sender=OptionalMachine)
165
def optionalmachine_post_save(**kwargs):
166
    """Synchronisation ipv6 et ecriture dans le cache"""
167
    machine_pref = kwargs['instance']
168
    machine_pref.set_in_cache()
169 170 171 172 173
    if machine_pref.ipv6_mode != "DISABLED":
        for interface in machines.models.Interface.objects.all():
            interface.sync_ipv6()


chirac's avatar
chirac committed
174
class OptionalTopologie(AclMixin, PreferencesModel):
175 176
    """Reglages pour la topologie : mode d'accès radius, vlan où placer
    les machines en accept ou reject"""
177 178 179
    MACHINE = 'MACHINE'
    DEFINED = 'DEFINED'
    CHOICE_RADIUS = (
180 181
        (MACHINE, _("On the IP range's VLAN of the machine")),
        (DEFINED, _("Preset in 'VLAN for machines accepted by RADIUS'")),
182
    )
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    radius_general_policy = models.CharField(
        max_length=32,
        choices=CHOICE_RADIUS,
        default='DEFINED'
    )
    vlan_decision_ok = models.OneToOneField(
        'machines.Vlan',
        on_delete=models.PROTECT,
        related_name='decision_ok',
        blank=True,
        null=True
    )
    vlan_decision_nok = models.OneToOneField(
        'machines.Vlan',
        on_delete=models.PROTECT,
        related_name='decision_nok',
        blank=True,
        null=True
    )
203

204 205
    class Meta:
        permissions = (
206
            ("view_optionaltopologie", _("Can view the topology options")),
207
        )
208
        verbose_name = _("topology options")
209

210

211
@receiver(post_save, sender=OptionalTopologie)
212
def optionaltopologie_post_save(**kwargs):
213
    """Ecriture dans le cache"""
214 215 216 217
    topologie_pref = kwargs['instance']
    topologie_pref.set_in_cache()


chirac's avatar
chirac committed
218
class GeneralOption(AclMixin, PreferencesModel):
219 220
    """Options générales : nombre de resultats par page, nom du site,
    temps où les liens sont valides"""
221

222
    general_message_fr = models.TextField(
223 224
        default="",
        blank=True,
225 226
        help_text=_("General message displayed on the French version of the"
                    " website (e.g. in case of maintenance)")
227 228 229 230
    )
    general_message_en = models.TextField(
        default="",
        blank=True,
231 232
        help_text=_("General message displayed on the English version of the"
                    " website (e.g. in case of maintenance)")
233
    )
234 235 236
    search_display_page = models.IntegerField(default=15)
    pagination_number = models.IntegerField(default=25)
    pagination_large_number = models.IntegerField(default=8)
237 238
    req_expire_hrs = models.IntegerField(default=48)
    site_name = models.CharField(max_length=32, default="Re2o")
239
    email_from = models.EmailField(default="www-data@example.com")
240 241 242 243 244
    GTU_sum_up = models.TextField(
        default="",
        blank=True,
    )
    GTU = models.FileField(
Maël Kervella's avatar
Maël Kervella committed
245
        upload_to='',
246 247 248 249
        default="",
        null=True,
        blank=True,
    )
250

251 252
    class Meta:
        permissions = (
253
            ("view_generaloption", _("Can view the general options")),
254
        )
255
        verbose_name = _("general options")
256

257

258
@receiver(post_save, sender=GeneralOption)
259
def generaloption_post_save(**kwargs):
260
    """Ecriture dans le cache"""
261 262 263 264
    general_pref = kwargs['instance']
    general_pref.set_in_cache()


chirac's avatar
chirac committed
265
class Service(AclMixin, models.Model):
266 267
    """Liste des services affichés sur la page d'accueil : url, description,
    image et nom"""
268 269 270
    name = models.CharField(max_length=32)
    url = models.URLField()
    description = models.TextField()
271
    image = models.ImageField(upload_to='logo', blank=True)
272

273 274
    class Meta:
        permissions = (
275
            ("view_service", _("Can view the service options")),
276
        )
277 278
        verbose_name = _("service")
        verbose_name_plural =_("services")
279

280 281 282
    def __str__(self):
        return str(self.name)

283
class MailContact(AclMixin, models.Model):
284
    """Contact email adress with a commentary."""
285 286 287

    address = models.EmailField(
        default = "contact@example.org",
288
        help_text = _("Contact email address")
289 290 291 292 293
    )

    commentary = models.CharField(
        blank = True,
        null = True,
294
        help_text = _(
295
            "Description of the associated email address."),
296 297 298
        max_length = 256
    )

299 300 301 302
    @cached_property
    def get_name(self):
        return self.address.split("@")[0]

303 304
    class Meta:
        permissions = (
305
            ("view_mailcontact", _("Can view a contact email address object")),
306
        )
307 308
        verbose_name = _("contact email address")
        verbose_name_plural = _("contact email addresses")
309 310 311 312

    def __str__(self):
        return(self.address)

313

chirac's avatar
chirac committed
314
class AssoOption(AclMixin, PreferencesModel):
315
    """Options générales de l'asso : siret, addresse, nom, etc"""
316

317
    name = models.CharField(
318
        default=_("Networking organisation school Something"),
319 320
        max_length=256
    )
321
    siret = models.CharField(default="00000000000000", max_length=32)
322 323
    adresse1 = models.CharField(default=_("Threadneedle Street"), max_length=128)
    adresse2 = models.CharField(default=_("London EC2R 8AH"), max_length=128)
324 325
    contact = models.EmailField(default="contact@example.org")
    telephone = models.CharField(max_length=15, default="0000000000")
326
    pseudo = models.CharField(default=_("Organisation"), max_length=32)
327 328 329 330 331 332
    utilisateur_asso = models.OneToOneField(
        'users.User',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
333 334 335 336
    description = models.TextField(
        null=True,
        blank=True,
    )
337

338 339
    class Meta:
        permissions = (
340
            ("view_assooption", _("Can view the organisation options")),
341
        )
342
        verbose_name = _("organisation options")
343

344

345
@receiver(post_save, sender=AssoOption)
346
def assooption_post_save(**kwargs):
347
    """Ecriture dans le cache"""
348 349 350 351
    asso_pref = kwargs['instance']
    asso_pref.set_in_cache()


Gabriel Detraz's avatar
Gabriel Detraz committed
352 353
class HomeOption(AclMixin, PreferencesModel):
    """Settings of the home page (facebook/twitter etc)"""
Gabriel Detraz's avatar
Gabriel Detraz committed
354 355 356

    facebook_url = models.URLField(
        null=True,
357
        blank=True
Gabriel Detraz's avatar
Gabriel Detraz committed
358 359 360
    )
    twitter_url = models.URLField(
        null=True,
361
        blank=True
Gabriel Detraz's avatar
Gabriel Detraz committed
362 363 364 365
    )
    twitter_account_name = models.CharField(
        max_length=32,
        null=True,
366
        blank=True
Gabriel Detraz's avatar
Gabriel Detraz committed
367 368 369 370
    )

    class Meta:
        permissions = (
371
            ("view_homeoption", _("Can view the homepage options")),
Gabriel Detraz's avatar
Gabriel Detraz committed
372
        )
373
        verbose_name = _("homepage options")
Gabriel Detraz's avatar
Gabriel Detraz committed
374 375


Gabriel Detraz's avatar
Gabriel Detraz committed
376 377
@receiver(post_save, sender=HomeOption)
def homeoption_post_save(**kwargs):
Gabriel Detraz's avatar
Gabriel Detraz committed
378
    """Ecriture dans le cache"""
Gabriel Detraz's avatar
Gabriel Detraz committed
379 380
    home_pref = kwargs['instance']
    home_pref.set_in_cache()
Gabriel Detraz's avatar
Gabriel Detraz committed
381 382


chirac's avatar
chirac committed
383
class MailMessageOption(AclMixin, models.Model):
384
    """Reglages, mail de bienvenue et autre"""
385 386 387

    welcome_mail_fr = models.TextField(default="")
    welcome_mail_en = models.TextField(default="")
388

389 390
    class Meta:
        permissions = (
391 392
            ("view_mailmessageoption", _("Can view the email message"
                                         " options")),
393
        )
394 395
        verbose_name = _("email message options")