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 django.core.cache import cache
from datetime import date, timedelta from datetime import date, timedelta
import re import re
import hashlib
def choices_length(choices): def choices_length(choices):
return reduce(lambda m, choice: max(m, len(choice[0])), choices, 0) 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 User, CofProfile à partir de "data"
# - Enregistre Account # - Enregistre Account
def save(self, data = {}, *args, **kwargs): def save(self, data = {}, *args, **kwargs):
if self.pk and data: if self.pk and data:
# Account update # Account update
@ -200,6 +202,11 @@ class Account(models.Model):
self.cofprofile = cof self.cofprofile = cof
super(Account, self).save(*args, **kwargs) 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 # Surcharge de delete
# Pas de suppression possible # Pas de suppression possible
# Cas à régler plus tard # Cas à régler plus tard

View file

@ -1,45 +1,55 @@
# -*- coding: utf-8 -*- # -*- 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.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.core.cache import cache
from django.views.generic import ListView, DetailView 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.core.urlresolvers import reverse_lazy
from django.contrib import messages from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth import authenticate, login from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User, Permission, Group from django.contrib.auth.models import User, Permission, Group
from django.http import HttpResponse, JsonResponse, Http404 from django.http import JsonResponse, Http404
from django.forms import modelformset_factory, formset_factory from django.forms import formset_factory
from django.db import IntegrityError, transaction from django.db import transaction
from django.db.models import F, Sum, Prefetch, Count, Func from django.db.models import F, Sum, Prefetch, Count
from django.db.models.functions import Coalesce from django.db.models.functions import Coalesce
from django.utils import timezone from django.utils import timezone
from django.utils.crypto import get_random_string from django.utils.crypto import get_random_string
from gestioncof.models import CofProfile, Clipper from gestioncof.models import CofProfile, Clipper
from kfet.decorators import teamkfet_required 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, CheckoutStatement, GenericTeamToken, Supplier, SupplierArticle, Inventory,
InventoryArticle, Order, OrderArticle) InventoryArticle, Order, OrderArticle, Operation, OperationGroup,
from kfet.forms import * 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 collections import defaultdict
from kfet import consumers from kfet import consumers
from datetime import timedelta from datetime import timedelta
from decimal import Decimal
import django_cas_ng import django_cas_ng
import hashlib
import heapq import heapq
import statistics import statistics
@login_required @login_required
def home(request): def home(request):
return render(request, "kfet/base.html") return render(request, "kfet/base.html")
@teamkfet_required @teamkfet_required
def login_genericteam(request): def login_genericteam(request):
# Check si besoin de déconnecter l'utilisateur de CAS # Check si besoin de déconnecter l'utilisateur de CAS
@ -345,6 +355,7 @@ def account_read(request, trigramme):
# Account - Update # Account - Update
@login_required @login_required
def account_update(request, trigramme): def account_update(request, trigramme):
account = get_object_or_404(Account, trigramme=trigramme) account = get_object_or_404(Account, trigramme=trigramme)
@ -361,7 +372,8 @@ def account_update(request, trigramme):
cof_form = CofRestrictForm(instance=account.cofprofile) cof_form = CofRestrictForm(instance=account.cofprofile)
pwd_form = AccountPwdForm() pwd_form = AccountPwdForm()
if account.balance < 0 and not hasattr(account, 'negative'): 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() account.refresh_from_db()
if hasattr(account, 'negative'): if hasattr(account, 'negative'):
negative_form = AccountNegativeForm(instance=account.negative) negative_form = AccountNegativeForm(instance=account.negative)
@ -382,12 +394,15 @@ def account_update(request, trigramme):
if request.user.has_perm('kfet.is_team'): if request.user.has_perm('kfet.is_team'):
account_form = AccountForm(request.POST, instance=account) account_form = AccountForm(request.POST, instance=account)
cof_form = CofRestrictForm(request.POST, instance=account.cofprofile) cof_form = CofRestrictForm(request.POST,
user_form = UserRestrictTeamForm(request.POST, instance=account.user) instance=account.cofprofile)
user_form = UserRestrictTeamForm(request.POST,
instance=account.user)
group_form = UserGroupForm(request.POST, instance=account.user) group_form = UserGroupForm(request.POST, instance=account.user)
pwd_form = AccountPwdForm(request.POST) pwd_form = AccountPwdForm(request.POST)
if hasattr(account, 'negative'): 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') if (request.user.has_perm('kfet.change_account')
and account_form.is_valid() and cof_form.is_valid() 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) put_cleaned_data_in_dict(data, cof_form)
# Updating # Updating
account_form.save(data = data) account_form.save(data=data)
# Checking perm to update password # Checking perm to update password
if (request.user.has_perm('kfet.change_account_password') if (request.user.has_perm('kfet.change_account_password')
and pwd_form.is_valid()): and pwd_form.is_valid()):
pwd = pwd_form.cleaned_data['pwd1'] pwd = pwd_form.cleaned_data['pwd1']
pwd_sha256 = hashlib.sha256(pwd.encode('utf-8')).hexdigest() account.change_pwd(pwd)
Account.objects.filter(pk=account.pk).update( account.save()
password = pwd_sha256)
messages.success(request, 'Mot de passe mis à jour') messages.success(request, 'Mot de passe mis à jour')
# Checking perm to manage perms # Checking perm to manage perms
@ -423,47 +437,64 @@ def account_update(request, trigramme):
if (hasattr(account, 'negative') 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()): 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: if not balance_offset_new:
balance_offset_new = 0 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( Account.objects.filter(pk=account.pk).update(
balance = F('balance') + balance_offset_diff) balance=F('balance') + balance_offset_diff)
negative_form.save() 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() AccountNegative.objects.get(account=account).delete()
success = True success = True
messages.success(request, messages.success(
'Informations du compte %s mises à jour' % account.trigramme) request,
'Informations du compte %s mises à jour'
% account.trigramme)
# Modification de ses propres informations
if request.user == account.user: if request.user == account.user:
missing_perm = False missing_perm = False
account.refresh_from_db() account.refresh_from_db()
user_form = UserRestrictForm(request.POST, instance=account.user) user_form = UserRestrictForm(request.POST, instance=account.user)
account_form = AccountRestrictForm(request.POST, instance=account) account_form = AccountRestrictForm(request.POST, instance=account)
pwd_form = AccountPwdForm(request.POST)
if user_form.is_valid() and account_form.is_valid(): if user_form.is_valid() and account_form.is_valid():
user_form.save() user_form.save()
account_form.save() account_form.save()
success = True 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: if missing_perm:
messages.error(request, 'Permission refusée') messages.error(request, 'Permission refusée')
if success: if success:
return redirect('kfet.account.read', account.trigramme) return redirect('kfet.account.read', account.trigramme)
else: 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", { return render(request, "kfet/account_update.html", {
'account' : account, 'account': account,
'account_form' : account_form, 'account_form': account_form,
'cof_form' : cof_form, 'cof_form': cof_form,
'user_form' : user_form, 'user_form': user_form,
'group_form' : group_form, 'group_form': group_form,
'negative_form': negative_form, 'negative_form': negative_form,
'pwd_form' : pwd_form, 'pwd_form': pwd_form,
}) })
@permission_required('kfet.manage_perms') @permission_required('kfet.manage_perms')