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 !

views.py 31.8 KB
Newer Older
1 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.

23
# App de gestion des users pour re2o
Dalahro's avatar
Dalahro committed
24
# Goulven Kermarec, Gabriel Détraz, Lemesle Augustin
25
# Gplv2
26 27 28 29 30 31 32 33 34
"""
Module des views.

On définit les vues pour l'ajout, l'edition des users : infos personnelles,
mot de passe, etc

Permet aussi l'ajout, edition et suppression des droits, des bannissements,
des whitelist, des services users et des écoles
"""
35 36 37

from __future__ import unicode_literals

38
from django.urls import reverse
39
from django.shortcuts import get_object_or_404, render, redirect
40
from django.contrib import messages
41
from django.contrib.auth.decorators import login_required, permission_required
42
from django.db.models import ProtectedError
43
from django.utils import timezone
44
from django.db import transaction
45
from django.http import HttpResponse
46
from django.http import HttpResponseRedirect
47 48 49
from django.views.decorators.csrf import csrf_exempt

from rest_framework.renderers import JSONRenderer
50
from reversion import revisions as reversion
51

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
from cotisations.models import Facture
from machines.models import Machine
from preferences.models import OptionalUser, GeneralOption, AssoOption
from re2o.views import form
from re2o.utils import (
    all_has_access,
    SortTable,
    re2o_paginator
)
from re2o.acl import (
    can_create,
    can_edit,
    can_delete_set,
    can_delete,
    can_view,
    can_view_all,
    can_change
)
lhark's avatar
lhark committed
70

71 72
from .serializers import MailingSerializer, MailingMemberSerializer
from .models import (
73 74 75 76 77 78 79 80
    User,
    Ban,
    Whitelist,
    School,
    ListRight,
    Request,
    ServiceUser,
    Adherent,
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
81
    Club,
82
    ListShell,
83
)
84
from .forms import (
85 86 87 88 89 90 91
    BanForm,
    WhitelistForm,
    DelSchoolForm,
    DelListRightForm,
    NewListRightForm,
    StateForm,
    SchoolForm,
92
    ShellForm,
93 94 95 96 97 98 99 100
    EditServiceUserForm,
    ServiceUserForm,
    ListRightForm,
    AdherentForm,
    ClubForm,
    MassArchiveForm,
    PassForm,
    ResetPasswordForm,
101 102
    ClubAdminandMembersForm,
    GroupForm
103
)
104

105

106
@can_create(Adherent)
107
def new_user(request):
108 109
    """ Vue de création d'un nouvel utilisateur,
    envoie un mail pour le mot de passe"""
110
    user = AdherentForm(request.POST or None, user=request.user)
111 112
    GTU_sum_up = GeneralOption.get_cached_value('GTU_sum_up')
    GTU = GeneralOption.get_cached_value('GTU')
113
    if user.is_valid():
114
        user = user.save(commit=False)
115
        user.save()
116
        user.reset_passwd_mail(request)
117 118
        messages.success(request, "L'utilisateur %s a été crée, un mail\
        pour l'initialisation du mot de passe a été envoyé" % user.pseudo)
119 120
        return redirect(reverse(
            'users:profil',
121 122 123 124 125 126 127 128 129 130 131 132 133
            kwargs={'userid': str(user.id)}
        ))
    return form(
        {
            'userform': user,
            'GTU_sum_up': GTU_sum_up,
            'GTU': GTU,
            'showCGU': True,
            'action_name': 'Créer un utilisateur'
        },
        'users/user.html',
        request
    )
134

135

136
@login_required
137
@can_create(Club)
138 139 140
def new_club(request):
    """ Vue de création d'un nouveau club,
    envoie un mail pour le mot de passe"""
141
    club = ClubForm(request.POST or None, user=request.user)
142 143
    if club.is_valid():
        club = club.save(commit=False)
144
        club.save()
145 146 147
        club.reset_passwd_mail(request)
        messages.success(request, "L'utilisateur %s a été crée, un mail\
        pour l'initialisation du mot de passe a été envoyé" % club.pseudo)
148 149
        return redirect(reverse(
            'users:profil',
150 151 152 153 154 155 156
            kwargs={'userid': str(club.id)}
        ))
    return form(
        {'userform': club, 'showCGU': False, 'action_name': 'Créer un club'},
        'users/user.html',
        request
    )
157 158


159
@login_required
160
@can_edit(Club)
161
def edit_club_admin_members(request, club_instance, **_kwargs):
162 163
    """Vue d'edition de la liste des users administrateurs et
    membres d'un club"""
164 165 166 167
    club = ClubAdminandMembersForm(
        request.POST or None,
        instance=club_instance
    )
168
    if club.is_valid():
169 170 171
        if club.changed_data:
            club.save()
            messages.success(request, "Le club a bien été modifié")
172 173
        return redirect(reverse(
            'users:profil',
174 175 176 177 178 179 180 181 182 183 184
            kwargs={'userid': str(club_instance.id)}
        ))
    return form(
        {
            'userform': club,
            'showCGU': False,
            'action_name': 'Editer les admin et membres'
        },
        'users/user.html',
        request
    )
185 186


chirac's avatar
chirac committed
187
@login_required
188
@can_edit(User)
189
def edit_info(request, user, userid):
190 191 192
    """ Edite un utilisateur à partir de son id,
    si l'id est différent de request.user, vérifie la
    possession du droit cableur """
193
    if user.is_class_adherent:
194
        user_form = AdherentForm(
195 196 197 198
            request.POST or None,
            instance=user.adherent,
            user=request.user
        )
199 200
    else:
        user_form = ClubForm(
201 202 203 204
            request.POST or None,
            instance=user.club,
            user=request.user
        )
205 206 207
    if user_form.is_valid():
        if user_form.changed_data:
            user_form.save()
208
            messages.success(request, "L'user a bien été modifié")
209 210
        return redirect(reverse(
            'users:profil',
211 212 213
            kwargs={'userid': str(userid)}
        ))
    return form(
214
        {'userform': user_form, 'action_name': "Editer l'utilisateur"},
215 216 217
        'users/user.html',
        request
    )
218

219

chirac's avatar
chirac committed
220
@login_required
221
@can_edit(User, 'state')
222
def state(request, user, userid):
223 224
    """ Changer l'etat actif/desactivé/archivé d'un user,
    need droit bureau """
225 226 227 228
    state_form = StateForm(request.POST or None, instance=user)
    if state_form.is_valid():
        if state_form.changed_data:
            if state_form.cleaned_data['state'] == User.STATE_ARCHIVE:
229
                user.archive()
230
            elif state_form.cleaned_data['state'] == User.STATE_ACTIVE:
231
                user.unarchive()
232
            state_form.save()
233
            messages.success(request, "Etat changé avec succès")
234 235
        return redirect(reverse(
            'users:profil',
236 237 238
            kwargs={'userid': str(userid)}
        ))
    return form(
239
        {'userform': state_form, 'action_name': "Editer l'état"},
240 241 242
        'users/user.html',
        request
    )
243

244

245
@login_required
246
@can_edit(User, 'groups')
247
def groups(request, user, userid):
248
    """ View to edit the groups of a user """
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
249
    group_form = GroupForm(request.POST or None, instance=user, user=request.user)
250 251 252
    if group_form.is_valid():
        if group_form.changed_data:
            group_form.save()
253
            messages.success(request, "Groupes changés avec succès")
254 255
        return redirect(reverse(
            'users:profil',
256
            kwargs={'userid': str(userid)}
257
        ))
258
    return form(
259
        {'userform': group_form, 'action_name': 'Editer les groupes'},
260 261 262
        'users/user.html',
        request
    )
263 264


chirac's avatar
chirac committed
265
@login_required
266
@can_edit(User, 'password')
267
def password(request, user, userid):
268 269 270
    """ Reinitialisation d'un mot de passe à partir de l'userid,
    pour self par défaut, pour tous sans droit si droit cableur,
    pour tous si droit bureau """
271
    u_form = PassForm(request.POST or None, instance=user, user=request.user)
272
    if u_form.is_valid():
273 274 275
        if u_form.changed_data:
            u_form.save()
            messages.success(request, "Le mot de passe a changé")
276
        return redirect(reverse(
277
            'users:profil',
278
            kwargs={'userid': str(userid)}
279
        ))
280 281 282 283 284
    return form(
        {'userform': u_form, 'action_name': 'Changer le mot de passe'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
285

286

287
@login_required
288
@can_edit(User, 'groups')
289
def del_group(request, user, listrightid, **_kwargs):
290
    """ View used to delete a group """
291 292 293
    user.groups.remove(ListRight.objects.get(id=listrightid))
    user.save()
    messages.success(request, "Droit supprimé à %s" % user)
294
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
295 296


297
@login_required
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
298
@can_edit(User, 'is_superuser')
299 300 301 302 303 304 305 306
def del_superuser(request, user, **_kwargs):
    """Remove the superuser right of an user."""
    user.is_superuser = False
    user.save()
    messages.success(request, "%s n'est plus superuser" % user)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))


307
@login_required
308
@can_create(ServiceUser)
309 310 311 312
def new_serviceuser(request):
    """ Vue de création d'un nouvel utilisateur service"""
    user = ServiceUserForm(request.POST or None)
    if user.is_valid():
313
        user.save()
314 315
        messages.success(
            request,
316
            "L'utilisateur a été crée"
317
        )
318
        return redirect(reverse('users:index-serviceusers'))
319 320 321 322 323
    return form(
        {'userform': user, 'action_name': 'Créer un serviceuser'},
        'users/user.html',
        request
    )
324

325

326
@login_required
327
@can_edit(ServiceUser)
328
def edit_serviceuser(request, serviceuser, **_kwargs):
329
    """ Edit a ServiceUser """
330 331 332 333
    serviceuser = EditServiceUserForm(
        request.POST or None,
        instance=serviceuser
    )
334 335
    if serviceuser.is_valid():
        if serviceuser.changed_data:
336
            serviceuser.save()
337
        messages.success(request, "L'user a bien été modifié")
338
        return redirect(reverse('users:index-serviceusers'))
339 340 341 342 343
    return form(
        {'userform': serviceuser, 'action_name': 'Editer un serviceuser'},
        'users/user.html',
        request
    )
344

345

346
@login_required
347
@can_delete(ServiceUser)
348
def del_serviceuser(request, serviceuser, **_kwargs):
349
    """Suppression d'un ou plusieurs serviceusers"""
350
    if request.method == "POST":
351
        serviceuser.delete()
352
        messages.success(request, "L'user a été détruit")
353
        return redirect(reverse('users:index-serviceusers'))
354
    return form(
355
        {'objet': serviceuser, 'objet_name': 'serviceuser'},
356 357 358 359
        'users/delete.html',
        request
    )

360

chirac's avatar
chirac committed
361
@login_required
362 363 364
@can_create(Ban)
@can_edit(User)
def add_ban(request, user, userid):
365 366
    """ Ajouter un banissement, nécessite au moins le droit bofh
    (a fortiori bureau)
367
    Syntaxe : JJ/MM/AAAA , heure optionnelle, prend effet immédiatement"""
368 369 370
    ban_instance = Ban(user=user)
    ban = BanForm(request.POST or None, instance=ban_instance)
    if ban.is_valid():
371
        ban.save()
372
        messages.success(request, "Bannissement ajouté")
373 374
        return redirect(reverse(
            'users:profil',
375
            kwargs={'userid': str(userid)}
376
        ))
377
    if user.is_ban():
378 379 380 381
        messages.error(
            request,
            "Attention, cet utilisateur a deja un bannissement actif"
        )
382 383 384 385 386 387
    return form(
        {'userform': ban, 'action_name': 'Ajouter un ban'},
        'users/user.html',
        request
    )

388

chirac's avatar
chirac committed
389
@login_required
390
@can_edit(Ban)
391
def edit_ban(request, ban_instance, **_kwargs):
392 393
    """ Editer un bannissement, nécessite au moins le droit bofh
    (a fortiori bureau)
394
    Syntaxe : JJ/MM/AAAA , heure optionnelle, prend effet immédiatement"""
395 396
    ban = BanForm(request.POST or None, instance=ban_instance)
    if ban.is_valid():
397 398 399
        if ban.changed_data:
            ban.save()
            messages.success(request, "Bannissement modifié")
400
        return redirect(reverse('users:index'))
401 402 403 404 405
    return form(
        {'userform': ban, 'action_name': 'Editer un ban'},
        'users/user.html',
        request
    )
406

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
@login_required
@can_delete(Ban)
def del_ban(request, ban, **_kwargs):
        """ Supprime un banissement"""
        if request.method == "POST":
            ban.delete()
            messages.success(request, "Le banissement a été supprimé")
            return redirect(reverse(
                'users:profil',
                kwargs={'userid': str(ban.user.id)}
                ))
        return form(
            {'objet': ban, 'objet_name': 'ban'},
            'users/delete.html',
            request
        )


425

chirac's avatar
chirac committed
426
@login_required
427 428 429
@can_create(Whitelist)
@can_edit(User)
def add_whitelist(request, user, userid):
430 431 432 433
    """ Accorder un accès gracieux, temporaire ou permanent.
    Need droit cableur
    Syntaxe : JJ/MM/AAAA , heure optionnelle, prend effet immédiatement,
    raison obligatoire"""
chirac's avatar
chirac committed
434
    whitelist_instance = Whitelist(user=user)
435 436 437 438
    whitelist = WhitelistForm(
        request.POST or None,
        instance=whitelist_instance
    )
chirac's avatar
chirac committed
439
    if whitelist.is_valid():
440
        whitelist.save()
chirac's avatar
chirac committed
441
        messages.success(request, "Accès à titre gracieux accordé")
442 443
        return redirect(reverse(
            'users:profil',
444 445
            kwargs={'userid': str(userid)}
        ))
446
    if user.is_whitelisted():
447 448 449 450
        messages.error(
            request,
            "Attention, cet utilisateur a deja un accès gracieux actif"
        )
451 452 453 454 455
    return form(
        {'userform': whitelist, 'action_name': 'Ajouter une whitelist'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
456

457

chirac's avatar
chirac committed
458
@login_required
459
@can_edit(Whitelist)
460
def edit_whitelist(request, whitelist_instance, **_kwargs):
461 462 463 464 465 466 467 468
    """ Editer un accès gracieux, temporaire ou permanent.
    Need droit cableur
    Syntaxe : JJ/MM/AAAA , heure optionnelle, prend effet immédiatement,
    raison obligatoire"""
    whitelist = WhitelistForm(
        request.POST or None,
        instance=whitelist_instance
    )
chirac's avatar
chirac committed
469
    if whitelist.is_valid():
470 471 472
        if whitelist.changed_data:
            whitelist.save()
            messages.success(request, "Whitelist modifiée")
473
        return redirect(reverse('users:index'))
474 475 476 477 478
    return form(
        {'userform': whitelist, 'action_name': 'Editer une whitelist'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
479

480

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
@login_required
@can_delete(Whitelist)
def del_whitelist(request, whitelist, **_kwargs):
        """ Supprime un acces gracieux"""
        if request.method == "POST":
            whitelist.delete()
            messages.success(request, "L'accés gracieux a été supprimé")
            return redirect(reverse(
                'users:profil',
                kwargs={'userid': str(whitelist.user.id)}
                ))
        return form(
            {'objet': whitelist, 'objet_name': 'whitelist'},
            'users/delete.html',
            request
        )

chirac's avatar
chirac committed
498
@login_required
499
@can_create(School)
500
def add_school(request):
501 502
    """ Ajouter un établissement d'enseignement à la base de donnée,
    need cableur"""
503 504
    school = SchoolForm(request.POST or None)
    if school.is_valid():
505
        school.save()
506
        messages.success(request, "L'établissement a été ajouté")
507
        return redirect(reverse('users:index-school'))
508 509 510 511 512
    return form(
        {'userform': school, 'action_name': 'Ajouter'},
        'users/user.html',
        request
    )
513

514

chirac's avatar
chirac committed
515
@login_required
516
@can_edit(School)
517
def edit_school(request, school_instance, **_kwargs):
518 519
    """ Editer un établissement d'enseignement à partir du schoolid dans
    la base de donnée, need cableur"""
520 521
    school = SchoolForm(request.POST or None, instance=school_instance)
    if school.is_valid():
522 523 524
        if school.changed_data:
            school.save()
            messages.success(request, "Établissement modifié")
525
        return redirect(reverse('users:index-school'))
526 527 528 529 530
    return form(
        {'userform': school, 'action_name': 'Editer'},
        'users/user.html',
        request
    )
531

532

chirac's avatar
chirac committed
533
@login_required
534
@can_delete_set(School)
535
def del_school(request, instances):
536 537 538 539
    """ Supprimer un établissement d'enseignement à la base de donnée,
    need cableur
    Objet protégé, possible seulement si aucun user n'est affecté à
    l'établissement """
540
    school = DelSchoolForm(request.POST or None, instances=instances)
541 542 543 544
    if school.is_valid():
        school_dels = school.cleaned_data['schools']
        for school_del in school_dels:
            try:
545
                school_del.delete()
546 547
                messages.success(request, "L'établissement a été supprimé")
            except ProtectedError:
548 549 550
                messages.error(
                    request,
                    "L'établissement %s est affecté à au moins un user, \
lhark's avatar
lhark committed
551
                        vous ne pouvez pas le supprimer" % school_del)
552
        return redirect(reverse('users:index-school'))
553 554 555 556 557
    return form(
        {'userform': school, 'action_name': 'Supprimer'},
        'users/user.html',
        request
    )
558

559

560 561 562
@login_required
@can_create(ListShell)
def add_shell(request):
Gabriel Detraz's avatar
Gabriel Detraz committed
563
    """ Ajouter un shell à la base de donnée"""
564 565
    shell = ShellForm(request.POST or None)
    if shell.is_valid():
566
        shell.save()
567 568
        messages.success(request, "Le shell a été ajouté")
        return redirect(reverse('users:index-shell'))
569 570 571 572 573
    return form(
        {'userform': shell, 'action_name': 'Ajouter'},
        'users/user.html',
        request
    )
574 575 576 577


@login_required
@can_edit(ListShell)
578
def edit_shell(request, shell_instance, **_kwargs):
Gabriel Detraz's avatar
Gabriel Detraz committed
579
    """ Editer un shell à partir du listshellid"""
580 581
    shell = ShellForm(request.POST or None, instance=shell_instance)
    if shell.is_valid():
582 583 584
        if shell.changed_data:
            shell.save()
            messages.success(request, "Le shell a été modifié")
585
        return redirect(reverse('users:index-shell'))
586 587 588 589 590
    return form(
        {'userform': shell, 'action_name': 'Editer'},
        'users/user.html',
        request
    )
591 592 593 594


@login_required
@can_delete(ListShell)
595
def del_shell(request, shell, **_kwargs):
596 597
    """Destruction d'un shell"""
    if request.method == "POST":
598
        shell.delete()
599 600 601 602 603 604 605 606 607
        messages.success(request, "Le shell a été détruit")
        return redirect(reverse('users:index-shell'))
    return form(
        {'objet': shell, 'objet_name': 'shell'},
        'users/delete.html',
        request
    )


608
@login_required
609
@can_create(ListRight)
610
def add_listright(request):
611 612
    """ Ajouter un droit/groupe, nécessite droit bureau.
    Obligation de fournir un gid pour la synchro ldap, unique """
613 614
    listright = NewListRightForm(request.POST or None)
    if listright.is_valid():
615
        listright.save()
616
        messages.success(request, "Le droit/groupe a été ajouté")
617
        return redirect(reverse('users:index-listright'))
618 619 620 621 622
    return form(
        {'userform': listright, 'action_name': 'Ajouter'},
        'users/user.html',
        request
    )
623

624

625
@login_required
626
@can_edit(ListRight)
627
def edit_listright(request, listright_instance, **_kwargs):
628 629 630 631 632 633
    """ Editer un groupe/droit, necessite droit bureau,
    à partir du listright id """
    listright = ListRightForm(
        request.POST or None,
        instance=listright_instance
    )
634
    if listright.is_valid():
635 636 637
        if listright.changed_data:
            listright.save()
            messages.success(request, "Droit modifié")
638
        return redirect(reverse('users:index-listright'))
639 640 641 642 643
    return form(
        {'userform': listright, 'action_name': 'Editer'},
        'users/user.html',
        request
    )
644

645

646
@login_required
647
@can_delete_set(ListRight)
648
def del_listright(request, instances):
649 650
    """ Supprimer un ou plusieurs groupe, possible si il est vide, need droit
    bureau """
651
    listright = DelListRightForm(request.POST or None, instances=instances)
652 653 654 655
    if listright.is_valid():
        listright_dels = listright.cleaned_data['listrights']
        for listright_del in listright_dels:
            try:
656
                listright_del.delete()
657 658 659 660
                messages.success(request, "Le droit/groupe a été supprimé")
            except ProtectedError:
                messages.error(
                    request,
661
                    "Le groupe %s est affecté à au moins un user, \
662
                        vous ne pouvez pas le supprimer" % listright_del)
663
        return redirect(reverse('users:index-listright'))
664 665 666 667 668
    return form(
        {'userform': listright, 'action_name': 'Supprimer'},
        'users/user.html',
        request
    )
669

670

671
@login_required
672 673
@can_view_all(User)
@can_change(User, 'state')
674 675 676 677 678 679
def mass_archive(request):
    """ Permet l'archivage massif"""
    to_archive_date = MassArchiveForm(request.POST or None)
    to_archive_list = []
    if to_archive_date.is_valid():
        date = to_archive_date.cleaned_data['date']
680 681 682 683
        to_archive_list = [user for user in
                           User.objects.exclude(state=User.STATE_ARCHIVE)
                           if not user.end_access()
                           or user.end_access() < date]
684 685 686
        if "valider" in request.POST:
            for user in to_archive_list:
                with transaction.atomic(), reversion.create_revision():
687
                    user.archive()
688 689
                    user.save()
                    reversion.set_comment("Archivage")
690 691 692
            messages.success(request, "%s users ont été archivés" % len(
                to_archive_list
            ))
693
            return redirect(reverse('users:index'))
694 695 696 697 698 699
    return form(
        {'userform': to_archive_date, 'to_archive_list': to_archive_list},
        'users/mass_archive.html',
        request
    )

700

chirac's avatar
chirac committed
701
@login_required
702
@can_view_all(Adherent)
chirac's avatar
chirac committed
703
def index(request):
704
    """ Affiche l'ensemble des adherents, need droit cableur """
705
    pagination_number = GeneralOption.get_cached_value('pagination_number')
706
    users_list = Adherent.objects.select_related('room')
707 708 709 710 711 712
    users_list = SortTable.sort(
        users_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX
    )
713
    users_list = re2o_paginator(request, users_list, pagination_number)
714
    return render(request, 'users/index.html', {'users_list': users_list})
715

716

717
@login_required
718
@can_view_all(Club)
719 720
def index_clubs(request):
    """ Affiche l'ensemble des clubs, need droit cableur """
721
    pagination_number = GeneralOption.get_cached_value('pagination_number')
722
    clubs_list = Club.objects.select_related('room')
723 724 725 726 727 728
    clubs_list = SortTable.sort(
        clubs_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX
    )
729
    clubs_list = re2o_paginator(request, clubs_list, pagination_number)
730 731 732 733 734
    return render(
        request,
        'users/index_clubs.html',
        {'clubs_list': clubs_list}
    )
735 736


chirac's avatar
chirac committed
737
@login_required
738
@can_view_all(Ban)
739
def index_ban(request):
740
    """ Affiche l'ensemble des ban, need droit cableur """
741
    pagination_number = GeneralOption.get_cached_value('pagination_number')
742 743 744 745 746 747 748
    ban_list = Ban.objects.select_related('user')
    ban_list = SortTable.sort(
        ban_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_BAN
    )
749
    ban_list = re2o_paginator(request, ban_list, pagination_number)
750
    return render(request, 'users/index_ban.html', {'ban_list': ban_list})
751

752

chirac's avatar
chirac committed
753
@login_required
754
@can_view_all(Whitelist)
755
def index_white(request):
756
    """ Affiche l'ensemble des whitelist, need droit cableur """
757
    pagination_number = GeneralOption.get_cached_value('pagination_number')
758 759 760 761 762 763 764
    white_list = Whitelist.objects.select_related('user')
    white_list = SortTable.sort(
        white_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_BAN
    )
765
    white_list = re2o_paginator(request, white_list, pagination_number)
766 767 768 769 770 771
    return render(
        request,
        'users/index_whitelist.html',
        {'white_list': white_list}
    )

772

chirac's avatar
chirac committed
773
@login_required
774
@can_view_all(School)
775
def index_school(request):
776
    """ Affiche l'ensemble des établissement"""
777
    school_list = School.objects.order_by('name')
778 779 780 781 782 783 784
    pagination_number = GeneralOption.get_cached_value('pagination_number')
    school_list = SortTable.sort(
        school_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_SCHOOL
    )
785
    school_list = re2o_paginator(request, school_list, pagination_number)
786 787 788 789 790 791
    return render(
        request,
        'users/index_schools.html',
        {'school_list': school_list}
    )

792

793 794 795 796 797 798 799 800 801 802 803 804
@login_required
@can_view_all(ListShell)
def index_shell(request):
    """ Affiche l'ensemble des shells"""
    shell_list = ListShell.objects.order_by('shell')
    return render(
        request,
        'users/index_shell.html',
        {'shell_list': shell_list}
    )


805
@login_required
806
@can_view_all(ListRight)
807
def index_listright(request):
808
    """ Affiche l'ensemble des droits"""
809 810
    listright_list = ListRight.objects.order_by('unix_name')\
        .prefetch_related('permissions').prefetch_related('user_set')
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
811
    superuser_right = User.objects.filter(is_superuser=True)
812 813 814
    return render(
        request,
        'users/index_listright.html',
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
815 816 817 818
        {
            'listright_list': listright_list,
            'superuser_right' : superuser_right,
        }
819 820
    )

821

822
@login_required
823
@can_view_all(ServiceUser)
824 825 826
def index_serviceusers(request):
    """ Affiche les users de services (pour les accès ldap)"""
    serviceusers_list = ServiceUser.objects.order_by('pseudo')
827 828 829 830 831 832
    return render(
        request,
        'users/index_serviceusers.html',
        {'serviceusers_list': serviceusers_list}
    )

833

834 835
@login_required
def mon_profil(request):
836
    """ Lien vers profil, renvoie request.id à la fonction """
837 838
    return redirect(reverse(
        'users:profil',
839
        kwargs={'userid': str(request.user.id)}
840
        ))
841

842

chirac's avatar
chirac committed
843
@login_required
844
@can_view(User)
845
def profil(request, users, **_kwargs):
846
    """ Affiche un profil, self or cableur, prend un userid en argument """
847 848 849 850 851
    machines = Machine.objects.filter(user=users).select_related('user')\
        .prefetch_related('interface_set__domain__extension')\
        .prefetch_related('interface_set__ipv4__ip_type__extension')\
        .prefetch_related('interface_set__type')\
        .prefetch_related('interface_set__domain__related_domain__extension')
852 853 854 855 856 857
    machines = SortTable.sort(
        machines,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.MACHINES_INDEX
    )
858 859 860
    pagination_large_number = GeneralOption.get_cached_value(
        'pagination_large_number'
    )
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
861
    nb_machines = machines.count()
862
    machines = re2o_paginator(request, machines, pagination_large_number)
chirac's avatar
chirac committed
863
    factures = Facture.objects.filter(user=users)
864 865 866 867 868 869
    factures = SortTable.sort(
        factures,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.COTISATIONS_INDEX
    )
chirac's avatar
chirac committed
870
    bans = Ban.objects.filter(user=users)
871 872 873 874 875 876
    bans = SortTable.sort(
        bans,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_BAN
    )
chirac's avatar
chirac committed
877
    whitelists = Whitelist.objects.filter(user=users)
878 879 880 881 882 883
    whitelists = SortTable.sort(
        whitelists,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_WHITE
    )
884
    user_solde = OptionalUser.get_cached_value('user_solde')
885
    allow_online_payment = AssoOption.get_cached_value('payment') != 'NONE'
886 887 888 889
    return render(
        request,
        'users/profil.html',
        {
890
            'users': users,
891
            'machines_list': machines,
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
892
            'nb_machines' : nb_machines,
893 894 895
            'facture_list': factures,
            'ban_list': bans,
            'white_list': whitelists,
chibrac's avatar
chibrac committed
896
            'user_solde': user_solde,
897
            'allow_online_payment': allow_online_payment,
lhark's avatar
lhark committed
898 899
        }
    )
900

901

chirac's avatar
chirac committed
902
def reset_password(request):
903
    """ Reintialisation du mot de passe si mdp oublié """
chirac's avatar
chirac committed
904 905 906
    userform = ResetPasswordForm(request.POST or None)
    if userform.is_valid():
        try:
907 908 909 910
            user = User.objects.get(
                pseudo=userform.cleaned_data['pseudo'],
                email=userform.cleaned_data['email']
            )
chirac's avatar
chirac committed
911 912
        except User.DoesNotExist:
            messages.error(request, "Cet utilisateur n'existe pas")
913 914 915 916 917
            return form(
                {'userform': userform, 'action_name': 'Réinitialiser'},
                'users/user.html',
                request
            )
918
        user.reset_passwd_mail(request)
919 920
        messages.success(request, "Un mail pour l'initialisation du mot\
        de passe a été envoyé")
921
        redirect(reverse('index'))
922 923 924 925 926
    return form(
        {'userform': userform, 'action_name': 'Réinitialiser'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
927

928

929
def process(request, token):
930
    """Process, lien pour la reinitialisation du mot de passe"""
931 932 933 934 935 936
    valid_reqs = Request.objects.filter(expires_at__gt=timezone.now())
    req = get_object_or_404(valid_reqs, token=token)

    if req.type == Request.PASSWD:
        return process_passwd(request, req)
    else:
chirac's avatar
chirac committed
937
        messages.error(request, "Entrée incorrecte, contactez un admin")
938
        redirect(reverse('index'))
939

940

941
def process_passwd(request, req):
942 943
    """Process le changeemnt de mot de passe, renvoie le formulaire
    demandant le nouveau password"""
944
    user = req.user
945
    u_form = PassForm(request.POST or None, instance=user, user=request.user)
946
    if u_form.is_valid():
947 948 949 950 951
        with transaction.atomic(), reversion.create_revision():
            u_form.save()
            reversion.set_comment("Réinitialisation du mot de passe")
        req.delete()
        messages.success(request, "Le mot de passe a changé")
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
952
        return redirect(reverse('index'))
953 954 955 956 957
    return form(
        {'userform': u_form, 'action_name': 'Changer le mot de passe'},
        'users/user.html',
        request
    )
958

959 960

class JSONResponse(HttpResponse):
961
    """ Framework Rest """
962 963 964 965 966
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

967

968 969
@csrf_exempt
@login_required
970
@permission_required('machines.serveur')
971
def ml_std_list(_request):
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
    """ API view sending all the available standard mailings"""
    return JSONResponse([
        {'name': 'adherents'}
    ])


@csrf_exempt
@login_required
@permission_required('machines.serveur')
def ml_std_members(request, ml_name):
    """ API view sending all the members for a standard mailing"""
    # All with active connextion
    if ml_name == 'adherents':
        members = all_has_access().values('email').distinct()
    # Unknown mailing
    else:
        messages.error(request, "Cette mailing n'existe pas")
        return redirect(reverse('index'))
    seria = MailingMemberSerializer(members, many=True)
    return JSONResponse(seria.data)


@csrf_exempt
@login_required
@permission_required('machines.serveur')
997
def ml_club_list(_request):
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    """ API view sending all the available club mailings"""
    clubs = Club.objects.filter(mailing=True).values('pseudo')
    seria = MailingSerializer(clubs, many=True)
    return JSONResponse(seria.data)


@csrf_exempt
@login_required
@permission_required('machines.serveur')
def ml_club_admins(request, ml_name):
    """ API view sending all the administrators for a specific club mailing"""
    try:
        club = Club.objects.get(mailing=True, pseudo=ml_name)
    except Club.DoesNotExist:
        messages.error(request, "Cette mailing n'existe pas")
        return redirect(reverse('index'))
    members = club.administrators.all().values('email').distinct()
    seria = MailingMemberSerializer(members, many=True)
    return JSONResponse(seria.data)


@csrf_exempt
@login_required
@permission_required('machines.serveur')
def ml_club_members(request, ml_name):
    """ API view sending all the members for a specific club mailing"""
    try:
        club = Club.objects.get(mailing=True, pseudo=ml_name)
    except Club.DoesNotExist:
        messages.error(request, "Cette mailing n'existe pas")
        return redirect(reverse('index'))
1029 1030 1031 1032
    members = (
        club.administrators.all().values('email').distinct() |
        club.members.all().values('email').distinct()
    )
1033
    seria = MailingMemberSerializer(members, many=True)
1034
    return JSONResponse(seria.data)