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") raise ValidationError("Charge non positive")
if type_ope == Operation.WITHDRAW and amount >= 0: if type_ope == Operation.WITHDRAW and amount >= 0:
raise ValidationError("Retrait non négatif") raise ValidationError("Retrait non négatif")
self.cleaned_data['article'] = None
self.cleaned_data['article_nb'] = None
KPsulOperationFormSet = modelformset_factory( KPsulOperationFormSet = modelformset_factory(
Operation, 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 data['is_free'] = True
return data 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 # Surcharge Méthode save() avec gestions de User et CofProfile
# Args: # Args:
# - data : datas pour User et CofProfile # - data : datas pour User et CofProfile
@ -415,6 +422,9 @@ class GlobalPermissions(models.Model):
managed = False managed = False
permissions = ( permissions = (
('is_team', 'Is part of the team'), ('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): class Settings(models.Model):
@ -437,4 +447,5 @@ class Settings(models.Model):
return 0 return 0
class SettingsError(Exception): 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 import messages
from django.contrib.messages.views import SuccessMessageMixin from django.contrib.messages.views import SuccessMessageMixin
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 from django.contrib.auth.models import User, Permission
from django.http import HttpResponse, JsonResponse, Http404 from django.http import HttpResponse, JsonResponse, Http404
from django.forms import modelformset_factory from django.forms import modelformset_factory
from gestioncof.models import CofProfile, Clipper from gestioncof.models import CofProfile, Clipper
@ -398,7 +398,7 @@ def kpsul_perform_operations(request):
if not operation_formset.is_valid(): if not operation_formset.is_valid():
data['errors'].append({'operations': list(operation_formset.errors) }) data['errors'].append({'operations': list(operation_formset.errors) })
# Returning bad request if errors # Returning BAD REQUEST if errors
if 'errors' in data: if 'errors' in data:
return JsonResponse(data, status=400) return JsonResponse(data, status=400)
@ -410,14 +410,43 @@ def kpsul_perform_operations(request):
cof_grant = Settings.SUBVENTION_COF() cof_grant = Settings.SUBVENTION_COF()
cof_grant_divisor = 1 + cof_grant / 100 cof_grant_divisor = 1 + cof_grant / 100
# Calculating amount of each PURCHASE operations # Initializing required perms
# and total amount for operation group 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: for operation in operations:
# 1
if operation.type == Operation.PURCHASE: if operation.type == Operation.PURCHASE:
operation.amount = - operation.article.price * operation.article_nb operation.amount = - operation.article.price * operation.article_nb
if operationgroup.on_acc.is_cof: if operationgroup.on_acc.is_cof:
operation.amount = operation.amount / cof_grant_divisor operation.amount = operation.amount / cof_grant_divisor
# 2
operationgroup.amount += operation.amount 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 # Filling cof status for statistics
operationgroup.is_cof = operationgroup.on_acc.is_cof operationgroup.is_cof = operationgroup.on_acc.is_cof