Gestion des permissions dans K-Psul

- Ajout d'une méthode sur Account pour connaître les permissions
  nécessaires pour enregistrer des opérations en fonction du futur solde
  du compte
- Ajout d'une permission pour effectuer une charge sur un compte
- Ajoute que l'utilisateur connecté doit avoir toutes les permissions
  nécessaires pour enregistrer un groupe d'opérations. Si ce n'est pas
le cas, aucune opération n'est enregistrée et les permissions manquantes
sont envoyées en réponse.
- Dans le cas d'une charge ou d'un retrait, "article" et "article_nb" de
  Operation sont définis à NULL
This commit is contained in:
Aurélien Delobelle 2016-08-07 23:41:46 +02:00
parent 515a7ce28e
commit 4cb89aa005
5 changed files with 87 additions and 9 deletions

View file

@ -163,6 +163,8 @@ class KPsulOperationForm(forms.ModelForm):
raise ValidationError("Charge non positive")
if type_ope == Operation.WITHDRAW and amount >= 0:
raise ValidationError("Retrait non négatif")
self.cleaned_data['article'] = None
self.cleaned_data['article_nb'] = None
KPsulOperationFormSet = modelformset_factory(
Operation,

View file

@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('kfet', '0013_auto_20160807_1840'),
]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'permissions': (('is_team', 'Is part of the team'), ('can_perform_deposit', 'Peut effectuer une charge')), 'managed': False},
),
]

View file

@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('kfet', '0014_auto_20160807_2314'),
]
operations = [
migrations.AlterModelOptions(
name='globalpermissions',
options={'permissions': (('is_team', 'Is part of the team'), ('can_perform_deposit', 'Peut effectuer une charge'), ('can_perform_negative_operations', 'Peut enregistrer des commandes en négatif')), 'managed': False},
),
]

View file

@ -93,6 +93,13 @@ class Account(models.Model):
data['is_free'] = True
return data
def perms_to_perform_operation(self, amount):
new_balance = self.balance + amount
perms = []
if new_balance < 0:
perms.append('kfet.can_perform_negative_operations')
return perms
# Surcharge Méthode save() avec gestions de User et CofProfile
# Args:
# - data : datas pour User et CofProfile
@ -415,6 +422,9 @@ class GlobalPermissions(models.Model):
managed = False
permissions = (
('is_team', 'Is part of the team'),
('can_perform_deposit', 'Peut effectuer une charge'),
('can_perform_negative_operations',
'Peut enregistrer des commandes en négatif')
)
class Settings(models.Model):
@ -437,4 +447,5 @@ class Settings(models.Model):
return 0
class SettingsError(Exception):
pass
def __init__(self, msg):
self.msg = msg

View file

@ -6,7 +6,7 @@ from django.core.urlresolvers import reverse_lazy
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from django.contrib.auth.models import User, Permission
from django.http import HttpResponse, JsonResponse, Http404
from django.forms import modelformset_factory
from gestioncof.models import CofProfile, Clipper
@ -398,7 +398,7 @@ def kpsul_perform_operations(request):
if not operation_formset.is_valid():
data['errors'].append({'operations': list(operation_formset.errors) })
# Returning bad request if errors
# Returning BAD REQUEST if errors
if 'errors' in data:
return JsonResponse(data, status=400)
@ -410,14 +410,43 @@ def kpsul_perform_operations(request):
cof_grant = Settings.SUBVENTION_COF()
cof_grant_divisor = 1 + cof_grant / 100
# Calculating amount of each PURCHASE operations
# and total amount for operation group
# Initializing required perms
required_perms = []
# 1. Calculating amount of each PURCHASE operations
# 2. and total amount for operation group
# 3. Adding required permissions to perform each operation
for operation in operations:
# 1
if operation.type == Operation.PURCHASE:
operation.amount = - operation.article.price * operation.article_nb
if operationgroup.on_acc.is_cof:
operation.amount = operation.amount / cof_grant_divisor
# 2
operationgroup.amount += operation.amount
# 3
if operation.type == Operation.DEPOSIT:
required_perms.append('kfet.can_perform_deposit')
# Adding required permissions to perform operation group
opegroup_perms = operationgroup.on_acc.perms_to_perform_operation(
amount = operationgroup.amount)
required_perms += opegroup_perms
# Checking authenticated user has all perms
if not request.user.has_perms(required_perms):
# Sending BAD_REQUEST with missing perms
missing_perms = \
[ Permission.objects.get(codename=codename).name for codename in (
(perm.split('.'))[1] for perm in
required_perms if not request.user.has_perm(perm)
)]
data['errors'].append({'missing_perms': missing_perms })
return JsonResponse(data, status=400)
# If 1 perm is required, saving who perform the operations
operationgroup.valid_by = request.user.profile.account_kfet
# Filling cof status for statistics
operationgroup.is_cof = operationgroup.on_acc.is_cof