Merge branch 'Aufinal/own_password' into 'k-fet'

Changement de son propre mot de passe

Permet à un K-Fêteux (disposant de la permission `kfet.is_team`) de modifier son propre mot de passe sur la page `account/XXX/edit`.

Accessoirement, la fonction `account_update` est maintenant conforme à PEP8.

Fix #121

See merge request !148
This commit is contained in:
Aurélien Delobelle 2017-02-13 16:32:40 +01:00
commit 2e8fc45a1b
2 changed files with 86 additions and 48 deletions

View file

@ -18,6 +18,7 @@ from django.db.models import F
from django.core.cache import cache
from datetime import date, timedelta
import re
import hashlib
def choices_length(choices):
return reduce(lambda m, choice: max(m, len(choice[0])), choices, 0)
@ -154,6 +155,7 @@ class Account(models.Model):
# - Enregistre User, CofProfile à partir de "data"
# - Enregistre Account
def save(self, data = {}, *args, **kwargs):
if self.pk and data:
# Account update
@ -200,6 +202,11 @@ class Account(models.Model):
self.cofprofile = cof
super(Account, self).save(*args, **kwargs)
def change_pwd(self, pwd):
pwd_sha256 = hashlib.sha256(pwd.encode('utf-8'))\
.hexdigest()
self.password = pwd_sha256
# Surcharge de delete
# Pas de suppression possible
# Cas à régler plus tard

View file

@ -1,45 +1,55 @@
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from django.shortcuts import render, get_object_or_404, redirect
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.exceptions import PermissionDenied
from django.core.cache import cache
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView, FormView
from django.views.generic.edit import CreateView, UpdateView
from django.core.urlresolvers import reverse_lazy
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User, Permission, Group
from django.http import HttpResponse, JsonResponse, Http404
from django.forms import modelformset_factory, formset_factory
from django.db import IntegrityError, transaction
from django.db.models import F, Sum, Prefetch, Count, Func
from django.http import JsonResponse, Http404
from django.forms import formset_factory
from django.db import transaction
from django.db.models import F, Sum, Prefetch, Count
from django.db.models.functions import Coalesce
from django.utils import timezone
from django.utils.crypto import get_random_string
from gestioncof.models import CofProfile, Clipper
from kfet.decorators import teamkfet_required
from kfet.models import (Account, Checkout, Article, Settings, AccountNegative,
from kfet.models import (
Account, Checkout, Article, Settings, AccountNegative,
CheckoutStatement, GenericTeamToken, Supplier, SupplierArticle, Inventory,
InventoryArticle, Order, OrderArticle)
from kfet.forms import *
InventoryArticle, Order, OrderArticle, Operation, OperationGroup,
TransferGroup, Transfer)
from kfet.forms import (
AccountTriForm, AccountBalanceForm, AccountNoTriForm, UserForm, CofForm,
UserRestrictTeamForm, UserGroupForm, AccountForm, CofRestrictForm,
AccountPwdForm, AccountNegativeForm, UserRestrictForm, AccountRestrictForm,
GroupForm, CheckoutForm, CheckoutRestrictForm, CheckoutStatementCreateForm,
CheckoutStatementUpdateForm, ArticleForm, ArticleRestrictForm,
KPsulOperationGroupForm, KPsulAccountForm, KPsulCheckoutForm,
KPsulOperationFormSet, AddcostForm, FilterHistoryForm, SettingsForm,
TransferFormSet, InventoryArticleForm, OrderArticleForm,
OrderArticleToInventoryForm
)
from collections import defaultdict
from kfet import consumers
from datetime import timedelta
from decimal import Decimal
import django_cas_ng
import hashlib
import heapq
import statistics
@login_required
def home(request):
return render(request, "kfet/base.html")
@teamkfet_required
def login_genericteam(request):
# Check si besoin de déconnecter l'utilisateur de CAS
@ -345,6 +355,7 @@ def account_read(request, trigramme):
# Account - Update
@login_required
def account_update(request, trigramme):
account = get_object_or_404(Account, trigramme=trigramme)
@ -355,39 +366,43 @@ def account_update(request, trigramme):
raise PermissionDenied
if request.user.has_perm('kfet.is_team'):
user_form = UserRestrictTeamForm(instance=account.user)
group_form = UserGroupForm(instance=account.user)
user_form = UserRestrictTeamForm(instance=account.user)
group_form = UserGroupForm(instance=account.user)
account_form = AccountForm(instance=account)
cof_form = CofRestrictForm(instance=account.cofprofile)
pwd_form = AccountPwdForm()
cof_form = CofRestrictForm(instance=account.cofprofile)
pwd_form = AccountPwdForm()
if account.balance < 0 and not hasattr(account, 'negative'):
AccountNegative.objects.create(account=account, start=timezone.now())
AccountNegative.objects.create(account=account,
start=timezone.now())
account.refresh_from_db()
if hasattr(account, 'negative'):
negative_form = AccountNegativeForm(instance=account.negative)
else:
negative_form = None
else:
user_form = UserRestrictForm(instance=account.user)
user_form = UserRestrictForm(instance=account.user)
account_form = AccountRestrictForm(instance=account)
cof_form = None
group_form = None
cof_form = None
group_form = None
negative_form = None
pwd_form = None
pwd_form = None
if request.method == "POST":
# Update attempt
success = False
success = False
missing_perm = True
if request.user.has_perm('kfet.is_team'):
account_form = AccountForm(request.POST, instance=account)
cof_form = CofRestrictForm(request.POST, instance=account.cofprofile)
user_form = UserRestrictTeamForm(request.POST, instance=account.user)
group_form = UserGroupForm(request.POST, instance=account.user)
pwd_form = AccountPwdForm(request.POST)
cof_form = CofRestrictForm(request.POST,
instance=account.cofprofile)
user_form = UserRestrictTeamForm(request.POST,
instance=account.user)
group_form = UserGroupForm(request.POST, instance=account.user)
pwd_form = AccountPwdForm(request.POST)
if hasattr(account, 'negative'):
negative_form = AccountNegativeForm(request.POST, instance=account.negative)
negative_form = AccountNegativeForm(request.POST,
instance=account.negative)
if (request.user.has_perm('kfet.change_account')
and account_form.is_valid() and cof_form.is_valid()
@ -399,15 +414,14 @@ def account_update(request, trigramme):
put_cleaned_data_in_dict(data, cof_form)
# Updating
account_form.save(data = data)
account_form.save(data=data)
# Checking perm to update password
if (request.user.has_perm('kfet.change_account_password')
and pwd_form.is_valid()):
pwd = pwd_form.cleaned_data['pwd1']
pwd_sha256 = hashlib.sha256(pwd.encode('utf-8')).hexdigest()
Account.objects.filter(pk=account.pk).update(
password = pwd_sha256)
account.change_pwd(pwd)
account.save()
messages.success(request, 'Mot de passe mis à jour')
# Checking perm to manage perms
@ -421,49 +435,66 @@ def account_update(request, trigramme):
if account.negative.balance_offset:
balance_offset_old = account.negative.balance_offset
if (hasattr(account, 'negative')
and request.user.has_perm('kfet.change_accountnegative')
and request.user.has_perm('kfet.change_accountnegative')
and negative_form.is_valid()):
balance_offset_new = negative_form.cleaned_data['balance_offset']
balance_offset_new = \
negative_form.cleaned_data['balance_offset']
if not balance_offset_new:
balance_offset_new = 0
balance_offset_diff = balance_offset_new - balance_offset_old
balance_offset_diff = (balance_offset_new
- balance_offset_old)
Account.objects.filter(pk=account.pk).update(
balance = F('balance') + balance_offset_diff)
balance=F('balance') + balance_offset_diff)
negative_form.save()
if not balance_offset_new and Account.objects.get(pk=account.pk).balance >= 0:
if Account.objects.get(pk=account.pk).balance >= 0 \
and not balance_offset_new:
AccountNegative.objects.get(account=account).delete()
success = True
messages.success(request,
'Informations du compte %s mises à jour' % account.trigramme)
messages.success(
request,
'Informations du compte %s mises à jour'
% account.trigramme)
# Modification de ses propres informations
if request.user == account.user:
missing_perm = False
account.refresh_from_db()
user_form = UserRestrictForm(request.POST, instance=account.user)
account_form = AccountRestrictForm(request.POST, instance=account)
pwd_form = AccountPwdForm(request.POST)
if user_form.is_valid() and account_form.is_valid():
user_form.save()
account_form.save()
success = True
messages.success(request, 'Vos informations ont été mises à jour')
messages.success(request,
'Vos informations ont été mises à jour')
if request.user.has_perm('kfet.is_team') \
and pwd_form.is_valid():
pwd = pwd_form.cleaned_data['pwd1']
account.change_pwd(pwd)
account.save()
messages.success(
request, 'Votre mot de passe a été mis à jour')
if missing_perm:
messages.error(request, 'Permission refusée')
if success:
return redirect('kfet.account.read', account.trigramme)
else:
messages.error(request, 'Informations non mises à jour. Corrigez les erreurs')
messages.error(
request, 'Informations non mises à jour. Corrigez les erreurs')
return render(request, "kfet/account_update.html", {
'account' : account,
'account_form' : account_form,
'cof_form' : cof_form,
'user_form' : user_form,
'group_form' : group_form,
'account': account,
'account_form': account_form,
'cof_form': cof_form,
'user_form': user_form,
'group_form': group_form,
'negative_form': negative_form,
'pwd_form' : pwd_form,
'pwd_form': pwd_form,
})
@permission_required('kfet.manage_perms')