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 !

forms.py 22.8 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 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.
#
# 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
"""
Definition des forms pour l'application users.
25

chirac's avatar
chirac committed
26 27 28 29 30 31 32
Modification, creation de :
    - un user (informations personnelles)
    - un bannissement
    - le mot de passe d'un user
    - une whiteliste
    - un user de service
"""
33

34
from __future__ import unicode_literals
35 36

from django import forms
37
from django.forms import ModelForm, Form
38
from django.contrib.auth.forms import ReadOnlyPasswordHashField
Gabriel Detraz's avatar
Gabriel Detraz committed
39
from django.core.validators import MinLengthValidator
40
from django.utils import timezone
41
from django.contrib.auth.models import Group, Permission
42
from django.utils.translation import ugettext_lazy as _
43

chirac's avatar
chirac committed
44
from preferences.models import OptionalUser
45
from re2o.utils import remove_user_room, get_input_formats_help_text
46 47 48
from re2o.mixins import FormRevMixin
from re2o.field_permissions import FieldPermissionFormMixin

root's avatar
root committed
49 50
from .widgets import DateTimePicker

51 52 53 54 55 56
from .models import (
    User,
    ServiceUser,
    School,
    ListRight,
    Whitelist,
57
    EMailAddress,
58 59 60 61 62
    ListShell,
    Ban,
    Adherent,
    Club
)
63

64

65
class PassForm(FormRevMixin, FieldPermissionFormMixin, forms.ModelForm):
chirac's avatar
chirac committed
66 67 68
    """Formulaire de changement de mot de passe. Verifie que les 2
    nouveaux mots de passe renseignés sont identiques et respectent
    une norme"""
69
    selfpasswd = forms.CharField(
70
        label=_("Current password"),
71 72 73
        max_length=255,
        widget=forms.PasswordInput
    )
chirac's avatar
chirac committed
74
    passwd1 = forms.CharField(
75
        label=_("New password"),
chirac's avatar
chirac committed
76 77 78 79 80
        max_length=255,
        validators=[MinLengthValidator(8)],
        widget=forms.PasswordInput
    )
    passwd2 = forms.CharField(
81
        label=_("New password confirmation"),
chirac's avatar
chirac committed
82 83 84 85
        max_length=255,
        validators=[MinLengthValidator(8)],
        widget=forms.PasswordInput
    )
86

87 88 89 90
    class Meta:
        model = User
        fields = []

91
    def clean_passwd2(self):
chirac's avatar
chirac committed
92
        """Verifie que passwd1 et 2 sont identiques"""
93 94 95 96
        # Check that the two password entries match
        password1 = self.cleaned_data.get("passwd1")
        password2 = self.cleaned_data.get("passwd2")
        if password1 and password2 and password1 != password2:
97
            raise forms.ValidationError(
98
                _("The new passwords don't match.")
99
            )
100
        return password2
101

102 103
    def clean_selfpasswd(self):
        """Verifie si il y a lieu que le mdp self est correct"""
104
        if not self.instance.check_password(
105 106
                self.cleaned_data.get("selfpasswd")
            ):
107
            raise forms.ValidationError(_("The current password is incorrect."))
108 109 110 111 112 113 114 115
        return

    def save(self, commit=True):
        """Changement du mot de passe"""
        user = super(PassForm, self).save(commit=False)
        user.set_password(self.cleaned_data.get("passwd1"))
        user.save()

chirac's avatar
chirac committed
116

117
class UserCreationForm(FormRevMixin, forms.ModelForm):
118
    """A form for creating new users. Includes all the required
chirac's avatar
chirac committed
119 120 121 122 123 124
    fields, plus a repeated password.

    Formulaire pour la création d'un user. N'est utilisé que pour
    l'admin, lors de la creation d'un user par admin. Inclu tous les
    champs obligatoires"""
    password1 = forms.CharField(
125
        label=_("Password"),
chirac's avatar
chirac committed
126 127 128 129 130
        widget=forms.PasswordInput,
        validators=[MinLengthValidator(8)],
        max_length=255
    )
    password2 = forms.CharField(
131
        label=_("Password confirmation"),
chirac's avatar
chirac committed
132 133 134 135
        widget=forms.PasswordInput,
        validators=[MinLengthValidator(8)],
        max_length=255
    )
136
    is_admin = forms.BooleanField(label=_("Is admin"))
137

138
    def __init__(self, *args, **kwargs):
139
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
140 141
        super(UserCreationForm, self).__init__(*args, prefix=prefix, **kwargs)

142 143 144 145
    def clean_email(self):
        if not OptionalUser.objects.first().local_email_domain in self.cleaned_data.get('email'):
            return self.cleaned_data.get('email').lower()
        else:
146 147
            raise forms.ValidationError(_("You can't use an internal address"
                                          " as your external address."))
148

149
    class Meta:
150
        model = Adherent
151
        fields = ('pseudo', 'surname', 'email')
152 153

    def clean_password2(self):
chirac's avatar
chirac committed
154
        """Verifie que password1 et 2 sont identiques"""
155 156 157 158
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
159
            raise forms.ValidationError(_("The passwords don't match."))
160 161 162 163 164 165 166 167 168 169
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        user.save()
        user.is_admin = self.cleaned_data.get("is_admin")
        return user

chirac's avatar
chirac committed
170

171
class ServiceUserCreationForm(FormRevMixin, forms.ModelForm):
chirac's avatar
chirac committed
172
    """A form for creating new users. Includes all the required
chirac's avatar
chirac committed
173 174 175 176 177
    fields, plus a repeated password.

    Formulaire pour la creation de nouveaux serviceusers.
    Requiert seulement un mot de passe; et un pseudo"""
    password1 = forms.CharField(
178
        label=_("Password"),
chirac's avatar
chirac committed
179 180 181 182 183
        widget=forms.PasswordInput,
        min_length=8,
        max_length=255
    )
    password2 = forms.CharField(
184
        label=_("Password confirmation"),
chirac's avatar
chirac committed
185 186 187 188
        widget=forms.PasswordInput,
        min_length=8,
        max_length=255
    )
chirac's avatar
chirac committed
189

190
    def __init__(self, *args, **kwargs):
191
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
chirac's avatar
chirac committed
192 193 194 195 196
        super(ServiceUserCreationForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )
197

chirac's avatar
chirac committed
198 199 200 201 202
    class Meta:
        model = ServiceUser
        fields = ('pseudo',)

    def clean_password2(self):
chirac's avatar
chirac committed
203
        """Verifie que password1 et 2 sont indentiques"""
chirac's avatar
chirac committed
204 205 206 207
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
208
            raise forms.ValidationError(_("The passwords don't match."))
chirac's avatar
chirac committed
209 210 211 212 213 214 215 216
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(ServiceUserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        user.save()
        return user
217

chirac's avatar
chirac committed
218

219
class UserChangeForm(FormRevMixin, forms.ModelForm):
220 221 222
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
chirac's avatar
chirac committed
223 224

    Formulaire pour la modification d'un user coté admin
225 226
    """
    password = ReadOnlyPasswordHashField()
227
    is_admin = forms.BooleanField(label=_("Is admin"), required=False)
228 229

    class Meta:
230
        model = Adherent
231
        fields = ('pseudo', 'password', 'surname', 'email')
232 233

    def __init__(self, *args, **kwargs):
234
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
235
        super(UserChangeForm, self).__init__(*args, prefix=prefix, **kwargs)
236
        print(_("User is admin: %s") % kwargs['instance'].is_admin)
237 238 239
        self.initial['is_admin'] = kwargs['instance'].is_admin

    def clean_password(self):
chirac's avatar
chirac committed
240
        """Dummy fun"""
241 242 243 244 245 246 247 248 249 250 251 252
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserChangeForm, self).save(commit=False)
        user.is_admin = self.cleaned_data.get("is_admin")
        if commit:
            user.save()
        return user
chirac's avatar
chirac committed
253

chirac's avatar
chirac committed
254

255
class ServiceUserChangeForm(FormRevMixin, forms.ModelForm):
chirac's avatar
chirac committed
256 257 258
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
chirac's avatar
chirac committed
259 260

    Formulaire pour l'edition des service users coté admin
chirac's avatar
chirac committed
261 262 263
    """
    password = ReadOnlyPasswordHashField()

264
    def __init__(self, *args, **kwargs):
265
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
chirac's avatar
chirac committed
266 267 268 269 270
        super(ServiceUserChangeForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )
271

chirac's avatar
chirac committed
272 273 274 275 276
    class Meta:
        model = ServiceUser
        fields = ('pseudo',)

    def clean_password(self):
chirac's avatar
chirac committed
277
        """Dummy fun"""
chirac's avatar
chirac committed
278 279
        return self.initial["password"]

chirac's avatar
chirac committed
280

chirac's avatar
chirac committed
281
class ResetPasswordForm(forms.Form):
chirac's avatar
chirac committed
282 283
    """Formulaire de demande de reinitialisation de mot de passe,
    mdp oublié"""
284
    pseudo = forms.CharField(label=_("Username"), max_length=255)
chirac's avatar
chirac committed
285
    email = forms.EmailField(max_length=255)
286

chirac's avatar
chirac committed
287

288
class MassArchiveForm(forms.Form):
chirac's avatar
chirac committed
289 290 291
    """Formulaire d'archivage des users inactif. Prend en argument
    du formulaire la date de depart avant laquelle archiver les
    users"""
292 293 294
    date = forms.DateTimeField(help_text='%d/%m/%y')

    def clean(self):
chirac's avatar
chirac committed
295
        cleaned_data = super(MassArchiveForm, self).clean()
296 297
        date = cleaned_data.get("date")
        if date:
298
            if date > timezone.now():
299 300 301
                raise forms.ValidationError(_("Impossible to archive users"
                                              " whose end access date is in"
                                              " the future."))
chirac's avatar
chirac committed
302

303

304
class AdherentForm(FormRevMixin, FieldPermissionFormMixin, ModelForm):
chirac's avatar
chirac committed
305 306 307
    """Formulaire de base d'edition d'un user. Formulaire de base, utilisé
    pour l'edition de self par self ou un cableur. On formate les champs
    avec des label plus jolis"""
308
    def __init__(self, *args, **kwargs):
309
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
310
        super(AdherentForm, self).__init__(*args, prefix=prefix, **kwargs)
311 312 313 314 315 316 317 318
        self.fields['name'].label = _("First name")
        self.fields['surname'].label = _("Surname")
        self.fields['email'].label = _("Email address")
        self.fields['school'].label = _("School")
        self.fields['comment'].label = _("Comment")
        self.fields['room'].label = _("Room")
        self.fields['room'].empty_label = _("No room")
        self.fields['school'].empty_label = _("Select a school")
Fernet Laouen's avatar
Fernet Laouen committed
319
        self.fields['gpg_fingerprint'].widget.attrs['placeholder'] = _("Leave empty if you don't have any GPG key.")
320 321
        if 'shell' in self.fields:
            self.fields['shell'].empty_label = _("Default shell")
322

323 324 325 326
    def clean_email(self):
        if not OptionalUser.objects.first().local_email_domain in self.cleaned_data.get('email'):
            return self.cleaned_data.get('email').lower()
        else:
327 328 329
            raise forms.ValidationError(
                    _("You can't use a {} address.").format(
                        OptionalUser.objects.first().local_email_domain))
330

331
    class Meta:
332
        model = Adherent
333 334 335 336
        fields = [
            'name',
            'surname',
            'pseudo',
337
            'email',
338 339
            'school',
            'comment',
340
            'telephone',
341
            'room',
342
            'shell',
343
            'gpg_fingerprint'
344 345
        ]

346

347
    def clean_telephone(self):
chirac's avatar
chirac committed
348 349
        """Verifie que le tel est présent si 'option est validée
        dans preferences"""
350
        telephone = self.cleaned_data['telephone']
351
        if not telephone and OptionalUser.get_cached_value('is_tel_mandatory'):
chirac's avatar
chirac committed
352
            raise forms.ValidationError(
353
                _("A valid telephone number is required.")
chirac's avatar
chirac committed
354
            )
355 356
        return telephone

357 358 359 360 361 362
    def clean_gpg_fingerprint(self):
        """Format the GPG fingerprint"""
        gpg_fingerprint = self.cleaned_data.get('gpg_fingerprint', None)
        if gpg_fingerprint:
            return gpg_fingerprint.replace(' ', '').upper()

363
    force = forms.BooleanField(
364
        label=_("Force the move?"),
365 366 367 368 369 370 371 372
        initial=False,
        required=False
    )

    def clean_force(self):
        """On supprime l'ancien user de la chambre si et seulement si la
        case est cochée"""
        if self.cleaned_data.get('force', False):
373
            remove_user_room(self.cleaned_data.get('room'))
374
        return
chirac's avatar
chirac committed
375

376

377
class ClubForm(FormRevMixin, FieldPermissionFormMixin, ModelForm):
378 379 380 381 382
    """Formulaire de base d'edition d'un user. Formulaire de base, utilisé
    pour l'edition de self par self ou un cableur. On formate les champs
    avec des label plus jolis"""
    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
383
        super(ClubForm, self).__init__(*args, prefix=prefix, **kwargs)
384 385 386 387 388 389 390
        self.fields['surname'].label = _("Name")
        self.fields['school'].label = _("School")
        self.fields['comment'].label = _("Comment")
        self.fields['room'].label = _("Room")
        self.fields['room'].empty_label = _("No room")
        self.fields['school'].empty_label = _("Select a school")
        self.fields['mailing'].label = _("Use a mailing list")
391 392 393 394 395 396 397 398 399 400

    class Meta:
        model = Club
        fields = [
            'surname',
            'pseudo',
            'school',
            'comment',
            'room',
            'telephone',
401
            'shell',
402
            'mailing'
403 404 405 406 407 408
        ]

    def clean_telephone(self):
        """Verifie que le tel est présent si 'option est validée
        dans preferences"""
        telephone = self.cleaned_data['telephone']
409
        if not telephone and OptionalUser.get_cached_value('is_tel_mandatory'):
410
            raise forms.ValidationError(
411
                _("A valid telephone number is required.")
412 413 414 415
            )
        return telephone


416
class ClubAdminandMembersForm(FormRevMixin, ModelForm):
417 418 419 420 421 422 423 424
    """Permet d'éditer la liste des membres et des administrateurs
    d'un club"""
    class Meta:
        model = Club
        fields = ['administrators', 'members']

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
425 426 427 428 429
        super(ClubAdminandMembersForm, self).__init__(
            *args,
            prefix=prefix,
            **kwargs
        )
430 431


432
class PasswordForm(FormRevMixin, ModelForm):
chirac's avatar
chirac committed
433 434
    """ Formulaire de changement brut de mot de passe.
    Ne pas utiliser sans traitement"""
435 436 437 438
    class Meta:
        model = User
        fields = ['password', 'pwd_ntlm']

439
    def __init__(self, *args, **kwargs):
440
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
441 442
        super(PasswordForm, self).__init__(*args, prefix=prefix, **kwargs)

chirac's avatar
chirac committed
443

444
class ServiceUserForm(FormRevMixin, ModelForm):
chirac's avatar
chirac committed
445
    """ Modification d'un service user"""
chirac's avatar
chirac committed
446
    password = forms.CharField(
447
        label=_("New password"),
chirac's avatar
chirac committed
448 449 450 451 452
        max_length=255,
        validators=[MinLengthValidator(8)],
        widget=forms.PasswordInput,
        required=False
    )
453 454 455

    class Meta:
        model = ServiceUser
456
        fields = ('pseudo', 'access_group','comment')
457

458
    def __init__(self, *args, **kwargs):
459
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
460 461
        super(ServiceUserForm, self).__init__(*args, prefix=prefix, **kwargs)

462 463 464 465 466 467 468
    def save(self, commit=True):
        """Changement du mot de passe"""
        user = super(ServiceUserForm, self).save(commit=False)
        if self.cleaned_data['password']:
            user.set_password(self.cleaned_data.get("password"))
        user.save()

chirac's avatar
chirac committed
469

470
class EditServiceUserForm(ServiceUserForm):
chirac's avatar
chirac committed
471 472
    """Formulaire d'edition de base d'un service user. Ne permet
    d'editer que son group d'acl et son commentaire"""
473
    class Meta(ServiceUserForm.Meta):
chirac's avatar
chirac committed
474 475
        fields = ['access_group', 'comment']

476

477
class StateForm(FormRevMixin, ModelForm):
chirac's avatar
chirac committed
478
    """ Changement de l'état d'un user"""
479 480 481 482
    class Meta:
        model = User
        fields = ['state']

483
    def __init__(self, *args, **kwargs):
484
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
485 486
        super(StateForm, self).__init__(*args, prefix=prefix, **kwargs)

487

Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
488
class GroupForm(FieldPermissionFormMixin, FormRevMixin, ModelForm):
489 490 491 492 493 494 495 496 497
    """ Gestion des groupes d'un user"""
    groups = forms.ModelMultipleChoiceField(
        Group.objects.all(),
        widget=forms.CheckboxSelectMultiple,
        required=False
    )

    class Meta:
        model = User
498
        fields = ['is_superuser', 'groups']
499 500 501 502

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
        super(GroupForm, self).__init__(*args, prefix=prefix, **kwargs)
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
503
        if 'is_superuser' in self.fields:
504
            self.fields['is_superuser'].label = _("Superuser")
505 506


507
class SchoolForm(FormRevMixin, ModelForm):
chirac's avatar
chirac committed
508
    """Edition, creation d'un école"""
509 510 511 512 513
    class Meta:
        model = School
        fields = ['name']

    def __init__(self, *args, **kwargs):
514
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
515
        super(SchoolForm, self).__init__(*args, prefix=prefix, **kwargs)
516
        self.fields['name'].label = _("School")
517

chirac's avatar
chirac committed
518

519
class ShellForm(FormRevMixin, ModelForm):
520 521 522 523 524 525 526 527
    """Edition, creation d'un école"""
    class Meta:
        model = ListShell
        fields = ['shell']

    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
        super(ShellForm, self).__init__(*args, prefix=prefix, **kwargs)
528
        self.fields['shell'].label = _("Shell name")
529 530


531
class ListRightForm(FormRevMixin, ModelForm):
chirac's avatar
chirac committed
532
    """Edition, d'un groupe , équivalent à un droit
533
    Ne permet pas d'editer le gid, car il sert de primary key"""
534
    permissions = forms.ModelMultipleChoiceField(
535
        Permission.objects.all().select_related('content_type'),
536 537 538 539
        widget=forms.CheckboxSelectMultiple,
        required=False
    )

540 541
    class Meta:
        model = ListRight
542
        fields = ('name', 'unix_name', 'critical', 'permissions', 'details')
543 544

    def __init__(self, *args, **kwargs):
545
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
546
        super(ListRightForm, self).__init__(*args, prefix=prefix, **kwargs)
547
        self.fields['unix_name'].label = _("Name of the group of rights")
548

chirac's avatar
chirac committed
549

550
class NewListRightForm(ListRightForm):
chirac's avatar
chirac committed
551
    """Ajout d'un groupe/list de droit """
552
    class Meta(ListRightForm.Meta):
553 554
        fields = ('name', 'unix_name', 'gid', 'critical', 'permissions',
                  'details')
555 556 557

    def __init__(self, *args, **kwargs):
        super(NewListRightForm, self).__init__(*args, **kwargs)
558 559
        self.fields['gid'].label = _("GID. Warning: this field must not be"
                                     " edited after creation.")
chirac's avatar
chirac committed
560

561

562
class DelListRightForm(Form):
chirac's avatar
chirac committed
563 564
    """Suppression d'un ou plusieurs groupes"""
    listrights = forms.ModelMultipleChoiceField(
565
        queryset=ListRight.objects.none(),
566
        label=_("Current groups of rights"),
chirac's avatar
chirac committed
567 568 569
        widget=forms.CheckboxSelectMultiple
    )

570 571 572 573
    def __init__(self, *args, **kwargs):
        instances = kwargs.pop('instances', None)
        super(DelListRightForm, self).__init__(*args, **kwargs)
        if instances:
574
            self.fields['listrights'].queryset = instances
575
        else:
576
            self.fields['listrights'].queryset = ListRight.objects.all()
577

578

579
class DelSchoolForm(Form):
chirac's avatar
chirac committed
580 581
    """Suppression d'une ou plusieurs écoles"""
    schools = forms.ModelMultipleChoiceField(
582
        queryset=School.objects.none(),
583
        label=_("Current schools"),
chirac's avatar
chirac committed
584 585 586
        widget=forms.CheckboxSelectMultiple
    )

587
    def __init__(self, *args, **kwargs):
588
        instances = kwargs.pop('instances', None)
589
        super(DelSchoolForm, self).__init__(*args, **kwargs)
590 591 592 593
        if instances:
            self.fields['schools'].queryset = instances
        else:
            self.fields['schools'].queryset = School.objects.all()
594

595

596
class BanForm(FormRevMixin, ModelForm):
chirac's avatar
chirac committed
597
    """Creation, edition d'un objet bannissement"""
598
    def __init__(self, *args, **kwargs):
599
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
600
        super(BanForm, self).__init__(*args, prefix=prefix, **kwargs)
601
        self.fields['date_end'].label = _("End date")
602
        self.fields['date_end'].localize = False
603 604 605 606

    class Meta:
        model = Ban
        exclude = ['user']
607
        widgets = {'date_end':DateTimePicker}
608 609


610
class WhitelistForm(FormRevMixin, ModelForm):
chirac's avatar
chirac committed
611
    """Creation, edition d'un objet whitelist"""
612
    def __init__(self, *args, **kwargs):
613
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
614
        super(WhitelistForm, self).__init__(*args, prefix=prefix, **kwargs)
615
        self.fields['date_end'].label = _("End date")
root's avatar
root committed
616
        self.fields['date_end'].localize = False
617 618 619 620

    class Meta:
        model = Whitelist
        exclude = ['user']
root's avatar
root committed
621
        widgets = {'date_end':DateTimePicker}
622 623


624 625
class EMailAddressForm(FormRevMixin, ModelForm):
    """Create and edit a local email address"""
626 627
    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
628
        super(EMailAddressForm, self).__init__(*args, prefix=prefix, **kwargs)
629 630
        self.fields['local_part'].label = _("Local part of the email address")
        self.fields['local_part'].help_text = _("Can't contain @")
631

632 633
    def clean_local_part(self):
        return self.cleaned_data.get('local_part').lower()
634 635

    class Meta:
636
        model = EMailAddress
637
        exclude = ['user']
638

639 640 641

class EmailSettingsForm(FormRevMixin, FieldPermissionFormMixin, ModelForm):
    """Edit email-related settings"""
642 643
    def __init__(self, *args, **kwargs):
        prefix = kwargs.pop('prefix', self.Meta.model.__name__)
644
        super(EmailSettingsForm, self).__init__(*args, prefix=prefix, **kwargs)
645
        self.fields['email'].label = _("Main email address")
646
        if 'local_email_redirect' in self.fields:
647
            self.fields['local_email_redirect'].label = _("Redirect local emails")
648
        if 'local_email_enabled' in self.fields:
649
            self.fields['local_email_enabled'].label = _("Use local emails")
650

651 652 653 654
    def clean_email(self):
        if not OptionalUser.objects.first().local_email_domain in self.cleaned_data.get('email'):
            return self.cleaned_data.get('email').lower()
        else:
655 656 657
            raise forms.ValidationError(
                    _("You can't use a {} address.").format(
                        OptionalUser.objects.first().local_email_domain))
658

659
    class Meta:
660
        model = User
661
        fields = ['email','local_email_enabled', 'local_email_redirect']
662