views.py 14.8 KB
Newer Older
Gabriel Detraz's avatar
Gabriel Detraz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# App de gestion des users pour Amap
# Goulven Kermarec, Gabriel Détraz
# Gplv2
from django.shortcuts import render_to_response, get_object_or_404, render, redirect
from django.core.context_processors import csrf
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.template import Context, RequestContext, loader
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.db.models import Max, ProtectedError
from django.db import IntegrityError
from django.core.mail import send_mail
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.db import transaction

from reversion import revisions as reversion
from users.models import User, Right, ListRight, Request
from users.models import DelRightForm, DelListRightForm, NewListRightForm
from users.models import EditInfoForm, BaseInfoForm, StateForm, RightForm, ListRightForm
from users.forms import PassForm, ResetPasswordForm

23
from panier.models import Commande, Credit
24

Gabriel Detraz's avatar
Gabriel Detraz committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
from amap.settings import REQ_EXPIRE_STR, EMAIL_FROM, ASSO_NAME, ASSO_EMAIL, SITE_NAME, PAGINATION_NUMBER


def form(ctx, template, request):
    c = ctx
    c.update(csrf(request))
    return render_to_response(
        template,
        c,
        context_instance=RequestContext(request)
    )

def password_change_action(u_form, user, request, req=False):
    """ Fonction qui effectue le changeemnt de mdp bdd"""
    if u_form.cleaned_data['passwd1'] != u_form.cleaned_data['passwd2']:
        messages.error(request, "Les 2 mots de passe différent")
        return form({'userform': u_form}, 'users/user.html', request)
    user.set_password(u_form.cleaned_data['passwd1'])
    with transaction.atomic(), reversion.create_revision():
        user.save()
        reversion.set_comment("Réinitialisation du mot de passe")
    messages.success(request, "Le mot de passe a changé")
    if req:
        req.delete()
        return redirect("/")
    return redirect("/users/profil/" + str(user.id))

def reset_passwd_mail(req, request):
    t = loader.get_template('users/email_passwd_request')
    c = Context({
      'name': str(req.user.name) + ' ' + str(req.user.surname),
      'asso': ASSO_NAME,
      'asso_mail': ASSO_EMAIL,
      'site_name': SITE_NAME,
      'url': request.build_absolute_uri(
       reverse('users:process', kwargs={'token': req.token})),
       'expire_in': REQ_EXPIRE_STR,
    })
    send_mail('Changement de mot de passe', t.render(c),
    EMAIL_FROM, [req.user.email], fail_silently=False)
    return

@login_required
@permission_required('bureau')
def new_user(request):
    user = EditInfoForm(request.POST or None)
    if user.is_valid():
        user = user.save(commit=False)
        with transaction.atomic(), reversion.create_revision():
            user.save()
            reversion.set_user(request.user)
            reversion.set_comment("Création")
        req = Request()
        req.type = Request.PASSWD
        req.user = user
        req.save()
        reset_passwd_mail(req, request)
        messages.success(request, "L'utilisateur %s a été crée, un mail pour l'initialisation du mot de passe a été envoyé" % user.pseudo)
        return redirect("/users/profil/" + str(user.id))
    return form({'userform': user}, 'users/user.html', request)

@login_required
def edit_info(request, userid):
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, "Utilisateur inexistant")
        return redirect("/users/")
    if not request.user.has_perms(('bureau',)) and user != request.user:
        messages.error(request, "Vous ne pouvez pas modifier un autre user que vous sans droit bureau")
        return redirect("/users/profil/" + str(request.user.id))
    if not request.user.has_perms(('bureau',)):
        user = BaseInfoForm(request.POST or None, instance=user)
    else:
        user = EditInfoForm(request.POST or None, instance=user)
    if user.is_valid():
        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))
        messages.success(request, "L'user a bien été modifié")
        return redirect("/users/profil/" + userid)
    return form({'userform': user}, 'users/user.html', request)

@login_required
@permission_required('bureau')
def state(request, userid):
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, "Utilisateur inexistant")
        return redirect("/users/")
    state = StateForm(request.POST or None, instance=user)
    if state.is_valid():
        with transaction.atomic(), reversion.create_revision():
            state.save()
            reversion.set_user(request.user)
            reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in state.changed_data))
        messages.success(request, "Etat changé avec succès")
        return redirect("/users/profil/" + userid)
    return form({'userform': state}, 'users/user.html', request)

@login_required
def password(request, userid):
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, "Utilisateur inexistant")
        return redirect("/users/")
    if not request.user.has_perms(('bureau',)) and user != request.user:
        messages.error(request, "Vous ne pouvez pas modifier un autre user que vous sans droit bureau")
        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):
        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))
    u_form = PassForm(request.POST or None)
    if u_form.is_valid():
        return password_change_action(u_form, user, request)
    return form({'userform': u_form}, 'users/user.html', request)

@login_required
@permission_required('bureau')
def del_right(request):
    user_right_list = DelRightForm(request.POST or None)
    if user_right_list.is_valid():
        right_del = user_right_list.cleaned_data['rights']
        right_del.delete()
        messages.success(request, "Droit retiré avec succès")
        return redirect("/users/")
    return form({'userform': user_right_list}, 'users/user.html', request)

@login_required
@permission_required('bureau')
def add_right(request, userid):
    try:
        user = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, "Utilisateur inexistant")
        return redirect("/users/")
    right = RightForm(request.POST or None)
    if right.is_valid():
        right = right.save(commit=False)
        right.user = user
        try:
            right.save()
            messages.success(request, "Droit ajouté")
        except IntegrityError:
            pass
        return redirect("/users/profil/" + userid)
    return form({'userform': right}, 'users/user.html', request)

@login_required
@permission_required('bureau')
def add_listright(request):
    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):
    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):
    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,
                    "Le droit %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)

@login_required
@permission_required('bureau')
def index(request):
    users_list = User.objects.order_by('pk')
    paginator = Paginator(users_list, PAGINATION_NUMBER)
    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)
    return render(request, 'users/index.html', {'users_list': users_list})

@login_required
@permission_required('bureau')
def index_listright(request):
    listright_list = ListRight.objects.order_by('listright')
    return render(request, 'users/index_listright.html', {'listright_list':listright_list})

@login_required
def history(request, object, id):
    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(('bureau',)) and object_instance != request.user:
             messages.error(request, "Vous ne pouvez pas afficher l'historique d'un autre user que vous sans droit bureau")
             return redirect("/users/profil/" + str(request.user.id))
    elif object == 'listright' and request.user.has_perms(('bureau',)):
        try:
             object_instance = ListRight.objects.get(pk=id)
        except ListRight.DoesNotExist:
             messages.error(request, "Droit inexistant")
             return redirect("/users/")
    else:
        messages.error(request, "Objet  inconnu")
        return redirect("/users/")
    reversions = reversion.get_for_object(object_instance)
    paginator = Paginator(reversions, PAGINATION_NUMBER)
    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)
    return render(request, 'amap/history.html', {'reversions': reversions, 'object': object_instance})


@login_required
def mon_profil(request):
    return redirect("/users/profil/" + str(request.user.id))

@login_required
def profil(request, userid):
    try:
        users = User.objects.get(pk=userid)
    except User.DoesNotExist:
        messages.error(request, "Utilisateur inexistant")
        return redirect("/users/")
    if not request.user.has_perms(('bureau',)) and users != request.user:
        messages.error(request, "Vous ne pouvez pas afficher un autre user que vous sans droit bureau")
        return redirect("/users/profil/" + str(request.user.id))
    list_droits = Right.objects.filter(user=users)
298 299
    paniers_list = Commande.objects.filter(user=users).order_by('pk')
    credit_list = Credit.objects.filter(user=users).order_by('pk')
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    paginator_paniers = Paginator(paniers_list, PAGINATION_NUMBER)
    paginator_credit = Paginator(credit_list, PAGINATION_NUMBER)
    page = request.GET.get('page')
    try:
        paniers_list = paginator_paniers.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        paniers_list = paginator_paniers.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        paniers_list = paginator_paniers.page(paginator_paniers.num_pages)
    try:
        credit_list = paginator_credit.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        credit_list = paginator_credit.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        credit_list = paginator_credit.page(paginator_credit.num_pages)

Gabriel Detraz's avatar
Gabriel Detraz committed
320 321 322 323 324 325
    return render(
        request,
        'users/profil.html',
        {
            'user': users,
            'list_droits': list_droits,
326 327
            'credit_list': credit_list,
            'paniers_list': paniers_list,
Gabriel Detraz's avatar
Gabriel Detraz committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
        }
    )

def reset_password(request):
    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")
            return form({'userform': userform}, 'users/user.html', request)   
        req = Request()
        req.type = Request.PASSWD
        req.user = user
        req.save()
        reset_passwd_mail(req, request)
        messages.success(request, "Un mail pour l'initialisation du mot de passe a été envoyé")
        redirect("/") 
    return form({'userform': userform}, 'users/user.html', request)

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:
        messages.error(request, "Entrée incorrecte, contactez un admin")
        redirect("/")

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)