views.py 31.8 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

from __future__ import unicode_literals

29 30
from django.shortcuts import get_object_or_404, render, redirect
from django.template.context_processors import csrf
31
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
32
from django.template import Context, RequestContext, loader
33
from django.contrib import messages
34
from django.contrib.auth.decorators import login_required, permission_required
chirac's avatar
chirac committed
35
from django.db.models import Max, ProtectedError
36
from django.db import IntegrityError
37
from django.core.mail import send_mail
38
from django.utils import timezone
39
from django.core.urlresolvers import reverse
40
from django.db import transaction
41 42 43 44 45
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from rest_framework.renderers import JSONRenderer

lhark's avatar
lhark committed
46

root's avatar
root committed
47
from reversion.models import Version
48
from reversion import revisions as reversion
49 50
from users.serializers import MailSerializer
from users.models import User, Right, Ban, Whitelist, School, ListRight, Request, ServiceUser, all_has_access
51 52
from users.forms import DelRightForm, BanForm, WhitelistForm, DelSchoolForm, DelListRightForm, NewListRightForm
from users.forms import EditInfoForm, InfoForm, BaseInfoForm, StateForm, RightForm, SchoolForm, EditServiceUserForm, ServiceUserForm, ListRightForm
root's avatar
root committed
53
from cotisations.models import Facture
chirac's avatar
chirac committed
54
from machines.models import Machine, Interface
55
from users.forms import MassArchiveForm, PassForm, ResetPasswordForm
56
from preferences.models import OptionalUser, AssoOption, GeneralOption
chirac's avatar
chirac committed
57

58
from re2o.login import hashNT
chirac's avatar
chirac committed
59

chirac's avatar
chirac committed
60

chirac's avatar
chirac committed
61 62 63
def form(ctx, template, request):
    c = ctx
    c.update(csrf(request))
64
    return render(request, template, c)
65

66 67
def password_change_action(u_form, user, request, req=False):
    """ Fonction qui effectue le changeemnt de mdp bdd"""
68
    user.set_user_password(u_form.cleaned_data['passwd1'])
69 70 71
    with transaction.atomic(), reversion.create_revision():
        user.save()
        reversion.set_comment("Réinitialisation du mot de passe")
72 73 74 75 76 77
    messages.success(request, "Le mot de passe a changé")
    if req:
        req.delete()
        return redirect("/")
    return redirect("/users/profil/" + str(user.id))

chirac's avatar
chirac committed
78
@login_required
chirac's avatar
chirac committed
79
@permission_required('cableur')
chirac's avatar
chirac committed
80
def new_user(request):
chirac's avatar
chirac committed
81
    """ Vue de création d'un nouvel utilisateur, envoie un mail pour le mot de passe"""
82 83
    user = InfoForm(request.POST or None)
    if user.is_valid():
84
        user = user.save(commit=False)
85 86 87 88
        with transaction.atomic(), reversion.create_revision():
            user.save()
            reversion.set_user(request.user)
            reversion.set_comment("Création")
89
        user.reset_passwd_mail(request)
90
        messages.success(request, "L'utilisateur %s a été crée, un mail pour l'initialisation du mot de passe a été envoyé" % user.pseudo)
91
        return redirect("/users/profil/" + str(user.id))
92
    return form({'userform': user}, 'users/user.html', request)
93

chirac's avatar
chirac committed
94
@login_required
95
def edit_info(request, userid):
chirac's avatar
chirac committed
96 97
    """ Edite un utilisateur à partir de son id, 
    si l'id est différent de request.user, vérifie la possession du droit cableur """
98 99 100
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
101
        messages.error(request, "Utilisateur inexistant")
102
        return redirect("/users/")
103 104 105
    if not request.user.has_perms(('cableur',)) and user != request.user:
        messages.error(request, "Vous ne pouvez pas modifier un autre user que vous sans droit cableur")
        return redirect("/users/profil/" + str(request.user.id))
106 107 108
    if not request.user.has_perms(('cableur',)):
        user = BaseInfoForm(request.POST or None, instance=user)
    else:
109
        user = InfoForm(request.POST or None, instance=user)
110
    if user.is_valid():
111 112 113 114
        with transaction.atomic(), reversion.create_revision():
            user.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in user.changed_data))
115
        messages.success(request, "L'user a bien été modifié")
116
        return redirect("/users/profil/" + userid)
117
    return form({'userform': user}, 'users/user.html', request)
118

chirac's avatar
chirac committed
119
@login_required
chirac's avatar
chirac committed
120
@permission_required('bureau')
121
def state(request, userid):
chirac's avatar
chirac committed
122
    """ Changer l'etat actif/desactivé/archivé d'un user, need droit bureau """
123 124 125
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
126
        messages.error(request, "Utilisateur inexistant")
127
        return redirect("/users/")
128 129
    state = StateForm(request.POST or None, instance=user)
    if state.is_valid():
130
        with transaction.atomic(), reversion.create_revision():
131 132 133 134 135 136
            if state.cleaned_data['state'] == User.STATE_ARCHIVE:
                user.archive()
            elif state.cleaned_data['state'] == User.STATE_ACTIVE:
                user.unarchive()
            elif state.cleaned_data['state'] == User.STATE_DISABLED:
                user.state = User.STATE_DISABLED
137 138
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in state.changed_data))
139
            user.save()
140
        messages.success(request, "Etat changé avec succès")
141
        return redirect("/users/profil/" + userid)
142
    return form({'userform': state}, 'users/user.html', request)
143

chirac's avatar
chirac committed
144
@login_required
145
def password(request, userid):
chirac's avatar
chirac committed
146 147 148
    """ 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 """
149 150 151
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
152
        messages.error(request, "Utilisateur inexistant")
153
        return redirect("/users/")
154 155 156 157
    if not request.user.has_perms(('cableur',)) and user != request.user:
        messages.error(request, "Vous ne pouvez pas modifier un autre user que vous sans droit cableur")
        return redirect("/users/profil/" + str(request.user.id))
    if not request.user.has_perms(('bureau',)) and user != request.user and Right.objects.filter(user=user):
158 159
        messages.error(request, "Il faut les droits bureau pour modifier le mot de passe d'un membre actif")
        return redirect("/users/profil/" + str(request.user.id))
160 161
    u_form = PassForm(request.POST or None)
    if u_form.is_valid():
162
        return password_change_action(u_form, user, request)
163
    return form({'userform': u_form}, 'users/user.html', request)
chirac's avatar
chirac committed
164

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
@login_required
@permission_required('infra')
def new_serviceuser(request):
    """ Vue de création d'un nouvel utilisateur service"""
    user = ServiceUserForm(request.POST or None)
    if user.is_valid():
        user_object = user.save(commit=False)
        with transaction.atomic(), reversion.create_revision():
            user_object.set_password(user.cleaned_data['password'])
            user_object.save()
            reversion.set_user(request.user)
            reversion.set_comment("Création")
        messages.success(request, "L'utilisateur %s a été crée" % user_object.pseudo)
        return redirect("/users/index_serviceusers/")
    return form({'userform': user}, 'users/user.html', request)

@login_required
@permission_required('infra')
def edit_serviceuser(request, userid):
    """ Edite un utilisateur à partir de son id, 
    si l'id est différent de request.user, vérifie la possession du droit cableur """
    try:
        user = ServiceUser.objects.get(pk=userid)
    except ServiceUser.DoesNotExist:
        messages.error(request, "Utilisateur inexistant")
        return redirect("/users/")
    user = EditServiceUserForm(request.POST or None, instance=user)
    if user.is_valid():
        user_object = user.save(commit=False)
        with transaction.atomic(), reversion.create_revision():
            if user.cleaned_data['password']:
                user_object.set_password(user.cleaned_data['password'])
            user_object.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in user.changed_data))
        messages.success(request, "L'user a bien été modifié")
        return redirect("/users/index_serviceusers")
    return form({'userform': user}, 'users/user.html', request)

@login_required
@permission_required('infra')
def del_serviceuser(request, userid):
    try:
        user = ServiceUser.objects.get(pk=userid)
    except ServiceUser.DoesNotExist:
        messages.error(request, u"Utilisateur inexistant" )
        return redirect("/users/")
    if request.method == "POST":
        with transaction.atomic(), reversion.create_revision():
            user.delete()
            reversion.set_user(request.user)
        messages.success(request, "L'user a été détruite")
        return redirect("/users/index_serviceusers/")
    return form({'objet': user, 'objet_name': 'serviceuser'}, 'users/delete.html', request)

chirac's avatar
chirac committed
220
@login_required
221
@permission_required('bureau')
222
def add_right(request, userid):
chirac's avatar
chirac committed
223
    """ Ajout d'un droit à un user, need droit bureau """
224 225 226
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
227
        messages.error(request, "Utilisateur inexistant")
228
        return redirect("/users/")
lhark's avatar
lhark committed
229 230
    right = RightForm(request.POST or None)
    if right.is_valid():
231 232 233
        right = right.save(commit=False)
        right.user = user
        try:
chirac's avatar
chirac committed
234 235 236 237
            with transaction.atomic(), reversion.create_revision():
                reversion.set_user(request.user)
                reversion.set_comment("Ajout du droit %s" % right.right)
                right.save()
238 239 240
            messages.success(request, "Droit ajouté")
        except IntegrityError:
            pass
241
        return redirect("/users/profil/" + userid)
lhark's avatar
lhark committed
242 243
    return form({'userform': right}, 'users/user.html', request)

chirac's avatar
chirac committed
244
@login_required
245
@permission_required('bureau')
246
def del_right(request):
chirac's avatar
chirac committed
247
    """ Supprimer un droit à un user, need droit bureau """
248 249 250 251 252 253 254 255 256 257 258 259 260
    user_right_list = dict()
    for right in ListRight.objects.all():
        user_right_list[right]= DelRightForm(right, request.POST or None)
    for keys, right_item in user_right_list.items():
        if right_item.is_valid():
            right_del = right_item.cleaned_data['rights']
            with transaction.atomic(), reversion.create_revision():
                reversion.set_user(request.user)
                reversion.set_comment("Retrait des droit %s" % ','.join(str(deleted_right) for deleted_right in right_del))
                right_del.delete()
            messages.success(request, "Droit retiré avec succès")
            return redirect("/users/")
    return form({'userform': user_right_list}, 'users/del_right.html', request)
261

chirac's avatar
chirac committed
262
@login_required
chirac's avatar
chirac committed
263
@permission_required('bofh')
264
def add_ban(request, userid):
chirac's avatar
chirac committed
265 266
    """ Ajouter un banissement, nécessite au moins le droit bofh (a fortiori bureau)
    Syntaxe : JJ/MM/AAAA , heure optionnelle, prend effet immédiatement"""
267 268 269
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
270
        messages.error(request, "Utilisateur inexistant")
271 272 273 274
        return redirect("/users/")
    ban_instance = Ban(user=user)
    ban = BanForm(request.POST or None, instance=ban_instance)
    if ban.is_valid():
275
        with transaction.atomic(), reversion.create_revision():
276
            ban_object = ban.save()
277 278
            reversion.set_user(request.user)
            reversion.set_comment("Création")
279
        messages.success(request, "Bannissement ajouté")
280
        return redirect("/users/profil/" + userid)
281
    if user.is_ban:
282 283 284 285
        messages.error(
            request,
            "Attention, cet utilisateur a deja un bannissement actif"
        )
286 287
    return form({'userform': ban}, 'users/user.html', request)

chirac's avatar
chirac committed
288
@login_required
chirac's avatar
chirac committed
289
@permission_required('bofh')
290
def edit_ban(request, banid):
chirac's avatar
chirac committed
291 292
    """ Editer un bannissement, nécessite au moins le droit bofh (a fortiori bureau)
    Syntaxe : JJ/MM/AAAA , heure optionnelle, prend effet immédiatement"""
293 294
    try:
        ban_instance = Ban.objects.get(pk=banid)
chirac's avatar
chirac committed
295
    except Ban.DoesNotExist:
296
        messages.error(request, "Entrée inexistante")
297 298 299
        return redirect("/users/")
    ban = BanForm(request.POST or None, instance=ban_instance)
    if ban.is_valid():
300 301 302 303
        with transaction.atomic(), reversion.create_revision():
            ban.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in ban.changed_data))
304 305 306 307
        messages.success(request, "Bannissement modifié")
        return redirect("/users/")
    return form({'userform': ban}, 'users/user.html', request)

chirac's avatar
chirac committed
308
@login_required
chirac's avatar
chirac committed
309
@permission_required('cableur')
chirac's avatar
chirac committed
310
def add_whitelist(request, userid):
chirac's avatar
chirac committed
311 312
    """ 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
313 314 315
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
316
        messages.error(request, "Utilisateur inexistant")
chirac's avatar
chirac committed
317 318 319 320
        return redirect("/users/")
    whitelist_instance = Whitelist(user=user)
    whitelist = WhitelistForm(request.POST or None, instance=whitelist_instance)
    if whitelist.is_valid():
321 322 323 324
        with transaction.atomic(), reversion.create_revision():
            whitelist.save()
            reversion.set_user(request.user)
            reversion.set_comment("Création")
chirac's avatar
chirac committed
325
        messages.success(request, "Accès à titre gracieux accordé")
326
        return redirect("/users/profil/" + userid)
327
    if user.is_whitelisted:
328 329 330 331
        messages.error(
            request,
            "Attention, cet utilisateur a deja un accès gracieux actif"
        )
chirac's avatar
chirac committed
332 333
    return form({'userform': whitelist}, 'users/user.html', request)

chirac's avatar
chirac committed
334
@login_required
chirac's avatar
chirac committed
335
@permission_required('cableur')
chirac's avatar
chirac committed
336
def edit_whitelist(request, whitelistid):
chirac's avatar
chirac committed
337 338
    """ Editer 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
339 340 341
    try:
        whitelist_instance = Whitelist.objects.get(pk=whitelistid)
    except Whitelist.DoesNotExist:
342
        messages.error(request, "Entrée inexistante")
chirac's avatar
chirac committed
343 344 345
        return redirect("/users/")
    whitelist = WhitelistForm(request.POST or None, instance=whitelist_instance)
    if whitelist.is_valid():
346 347 348 349
        with transaction.atomic(), reversion.create_revision():
            whitelist.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in whitelist.changed_data))
chirac's avatar
chirac committed
350 351 352 353
        messages.success(request, "Whitelist modifiée")
        return redirect("/users/")
    return form({'userform': whitelist}, 'users/user.html', request)

chirac's avatar
chirac committed
354
@login_required
chirac's avatar
chirac committed
355
@permission_required('cableur')
chirac's avatar
chirac committed
356
def add_school(request):
chirac's avatar
chirac committed
357
    """ Ajouter un établissement d'enseignement à la base de donnée, need cableur"""
chirac's avatar
chirac committed
358 359
    school = SchoolForm(request.POST or None)
    if school.is_valid():
360 361 362 363
        with transaction.atomic(), reversion.create_revision():
            school.save()
            reversion.set_user(request.user)
            reversion.set_comment("Création")
chirac's avatar
chirac committed
364
        messages.success(request, "L'établissement a été ajouté")
365
        return redirect("/users/index_school/")
366
    return form({'userform': school}, 'users/user.html', request)
chirac's avatar
chirac committed
367

chirac's avatar
chirac committed
368
@login_required
chirac's avatar
chirac committed
369
@permission_required('cableur')
370
def edit_school(request, schoolid):
chirac's avatar
chirac committed
371
    """ Editer un établissement d'enseignement à partir du schoolid dans la base de donnée, need cableur"""
372 373 374 375 376 377 378
    try:
        school_instance = School.objects.get(pk=schoolid)
    except School.DoesNotExist:
        messages.error(request, u"Entrée inexistante" )
        return redirect("/users/")
    school = SchoolForm(request.POST or None, instance=school_instance)
    if school.is_valid():
379 380 381 382
        with transaction.atomic(), reversion.create_revision():
            school.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in school.changed_data))
383 384 385 386
        messages.success(request, "Établissement modifié")
        return redirect("/users/index_school/")
    return form({'userform': school}, 'users/user.html', request)

chirac's avatar
chirac committed
387
@login_required
chirac's avatar
chirac committed
388
@permission_required('cableur')
chirac's avatar
chirac committed
389
def del_school(request):
chirac's avatar
chirac committed
390 391
    """ 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 """
chirac's avatar
chirac committed
392 393 394 395 396
    school = DelSchoolForm(request.POST or None)
    if school.is_valid():
        school_dels = school.cleaned_data['schools']
        for school_del in school_dels:
            try:
397 398 399
                with transaction.atomic(), reversion.create_revision():
                    school_del.delete()
                    reversion.set_comment("Destruction")
chirac's avatar
chirac committed
400 401
                messages.success(request, "L'établissement a été supprimé")
            except ProtectedError:
402 403 404
                messages.error(
                    request,
                    "L'établissement %s est affecté à au moins un user, \
lhark's avatar
lhark committed
405
                        vous ne pouvez pas le supprimer" % school_del)
406
        return redirect("/users/index_school/")
chirac's avatar
chirac committed
407 408
    return form({'userform': school}, 'users/user.html', request)

409 410 411
@login_required
@permission_required('bureau')
def add_listright(request):
chirac's avatar
chirac committed
412 413
    """ Ajouter un droit/groupe, nécessite droit bureau.
    Obligation de fournir un gid pour la synchro ldap, unique """
414 415 416 417 418 419 420 421 422 423 424 425 426
    listright = NewListRightForm(request.POST or None)
    if listright.is_valid():
        with transaction.atomic(), reversion.create_revision():
            listright.save()
            reversion.set_user(request.user)
            reversion.set_comment("Création")
        messages.success(request, "Le droit/groupe a été ajouté")
        return redirect("/users/index_listright/")
    return form({'userform': listright}, 'users/user.html', request)

@login_required
@permission_required('bureau')
def edit_listright(request, listrightid):
chirac's avatar
chirac committed
427
    """ Editer un groupe/droit, necessite droit bureau, à partir du listright id """
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    try:
        listright_instance = ListRight.objects.get(pk=listrightid)
    except ListRight.DoesNotExist:
        messages.error(request, u"Entrée inexistante" )
        return redirect("/users/")
    listright = ListRightForm(request.POST or None, instance=listright_instance)
    if listright.is_valid():
        with transaction.atomic(), reversion.create_revision():
            listright.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in listright.changed_data))
        messages.success(request, "Droit modifié")
        return redirect("/users/index_listright/")
    return form({'userform': listright}, 'users/user.html', request)

@login_required
@permission_required('bureau')
def del_listright(request):
chirac's avatar
chirac committed
446
    """ Supprimer un ou plusieurs groupe, possible si il est vide, need droit bureau """
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    listright = DelListRightForm(request.POST or None)
    if listright.is_valid():
        listright_dels = listright.cleaned_data['listrights']
        for listright_del in listright_dels:
            try:
                with transaction.atomic(), reversion.create_revision():
                    listright_del.delete()
                    reversion.set_comment("Destruction")
                messages.success(request, "Le droit/groupe a été supprimé")
            except ProtectedError:
                messages.error(
                    request,
                    "L'établissement %s est affecté à au moins un user, \
                        vous ne pouvez pas le supprimer" % listright_del)
        return redirect("/users/index_listright/")
    return form({'userform': listright}, 'users/user.html', request)

464 465 466 467 468 469 470 471
@login_required
@permission_required('bureau')
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']
Gabriel Detraz's avatar
iTypoS  
Gabriel Detraz committed
472
        to_archive_list = [user for user in User.objects.exclude(state=User.STATE_ARCHIVE) if not user.end_access() or user.end_access() < date]
473 474 475
        if "valider" in request.POST:
            for user in to_archive_list:
                with transaction.atomic(), reversion.create_revision():
476
                    user.archive()
477
                    user.save()
478
                    reversion.set_user(request.user)
479 480 481 482 483
                    reversion.set_comment("Archivage")
            messages.success(request, "%s users ont été archivés" % len(to_archive_list))
            return redirect("/users/")        
    return form({'userform': to_archive_date, 'to_archive_list': to_archive_list}, 'users/mass_archive.html', request)

chirac's avatar
chirac committed
484
@login_required
485
@permission_required('cableur')
chirac's avatar
chirac committed
486
def index(request):
chirac's avatar
chirac committed
487
    """ Affiche l'ensemble des users, need droit cableur """
488 489
    options, created = GeneralOption.objects.get_or_create()
    pagination_number = options.pagination_number
490
    users_list = User.objects.select_related('room').order_by('state', 'name')
491
    paginator = Paginator(users_list, pagination_number)
492 493 494 495 496 497 498 499 500
    page = request.GET.get('page')
    try:
        users_list = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        users_list = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        users_list = paginator.page(paginator.num_pages)
501
    return render(request, 'users/index.html', {'users_list': users_list})
root's avatar
root committed
502

chirac's avatar
chirac committed
503
@login_required
chirac's avatar
chirac committed
504
@permission_required('cableur')
505
def index_ban(request):
chirac's avatar
chirac committed
506
    """ Affiche l'ensemble des ban, need droit cableur """
507 508
    options, created = GeneralOption.objects.get_or_create()
    pagination_number = options.pagination_number
Gabriel Detraz's avatar
Gabriel Detraz committed
509
    ban_list = Ban.objects.order_by('date_start').select_related('user').reverse()
510
    paginator = Paginator(ban_list, pagination_number)
511 512 513 514 515 516 517 518 519
    page = request.GET.get('page')
    try:
        ban_list = paginator.page(page)
    except PageNotAnInteger:
        # If page isn't an integer, deliver first page
        ban_list = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results. 
        ban_list = paginator.page(paginator.num_pages) 
520
    return render(request, 'users/index_ban.html', {'ban_list': ban_list})
521

chirac's avatar
chirac committed
522
@login_required
chirac's avatar
chirac committed
523
@permission_required('cableur')
524
def index_white(request):
chirac's avatar
chirac committed
525
    """ Affiche l'ensemble des whitelist, need droit cableur """
526 527
    options, created = GeneralOption.objects.get_or_create()
    pagination_number = options.pagination_number
Gabriel Detraz's avatar
Gabriel Detraz committed
528
    white_list = Whitelist.objects.select_related('user').order_by('date_start')
529 530 531 532 533 534 535 536 537 538
    paginator = Paginator(white_list, pagination_number)
    page = request.GET.get('page')
    try:
        white_list = paginator.page(page)
    except PageNotAnInteger:
        # If page isn't an integer, deliver first page
        white_list = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results. 
        white_list = paginator.page(paginator.num_pages) 
539 540 541 542 543 544
    return render(
        request,
        'users/index_whitelist.html',
        {'white_list': white_list}
    )

chirac's avatar
chirac committed
545
@login_required
chirac's avatar
chirac committed
546
@permission_required('cableur')
547
def index_school(request):
chirac's avatar
chirac committed
548
    """ Affiche l'ensemble des établissement, need droit cableur """
549 550 551
    school_list = School.objects.order_by('name')
    return render(request, 'users/index_schools.html', {'school_list':school_list})

552 553 554
@login_required
@permission_required('cableur')
def index_listright(request):
chirac's avatar
chirac committed
555
    """ Affiche l'ensemble des droits , need droit cableur """
556 557 558
    listright_list = ListRight.objects.order_by('listright')
    return render(request, 'users/index_listright.html', {'listright_list':listright_list})

559 560 561 562 563 564 565
@login_required
@permission_required('cableur')
def index_serviceusers(request):
    """ Affiche les users de services (pour les accès ldap)"""
    serviceusers_list = ServiceUser.objects.order_by('pseudo')
    return render(request, 'users/index_serviceusers.html', {'serviceusers_list':serviceusers_list})

566 567
@login_required
def history(request, object, id):
chirac's avatar
chirac committed
568 569 570 571 572 573
    """ Affichage de l'historique : (acl, argument)
    user : self or cableur, userid,
    ban : self or cableur, banid,
    whitelist : self or cableur, whitelistid,
    school : cableur, schoolid,
    listright : cableur, listrightid """
574 575 576 577 578 579 580 581 582
    if object == 'user':
        try:
             object_instance = User.objects.get(pk=id)
        except User.DoesNotExist:
             messages.error(request, "Utilisateur inexistant")
             return redirect("/users/")
        if not request.user.has_perms(('cableur',)) and object_instance != request.user:
             messages.error(request, "Vous ne pouvez pas afficher l'historique d'un autre user que vous sans droit cableur")
             return redirect("/users/profil/" + str(request.user.id))
583 584 585 586 587 588
    elif object == 'serviceuser' and request.user.has_perms(('cableur',)):
        try:
             object_instance = ServiceUser.objects.get(pk=id)
        except ServiceUser.DoesNotExist:
             messages.error(request, "User service inexistant")
             return redirect("/users/")
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    elif object == 'ban':
        try:
             object_instance = Ban.objects.get(pk=id)
        except Ban.DoesNotExist:
             messages.error(request, "Bannissement inexistant")
             return redirect("/users/")
        if not request.user.has_perms(('cableur',)) and object_instance.user != request.user:
             messages.error(request, "Vous ne pouvez pas afficher les bans d'un autre user que vous sans droit cableur")
             return redirect("/users/profil/" + str(request.user.id))
    elif object == 'whitelist':
        try:
             object_instance = Whitelist.objects.get(pk=id)
        except Whiltelist.DoesNotExist:
             messages.error(request, "Whitelist inexistant")
             return redirect("/users/")
        if not request.user.has_perms(('cableur',)) and object_instance.user != request.user:
             messages.error(request, "Vous ne pouvez pas afficher les whitelist d'un autre user que vous sans droit cableur")
             return redirect("/users/profil/" + str(request.user.id))
    elif object == 'school' and request.user.has_perms(('cableur',)):
        try:
             object_instance = School.objects.get(pk=id)
        except School.DoesNotExist:
             messages.error(request, "Ecole inexistante")
             return redirect("/users/")
613 614 615 616 617 618
    elif object == 'listright' and request.user.has_perms(('cableur',)):
        try:
             object_instance = ListRight.objects.get(pk=id)
        except ListRight.DoesNotExist:
             messages.error(request, "Droit inexistant")
             return redirect("/users/")
619 620 621
    else:
        messages.error(request, "Objet  inconnu")
        return redirect("/users/")
622 623
    options, created = GeneralOption.objects.get_or_create()
    pagination_number = options.pagination_number
root's avatar
root committed
624
    reversions = Version.objects.get_for_object(object_instance)
625
    paginator = Paginator(reversions, pagination_number)
chirac's avatar
chirac committed
626 627 628 629 630 631 632 633 634
    page = request.GET.get('page')
    try:
        reversions = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        reversions = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        reversions = paginator.page(paginator.num_pages)
635 636 637
    return render(request, 're2o/history.html', {'reversions': reversions, 'object': object_instance})


638 639
@login_required
def mon_profil(request):
chirac's avatar
chirac committed
640
    """ Lien vers profil, renvoie request.id à la fonction """
641 642
    return redirect("/users/profil/" + str(request.user.id))

chirac's avatar
chirac committed
643
@login_required
644
def profil(request, userid):
chirac's avatar
chirac committed
645
    """ Affiche un profil, self or cableur, prend un userid en argument """
646 647 648
    try:
        users = User.objects.get(pk=userid)
    except User.DoesNotExist:
649
        messages.error(request, "Utilisateur inexistant")
650
        return redirect("/users/")
651 652 653
    if not request.user.has_perms(('cableur',)) and users != request.user:
        messages.error(request, "Vous ne pouvez pas afficher un autre user que vous sans droit cableur")
        return redirect("/users/profil/" + str(request.user.id))
654
    machines = Machine.objects.filter(user__pseudo=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')
655 656 657
    factures = Facture.objects.filter(user__pseudo=users)
    bans = Ban.objects.filter(user__pseudo=users)
    whitelists = Whitelist.objects.filter(user__pseudo=users)
658
    list_droits = Right.objects.filter(user=users)
chibrac's avatar
chibrac committed
659 660
    options, created = OptionalUser.objects.get_or_create()
    user_solde = options.user_solde
661 662 663 664 665
    return render(
        request,
        'users/profil.html',
        {
            'user': users,
666
            'machines_list': machines,
667 668 669
            'facture_list': factures,
            'ban_list': bans,
            'white_list': whitelists,
chirac's avatar
chirac committed
670
            'list_droits': list_droits,
chibrac's avatar
chibrac committed
671
            'user_solde': user_solde,
lhark's avatar
lhark committed
672 673
        }
    )
root's avatar
root committed
674

chirac's avatar
chirac committed
675
def reset_password(request):
chirac's avatar
chirac committed
676
    """ Reintialisation du mot de passe si mdp oublié """
chirac's avatar
chirac committed
677 678 679 680 681 682
    userform = ResetPasswordForm(request.POST or None)
    if userform.is_valid():
        try:
            user = User.objects.get(pseudo=userform.cleaned_data['pseudo'],email=userform.cleaned_data['email'])
        except User.DoesNotExist:
            messages.error(request, "Cet utilisateur n'existe pas")
683 684
            return form({'userform': userform}, 'users/user.html', request)
        user.reset_passwd_mail(request)
chirac's avatar
chirac committed
685 686 687 688
        messages.success(request, "Un mail pour l'initialisation du mot de passe a été envoyé")
        redirect("/") 
    return form({'userform': userform}, 'users/user.html', request)

689 690 691 692 693 694 695 696 697
def process(request, token):
    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)
    elif req.type == Request.EMAIL:
        return process_email(request, req=req)
    else:
chirac's avatar
chirac committed
698 699
        messages.error(request, "Entrée incorrecte, contactez un admin")
        redirect("/")
700 701 702 703 704 705 706

def process_passwd(request, req):
    u_form = PassForm(request.POST or None)
    user = req.user
    if u_form.is_valid():
        return password_change_action(u_form, user, request, req=req)
    return form({'userform': u_form}, 'users/user.html', request)
707 708 709 710 711 712 713 714 715 716 717 718
""" Framework Rest """

class JSONResponse(HttpResponse):
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt
@login_required
@permission_required('serveur')
def mailing(request):
chirac's avatar
chirac committed
719 720
    """ Fonction de serialisation des addresses mail de tous les users
    Pour generation de ml all users"""
721
    mails = all_has_access().values('email').distinct()
722 723
    seria = MailSerializer(mails, many=True)
    return JSONResponse(seria.data)
724