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 30.7 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

chirac's avatar
chirac committed
408
@login_required
409 410 411
@can_create(Whitelist)
@can_edit(User)
def add_whitelist(request, user, userid):
412 413 414 415
    """ 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
416
    whitelist_instance = Whitelist(user=user)
417 418 419 420
    whitelist = WhitelistForm(
        request.POST or None,
        instance=whitelist_instance
    )
chirac's avatar
chirac committed
421
    if whitelist.is_valid():
422
        whitelist.save()
chirac's avatar
chirac committed
423
        messages.success(request, "Accès à titre gracieux accordé")
424 425
        return redirect(reverse(
            'users:profil',
426 427
            kwargs={'userid': str(userid)}
        ))
428
    if user.is_whitelisted():
429 430 431 432
        messages.error(
            request,
            "Attention, cet utilisateur a deja un accès gracieux actif"
        )
433 434 435 436 437
    return form(
        {'userform': whitelist, 'action_name': 'Ajouter une whitelist'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
438

439

chirac's avatar
chirac committed
440
@login_required
441
@can_edit(Whitelist)
442
def edit_whitelist(request, whitelist_instance, **_kwargs):
443 444 445 446 447 448 449 450
    """ 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
451
    if whitelist.is_valid():
452 453 454
        if whitelist.changed_data:
            whitelist.save()
            messages.success(request, "Whitelist modifiée")
455
        return redirect(reverse('users:index'))
456 457 458 459 460
    return form(
        {'userform': whitelist, 'action_name': 'Editer une whitelist'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
461

462

chirac's avatar
chirac committed
463
@login_required
464
@can_create(School)
465
def add_school(request):
466 467
    """ Ajouter un établissement d'enseignement à la base de donnée,
    need cableur"""
468 469
    school = SchoolForm(request.POST or None)
    if school.is_valid():
470
        school.save()
471
        messages.success(request, "L'établissement a été ajouté")
472
        return redirect(reverse('users:index-school'))
473 474 475 476 477
    return form(
        {'userform': school, 'action_name': 'Ajouter'},
        'users/user.html',
        request
    )
478

479

chirac's avatar
chirac committed
480
@login_required
481
@can_edit(School)
482
def edit_school(request, school_instance, **_kwargs):
483 484
    """ Editer un établissement d'enseignement à partir du schoolid dans
    la base de donnée, need cableur"""
485 486
    school = SchoolForm(request.POST or None, instance=school_instance)
    if school.is_valid():
487 488 489
        if school.changed_data:
            school.save()
            messages.success(request, "Établissement modifié")
490
        return redirect(reverse('users:index-school'))
491 492 493 494 495
    return form(
        {'userform': school, 'action_name': 'Editer'},
        'users/user.html',
        request
    )
496

497

chirac's avatar
chirac committed
498
@login_required
499
@can_delete_set(School)
500
def del_school(request, instances):
501 502 503 504
    """ 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 """
505
    school = DelSchoolForm(request.POST or None, instances=instances)
506 507 508 509
    if school.is_valid():
        school_dels = school.cleaned_data['schools']
        for school_del in school_dels:
            try:
510
                school_del.delete()
511 512
                messages.success(request, "L'établissement a été supprimé")
            except ProtectedError:
513 514 515
                messages.error(
                    request,
                    "L'établissement %s est affecté à au moins un user, \
lhark's avatar
lhark committed
516
                        vous ne pouvez pas le supprimer" % school_del)
517
        return redirect(reverse('users:index-school'))
518 519 520 521 522
    return form(
        {'userform': school, 'action_name': 'Supprimer'},
        'users/user.html',
        request
    )
523

524

525 526 527
@login_required
@can_create(ListShell)
def add_shell(request):
Gabriel Detraz's avatar
Gabriel Detraz committed
528
    """ Ajouter un shell à la base de donnée"""
529 530
    shell = ShellForm(request.POST or None)
    if shell.is_valid():
531
        shell.save()
532 533
        messages.success(request, "Le shell a été ajouté")
        return redirect(reverse('users:index-shell'))
534 535 536 537 538
    return form(
        {'userform': shell, 'action_name': 'Ajouter'},
        'users/user.html',
        request
    )
539 540 541 542


@login_required
@can_edit(ListShell)
543
def edit_shell(request, shell_instance, **_kwargs):
Gabriel Detraz's avatar
Gabriel Detraz committed
544
    """ Editer un shell à partir du listshellid"""
545 546
    shell = ShellForm(request.POST or None, instance=shell_instance)
    if shell.is_valid():
547 548 549
        if shell.changed_data:
            shell.save()
            messages.success(request, "Le shell a été modifié")
550
        return redirect(reverse('users:index-shell'))
551 552 553 554 555
    return form(
        {'userform': shell, 'action_name': 'Editer'},
        'users/user.html',
        request
    )
556 557 558 559


@login_required
@can_delete(ListShell)
560
def del_shell(request, shell, **_kwargs):
561 562
    """Destruction d'un shell"""
    if request.method == "POST":
563
        shell.delete()
564 565 566 567 568 569 570 571 572
        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
    )


573
@login_required
574
@can_create(ListRight)
575
def add_listright(request):
576 577
    """ Ajouter un droit/groupe, nécessite droit bureau.
    Obligation de fournir un gid pour la synchro ldap, unique """
578 579
    listright = NewListRightForm(request.POST or None)
    if listright.is_valid():
580
        listright.save()
581
        messages.success(request, "Le droit/groupe a été ajouté")
582
        return redirect(reverse('users:index-listright'))
583 584 585 586 587
    return form(
        {'userform': listright, 'action_name': 'Ajouter'},
        'users/user.html',
        request
    )
588

589

590
@login_required
591
@can_edit(ListRight)
592
def edit_listright(request, listright_instance, **_kwargs):
593 594 595 596 597 598
    """ Editer un groupe/droit, necessite droit bureau,
    à partir du listright id """
    listright = ListRightForm(
        request.POST or None,
        instance=listright_instance
    )
599
    if listright.is_valid():
600 601 602
        if listright.changed_data:
            listright.save()
            messages.success(request, "Droit modifié")
603
        return redirect(reverse('users:index-listright'))
604 605 606 607 608
    return form(
        {'userform': listright, 'action_name': 'Editer'},
        'users/user.html',
        request
    )
609

610

611
@login_required
612
@can_delete_set(ListRight)
613
def del_listright(request, instances):
614 615
    """ Supprimer un ou plusieurs groupe, possible si il est vide, need droit
    bureau """
616
    listright = DelListRightForm(request.POST or None, instances=instances)
617 618 619 620
    if listright.is_valid():
        listright_dels = listright.cleaned_data['listrights']
        for listright_del in listright_dels:
            try:
621
                listright_del.delete()
622 623 624 625
                messages.success(request, "Le droit/groupe a été supprimé")
            except ProtectedError:
                messages.error(
                    request,
626
                    "Le groupe %s est affecté à au moins un user, \
627
                        vous ne pouvez pas le supprimer" % listright_del)
628
        return redirect(reverse('users:index-listright'))
629 630 631 632 633
    return form(
        {'userform': listright, 'action_name': 'Supprimer'},
        'users/user.html',
        request
    )
634

635

636
@login_required
637 638
@can_view_all(User)
@can_change(User, 'state')
639 640 641 642 643 644
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']
645 646 647 648
        to_archive_list = [user for user in
                           User.objects.exclude(state=User.STATE_ARCHIVE)
                           if not user.end_access()
                           or user.end_access() < date]
649 650 651
        if "valider" in request.POST:
            for user in to_archive_list:
                with transaction.atomic(), reversion.create_revision():
652
                    user.archive()
653 654
                    user.save()
                    reversion.set_comment("Archivage")
655 656 657
            messages.success(request, "%s users ont été archivés" % len(
                to_archive_list
            ))
658
            return redirect(reverse('users:index'))
659 660 661 662 663 664
    return form(
        {'userform': to_archive_date, 'to_archive_list': to_archive_list},
        'users/mass_archive.html',
        request
    )

665

chirac's avatar
chirac committed
666
@login_required
667
@can_view_all(Adherent)
chirac's avatar
chirac committed
668
def index(request):
669
    """ Affiche l'ensemble des adherents, need droit cableur """
670
    pagination_number = GeneralOption.get_cached_value('pagination_number')
671
    users_list = Adherent.objects.select_related('room')
672 673 674 675 676 677
    users_list = SortTable.sort(
        users_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX
    )
678
    users_list = re2o_paginator(request, users_list, pagination_number)
679
    return render(request, 'users/index.html', {'users_list': users_list})
680

681

682
@login_required
683
@can_view_all(Club)
684 685
def index_clubs(request):
    """ Affiche l'ensemble des clubs, need droit cableur """
686
    pagination_number = GeneralOption.get_cached_value('pagination_number')
687
    clubs_list = Club.objects.select_related('room')
688 689 690 691 692 693
    clubs_list = SortTable.sort(
        clubs_list,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX
    )
694
    clubs_list = re2o_paginator(request, clubs_list, pagination_number)
695 696 697 698 699
    return render(
        request,
        'users/index_clubs.html',
        {'clubs_list': clubs_list}
    )
700 701


chirac's avatar
chirac committed
702
@login_required
703
@can_view_all(Ban)
704
def index_ban(request):
705
    """ Affiche l'ensemble des ban, need droit cableur """
706
    pagination_number = GeneralOption.get_cached_value('pagination_number')
707 708 709 710 711 712 713
    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
    )
714
    ban_list = re2o_paginator(request, ban_list, pagination_number)
715
    return render(request, 'users/index_ban.html', {'ban_list': ban_list})
716

717

chirac's avatar
chirac committed
718
@login_required
719
@can_view_all(Whitelist)
720
def index_white(request):
721
    """ Affiche l'ensemble des whitelist, need droit cableur """
722
    pagination_number = GeneralOption.get_cached_value('pagination_number')
723 724 725 726 727 728 729
    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
    )
730
    white_list = re2o_paginator(request, white_list, pagination_number)
731 732 733 734 735 736
    return render(
        request,
        'users/index_whitelist.html',
        {'white_list': white_list}
    )

737

chirac's avatar
chirac committed
738
@login_required
739
@can_view_all(School)
740
def index_school(request):
741
    """ Affiche l'ensemble des établissement"""
742
    school_list = School.objects.order_by('name')
743 744 745 746 747 748 749
    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
    )
750
    school_list = re2o_paginator(request, school_list, pagination_number)
751 752 753 754 755 756
    return render(
        request,
        'users/index_schools.html',
        {'school_list': school_list}
    )

757

758 759 760 761 762 763 764 765 766 767 768 769
@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}
    )


770
@login_required
771
@can_view_all(ListRight)
772
def index_listright(request):
773
    """ Affiche l'ensemble des droits"""
774 775
    listright_list = ListRight.objects.order_by('unix_name')\
        .prefetch_related('permissions').prefetch_related('user_set')
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
776
    superuser_right = User.objects.filter(is_superuser=True)
777 778 779
    return render(
        request,
        'users/index_listright.html',
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
780 781 782 783
        {
            'listright_list': listright_list,
            'superuser_right' : superuser_right,
        }
784 785
    )

786

787
@login_required
788
@can_view_all(ServiceUser)
789 790 791
def index_serviceusers(request):
    """ Affiche les users de services (pour les accès ldap)"""
    serviceusers_list = ServiceUser.objects.order_by('pseudo')
792 793 794 795 796 797
    return render(
        request,
        'users/index_serviceusers.html',
        {'serviceusers_list': serviceusers_list}
    )

798

799 800
@login_required
def mon_profil(request):
801
    """ Lien vers profil, renvoie request.id à la fonction """
802 803
    return redirect(reverse(
        'users:profil',
804
        kwargs={'userid': str(request.user.id)}
805
        ))
806

807

chirac's avatar
chirac committed
808
@login_required
809
@can_view(User)
810
def profil(request, users, **_kwargs):
811
    """ Affiche un profil, self or cableur, prend un userid en argument """
812 813 814 815 816
    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')
817 818 819 820 821 822
    machines = SortTable.sort(
        machines,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.MACHINES_INDEX
    )
823 824 825
    pagination_large_number = GeneralOption.get_cached_value(
        'pagination_large_number'
    )
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
826
    nb_machines = machines.count()
827
    machines = re2o_paginator(request, machines, pagination_large_number)
chirac's avatar
chirac committed
828
    factures = Facture.objects.filter(user=users)
829 830 831 832 833 834
    factures = SortTable.sort(
        factures,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.COTISATIONS_INDEX
    )
chirac's avatar
chirac committed
835
    bans = Ban.objects.filter(user=users)
836 837 838 839 840 841
    bans = SortTable.sort(
        bans,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_BAN
    )
chirac's avatar
chirac committed
842
    whitelists = Whitelist.objects.filter(user=users)
843 844 845 846 847 848
    whitelists = SortTable.sort(
        whitelists,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_WHITE
    )
849
    user_solde = OptionalUser.get_cached_value('user_solde')
850
    allow_online_payment = AssoOption.get_cached_value('payment') != 'NONE'
851 852 853 854
    return render(
        request,
        'users/profil.html',
        {
855
            'users': users,
856
            'machines_list': machines,
Levy--Falk Hugo's avatar
Levy--Falk Hugo committed
857
            'nb_machines' : nb_machines,
858 859 860
            'facture_list': factures,
            'ban_list': bans,
            'white_list': whitelists,
chibrac's avatar
chibrac committed
861
            'user_solde': user_solde,
862
            'allow_online_payment': allow_online_payment,
lhark's avatar
lhark committed
863 864
        }
    )
865

866

chirac's avatar
chirac committed
867
def reset_password(request):
868
    """ Reintialisation du mot de passe si mdp oublié """
chirac's avatar
chirac committed
869 870 871
    userform = ResetPasswordForm(request.POST or None)
    if userform.is_valid():
        try:
872 873 874 875
            user = User.objects.get(
                pseudo=userform.cleaned_data['pseudo'],
                email=userform.cleaned_data['email']
            )
chirac's avatar
chirac committed
876 877
        except User.DoesNotExist:
            messages.error(request, "Cet utilisateur n'existe pas")
878 879 880 881 882
            return form(
                {'userform': userform, 'action_name': 'Réinitialiser'},
                'users/user.html',
                request
            )
883
        user.reset_passwd_mail(request)
884 885
        messages.success(request, "Un mail pour l'initialisation du mot\
        de passe a été envoyé")
886
        redirect(reverse('index'))
887 888 889 890 891
    return form(
        {'userform': userform, 'action_name': 'Réinitialiser'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
892

893

894
def process(request, token):
895
    """Process, lien pour la reinitialisation du mot de passe"""
896 897 898 899 900 901
    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
902
        messages.error(request, "Entrée incorrecte, contactez un admin")
903
        redirect(reverse('index'))
904

905

906
def process_passwd(request, req):
907 908
    """Process le changeemnt de mot de passe, renvoie le formulaire
    demandant le nouveau password"""
909
    user = req.user
910
    u_form = PassForm(request.POST or None, instance=user, user=request.user)
911
    if u_form.is_valid():
912 913 914 915 916
        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
917
        return redirect(reverse('index'))
918 919 920 921 922
    return form(
        {'userform': u_form, 'action_name': 'Changer le mot de passe'},
        'users/user.html',
        request
    )
923

924 925

class JSONResponse(HttpResponse):
926
    """ Framework Rest """
927 928 929 930 931
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

932

933 934
@csrf_exempt
@login_required
935
@permission_required('machines.serveur')
936
def ml_std_list(_request):
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
    """ 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')
962
def ml_club_list(_request):
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    """ 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'))
994 995 996 997
    members = (
        club.administrators.all().values('email').distinct() |
        club.members.all().values('email').distinct()
    )
998
    seria = MailingMemberSerializer(members, many=True)
999
    return JSONResponse(seria.data)