views.py 32.4 KB
Newer Older
lhark's avatar
lhark committed
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.

chirac's avatar
chirac committed
23
# App de gestion des users pour re2o
Dalahro's avatar
Dalahro committed
24
# Goulven Kermarec, Gabriel Détraz, Lemesle Augustin
chirac's avatar
chirac committed
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, Count, Max
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
Maël Kervella's avatar
Maël Kervella committed
50
from reversion import revisions as reversion
51

52
from cotisations.models import Facture, Paiement
Maël Kervella's avatar
Maël Kervella committed
53
from machines.models import Machine
Gabriel Detraz's avatar
Gabriel Detraz committed
54
from preferences.models import OptionalUser, GeneralOption, AssoOption
Maël Kervella's avatar
Maël Kervella committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
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
)
70
from cotisations.utils import find_payment_method
lhark's avatar
lhark committed
71

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

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

107
@can_create(Adherent)
chirac's avatar
chirac committed
108
def new_user(request):
109 110
    """ Vue de création d'un nouvel utilisateur,
    envoie un mail pour le mot de passe"""
111
    user = AdherentForm(request.POST or None, user=request.user)
112 113
    GTU_sum_up = GeneralOption.get_cached_value('GTU_sum_up')
    GTU = GeneralOption.get_cached_value('GTU')
114
    if user.is_valid():
115
        user = 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',
Maël Kervella's avatar
Maël Kervella committed
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',
Maël Kervella's avatar
Maël Kervella committed
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"""
Maël Kervella's avatar
Maël Kervella committed
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',
Maël Kervella's avatar
Maël Kervella committed
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:
Maël Kervella's avatar
Maël Kervella committed
194
        user_form = AdherentForm(
195 196 197 198
            request.POST or None,
            instance=user.adherent,
            user=request.user
        )
Maël Kervella's avatar
Maël Kervella committed
199 200
    else:
        user_form = ClubForm(
201 202 203 204
            request.POST or None,
            instance=user.club,
            user=request.user
        )
Maël Kervella's avatar
Maël Kervella committed
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',
Maël Kervella's avatar
Maël Kervella committed
211 212 213
            kwargs={'userid': str(userid)}
        ))
    return form(
Maël Kervella's avatar
Maël Kervella committed
214
        {'userform': user_form, 'action_name': "Editer l'utilisateur"},
Maël Kervella's avatar
Maël Kervella committed
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):
chirac's avatar
chirac committed
223
    """ Change the state (active/unactive/archived) of a user"""
Maël Kervella's avatar
Maël Kervella committed
224 225 226 227
    state_form = StateForm(request.POST or None, instance=user)
    if state_form.is_valid():
        if state_form.changed_data:
            state_form.save()
228
            messages.success(request, "Etat changé avec succès")
229 230
        return redirect(reverse(
            'users:profil',
Maël Kervella's avatar
Maël Kervella committed
231 232 233
            kwargs={'userid': str(userid)}
        ))
    return form(
Maël Kervella's avatar
Maël Kervella committed
234
        {'userform': state_form, 'action_name': "Editer l'état"},
Maël Kervella's avatar
Maël Kervella committed
235 236 237
        'users/user.html',
        request
    )
238

239

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


chirac's avatar
chirac committed
261
@login_required
262
@can_edit(User, 'password')
263
def password(request, user, userid):
chirac's avatar
chirac committed
264 265 266
    """ 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 """
267
    u_form = PassForm(request.POST or None, instance=user, user=request.user)
268
    if u_form.is_valid():
269 270 271
        if u_form.changed_data:
            u_form.save()
            messages.success(request, "Le mot de passe a changé")
272
        return redirect(reverse(
Maël Kervella's avatar
Maël Kervella committed
273
            'users:profil',
Maël Kervella's avatar
Maël Kervella committed
274
            kwargs={'userid': str(userid)}
275
        ))
Maël Kervella's avatar
Maël Kervella committed
276 277 278 279 280
    return form(
        {'userform': u_form, 'action_name': 'Changer le mot de passe'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
281

282

283
@login_required
284
@can_edit(User, 'groups')
285
def del_group(request, user, listrightid, **_kwargs):
Maël Kervella's avatar
Maël Kervella committed
286
    """ View used to delete a group """
287 288 289
    user.groups.remove(ListRight.objects.get(id=listrightid))
    user.save()
    messages.success(request, "Droit supprimé à %s" % user)
290
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
291 292


Hugo LEVY-FALK's avatar
Hugo LEVY-FALK committed
293
@login_required
Hugo LEVY-FALK's avatar
ACL  
Hugo LEVY-FALK committed
294
@can_edit(User, 'is_superuser')
Hugo LEVY-FALK's avatar
Hugo LEVY-FALK committed
295 296 297 298 299 300 301 302
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'))


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

321

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

341

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

356

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

384

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

403

404 405 406
@login_required
@can_delete(Ban)
def del_ban(request, ban, **_kwargs):
407 408 409 410 411 412 413 414 415 416 417 418 419
    """ 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
    )
420

421

chirac's avatar
chirac committed
422
@login_required
423 424 425
@can_create(Whitelist)
@can_edit(User)
def add_whitelist(request, user, userid):
426 427 428 429
    """ 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
430
    whitelist_instance = Whitelist(user=user)
431 432 433 434
    whitelist = WhitelistForm(
        request.POST or None,
        instance=whitelist_instance
    )
chirac's avatar
chirac committed
435
    if whitelist.is_valid():
436
        whitelist.save()
chirac's avatar
chirac committed
437
        messages.success(request, "Accès à titre gracieux accordé")
438 439
        return redirect(reverse(
            'users:profil',
Maël Kervella's avatar
Maël Kervella committed
440 441
            kwargs={'userid': str(userid)}
        ))
442
    if user.is_whitelisted():
443 444 445 446
        messages.error(
            request,
            "Attention, cet utilisateur a deja un accès gracieux actif"
        )
Maël Kervella's avatar
Maël Kervella committed
447 448 449 450 451
    return form(
        {'userform': whitelist, 'action_name': 'Ajouter une whitelist'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
452

453

chirac's avatar
chirac committed
454
@login_required
455
@can_edit(Whitelist)
456
def edit_whitelist(request, whitelist_instance, **_kwargs):
457 458 459 460 461 462 463 464
    """ 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
465
    if whitelist.is_valid():
466 467 468
        if whitelist.changed_data:
            whitelist.save()
            messages.success(request, "Whitelist modifiée")
469
        return redirect(reverse('users:index'))
Maël Kervella's avatar
Maël Kervella committed
470 471 472 473 474
    return form(
        {'userform': whitelist, 'action_name': 'Editer une whitelist'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
475

476

477 478 479
@login_required
@can_delete(Whitelist)
def del_whitelist(request, whitelist, **_kwargs):
480 481 482 483 484 485 486 487 488 489 490 491 492 493
    """ 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
    )

494

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

511

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

529

chirac's avatar
chirac committed
530
@login_required
531
@can_delete_set(School)
532
def del_school(request, instances):
533 534 535 536
    """ 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 """
537
    school = DelSchoolForm(request.POST or None, instances=instances)
chirac's avatar
chirac committed
538 539 540 541
    if school.is_valid():
        school_dels = school.cleaned_data['schools']
        for school_del in school_dels:
            try:
542
                school_del.delete()
chirac's avatar
chirac committed
543 544
                messages.success(request, "L'établissement a été supprimé")
            except ProtectedError:
545 546 547
                messages.error(
                    request,
                    "L'établissement %s est affecté à au moins un user, \
lhark's avatar
lhark committed
548
                        vous ne pouvez pas le supprimer" % school_del)
549
        return redirect(reverse('users:index-school'))
Maël Kervella's avatar
Maël Kervella committed
550 551 552 553 554
    return form(
        {'userform': school, 'action_name': 'Supprimer'},
        'users/user.html',
        request
    )
chirac's avatar
chirac committed
555

556

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


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


@login_required
@can_delete(ListShell)
592
def del_shell(request, shell, **_kwargs):
593 594
    """Destruction d'un shell"""
    if request.method == "POST":
595
        shell.delete()
596 597 598 599 600 601 602 603 604
        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
    )


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

621

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

642

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

667

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

697

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

713

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


chirac's avatar
chirac committed
734
@login_required
735
@can_view_all(Ban)
736
def index_ban(request):
chirac's avatar
chirac committed
737
    """ Affiche l'ensemble des ban, need droit cableur """
738
    pagination_number = GeneralOption.get_cached_value('pagination_number')
739 740 741 742 743 744 745
    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
    )
746
    ban_list = re2o_paginator(request, ban_list, pagination_number)
747
    return render(request, 'users/index_ban.html', {'ban_list': ban_list})
748

749

chirac's avatar
chirac committed
750
@login_required
751
@can_view_all(Whitelist)
752
def index_white(request):
chirac's avatar
chirac committed
753
    """ Affiche l'ensemble des whitelist, need droit cableur """
754
    pagination_number = GeneralOption.get_cached_value('pagination_number')
755 756 757 758 759 760 761
    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
    )
762
    white_list = re2o_paginator(request, white_list, pagination_number)
763 764 765 766 767 768
    return render(
        request,
        'users/index_whitelist.html',
        {'white_list': white_list}
    )

769

chirac's avatar
chirac committed
770
@login_required
771
@can_view_all(School)
772
def index_school(request):
773
    """ Affiche l'ensemble des établissement"""
774
    school_list = School.objects.order_by('name')
775 776 777 778 779 780 781
    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
    )
782
    school_list = re2o_paginator(request, school_list, pagination_number)
783 784 785 786 787 788
    return render(
        request,
        'users/index_schools.html',
        {'school_list': school_list}
    )

789

790 791 792 793 794 795 796 797 798 799 800 801
@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}
    )


802
@login_required
803
@can_view_all(ListRight)
804
def index_listright(request):
805
    """ Affiche l'ensemble des droits"""
806 807 808 809 810
    rights = {}
    for right in (ListRight.objects
                  .order_by('name')
                  .prefetch_related('permissions')
                  .prefetch_related('user_set')
811
                  .prefetch_related('user_set__facture_set__vente_set__cotisation')
812 813 814
                 ):
        rights[right] = (right.user_set
                         .annotate(action_number=Count('revision'),
815 816
                                   last_seen=Max('revision__date_created'),
                                   end_adhesion=Max('facture__vente__cotisation__date_end'))
817 818 819 820
                        )
    superusers = (User.objects
                  .filter(is_superuser=True)
                  .annotate(action_number=Count('revision'),
821 822
                            last_seen=Max('revision__date_created'),
                            end_adhesion=Max('facture__vente__cotisation__date_end'))
823
                 )
824 825 826
    return render(
        request,
        'users/index_listright.html',
Hugo LEVY-FALK's avatar
Hugo LEVY-FALK committed
827
        {
828 829
            'rights': rights,
            'superusers' : superusers,
Hugo LEVY-FALK's avatar
Hugo LEVY-FALK committed
830
        }
831 832
    )

833

834
@login_required
835
@can_view_all(ServiceUser)
836 837 838
def index_serviceusers(request):
    """ Affiche les users de services (pour les accès ldap)"""
    serviceusers_list = ServiceUser.objects.order_by('pseudo')
839 840 841 842 843 844
    return render(
        request,
        'users/index_serviceusers.html',
        {'serviceusers_list': serviceusers_list}
    )

845

846 847
@login_required
def mon_profil(request):
chirac's avatar
chirac committed
848
    """ Lien vers profil, renvoie request.id à la fonction """
849 850
    return redirect(reverse(
        'users:profil',
Maël Kervella's avatar
Maël Kervella committed
851
        kwargs={'userid': str(request.user.id)}
852
    ))
853

854

chirac's avatar
chirac committed
855
@login_required
856
@can_view(User)
857
def profil(request, users, **_kwargs):
chirac's avatar
chirac committed
858
    """ Affiche un profil, self or cableur, prend un userid en argument """
859 860 861 862 863
    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')
864 865 866 867 868 869
    machines = SortTable.sort(
        machines,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.MACHINES_INDEX
    )
Maël Kervella's avatar
Maël Kervella committed
870 871 872
    pagination_large_number = GeneralOption.get_cached_value(
        'pagination_large_number'
    )
Hugo LEVY-FALK's avatar
Fix #86  
Hugo LEVY-FALK committed
873
    nb_machines = machines.count()
874
    machines = re2o_paginator(request, machines, pagination_large_number)
chirac's avatar
chirac committed
875
    factures = Facture.objects.filter(user=users)
876 877 878 879 880 881
    factures = SortTable.sort(
        factures,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.COTISATIONS_INDEX
    )
chirac's avatar
chirac committed
882
    bans = Ban.objects.filter(user=users)
883 884 885 886 887 888
    bans = SortTable.sort(
        bans,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_BAN
    )
chirac's avatar
chirac committed
889
    whitelists = Whitelist.objects.filter(user=users)
890 891 892 893 894 895
    whitelists = SortTable.sort(
        whitelists,
        request.GET.get('col'),
        request.GET.get('order'),
        SortTable.USERS_INDEX_WHITE
    )
896 897 898 899 900 901 902 903 904
    try:
        balance = find_payment_method(Paiement.objects.get(is_balance=True))
    except Paiement.DoesNotExist:
        user_solde = False
    else:
        user_solde = (
            balance is not None
            and balance.can_credit_balance(request.user)
        )
905 906 907 908
    return render(
        request,
        'users/profil.html',
        {
909
            'users': users,
910
            'machines_list': machines,
911
            'nb_machines': nb_machines,
912 913 914
            'facture_list': factures,
            'ban_list': bans,
            'white_list': whitelists,
chibrac's avatar
chibrac committed
915
            'user_solde': user_solde,
Gabriel Detraz's avatar
Gabriel Detraz committed
916 917
            'solde_activated': Paiement.objects.filter(is_balance=True).exists(),
            'asso_name': AssoOption.objects.first().name
lhark's avatar
lhark committed
918 919
        }
    )
root's avatar
root committed
920

921

chirac's avatar
chirac committed
922
def reset_password(request):
chirac's avatar
chirac committed
923
    """ Reintialisation du mot de passe si mdp oublié """