Added permission app

This commit is contained in:
Benjamin Graillot 2019-09-18 14:26:42 +02:00
parent 2a2e78f83f
commit 67d1d9f7b7
9 changed files with 182 additions and 0 deletions

33
apps/member/backends.py Normal file
View File

@ -0,0 +1,33 @@
from django.contribs.contenttype.models import ContentType
from member.models import Club, Membership, RolePermissions
class PermissionBackend(object):
supports_object_permissions = True
supports_anonymous_user = False
supports_inactive_user = False
def authenticate(self, username, password):
return None
def permissions(self, user, obj):
for membership in user.memberships.all():
if not membership.valid() or membership.role is None:
continue
for permission in RolePermissions.objects.get(role=membership.role).permissions.objects.all():
permission = permission.about(user=user, club=membership.club)
yield permission
def has_perm(self, user_obj, perm, obj=None):
if obj is None:
return False
perm = perm.split('_')
perm_type = perm[1]
perm_field = perm[2] if len(perm) == 3 else None
return any(permission.applies(obj, perm_type, perm_field) for obj in self.permissions(user_obj, obj))
def get_all_permissions(self, user_obj, obj=None):
if obj is None:
return []
else:
return list(self.permissions(user_obj, obj))

View File

@ -2,6 +2,8 @@
# Copyright (C) 2018-2019 by BDE ENS Paris-Saclay # Copyright (C) 2018-2019 by BDE ENS Paris-Saclay
# SPDX-License-Identifier: GPL-3.0-or-later # SPDX-License-Identifier: GPL-3.0-or-later
import datetime
from django.conf import settings from django.conf import settings
from django.db import models from django.db import models
from django.db.models.signals import post_save from django.db.models.signals import post_save
@ -9,6 +11,7 @@ from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.urls import reverse from django.urls import reverse
class Profile(models.Model): class Profile(models.Model):
""" """
An user profile An user profile
@ -51,6 +54,7 @@ class Profile(models.Model):
def get_absolute_url(self): def get_absolute_url(self):
return reverse('user_detail',args=(self.pk,)) return reverse('user_detail',args=(self.pk,))
class Club(models.Model): class Club(models.Model):
""" """
A student club A student club
@ -141,11 +145,29 @@ class Membership(models.Model):
verbose_name=_('fee'), verbose_name=_('fee'),
) )
def valid(self):
return self.date_start <= datetime.datetime.now() < self.date_end
class Meta: class Meta:
verbose_name = _('membership') verbose_name = _('membership')
verbose_name_plural = _('memberships') verbose_name_plural = _('memberships')
class RolePermissions(models.Model):
"""
Permissions associated with a Role
"""
role = models.ForeignKey(
Role,
on_delete=models.PROTECT,
related_name='+',
verbose_name=_('role'),
)
permissions = models.ManyToManyField(
'permission.Permission'
)
# @receiver(post_save, sender=settings.AUTH_USER_MODEL) # @receiver(post_save, sender=settings.AUTH_USER_MODEL)
# def save_user_profile(instance, created, **_kwargs): # def save_user_profile(instance, created, **_kwargs):
# """ # """

View File

3
apps/permission/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

5
apps/permission/apps.py Normal file
View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class PermissionConfig(AppConfig):
name = 'permission'

112
apps/permission/models.py Normal file
View File

@ -0,0 +1,112 @@
import json
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
class InstancedPermission:
def __init__(self, model, permission, type, field):
self.model = model
self.permission = permission
self.type = type
self.field = field
def applies(self, obj, permission_type, field_name=None):
if ContentType.objects.get_for_model(obj) != self.model:
# The permission does not apply to the object
return False
if self.permission is None:
if permission_type == self.type:
if field_name is not None:
return field_name == self.field
else:
return True
else:
return False
elif isinstance(self.permission, dict):
for field in self.permission:
value = getattr(obj, field)
if isinstance(value, models.Model):
value = value.pk
if value != self.permission[field]:
return False
elif isinstance(self.permission, type(obj.pk)):
if obj.pk != self.permission:
return False
if permission_type == self.type:
if field_name:
return field_name == self.field
else:
return True
return False
def __repr__(self):
if self.field:
return _("Can {type} {model}.{field} in {permission}").format(type=self.type, model=self.model, field=self.field, permission=self.permission)
else:
return _("Can {type} {model} in {permission}").format(type=self.type, model=self.model, permission=self.permission)
class Permission(models.Model):
PERMISSION_TYPES = [
('C', 'add'),
('R', 'view'),
('U', 'change'),
('D', 'delete')
]
model = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='+')
permission = models.TextField()
type = models.CharField(max_length=15, choices=PERMISSION_TYPES)
field = models.CharField(max_length=255, blank=True)
class Meta:
unique_together = ('model', 'permission', 'type', 'field')
def clean(self):
if self.field and self.type not in {'R', 'U'}:
raise ValidationError(_("Specifying field applies only to view and change permission types."))
def save(self):
self.full_clean()
super().save()
def _about(_self, _permission, **kwargs):
if _permission[0] == 'all':
return None
elif _permission[0] == 'pk':
if _permission[1] in kwargs:
return kwargs[_permission[1]].pk
else:
return None
elif _permission[0] == 'filter':
return {field: _self._about(_permission[1][field], **kwargs) for field in _permission[1]}
else:
return _permission
def about(self, **kwargs):
permission = json.loads(self.permission)
permission = self._about(permission, **kwargs)
return InstancedPermission(self.model, permission, self.type, self.field)
def __str__(self):
if self.field:
return _("Can {type} {model}.{field} in {permission}").format(type=self.type, model=self.model, field=self.field, permission=self.permission)
else:
return _("Can {type} {model} in {permission}").format(type=self.type, model=self.model, permission=self.permission)
class UserPermission(models.Model):
user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
permission = models.ForeignKey(Permission, on_delete=models.CASCADE)

3
apps/permission/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

3
apps/permission/views.py Normal file
View File

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

View File

@ -56,6 +56,7 @@ INSTALLED_APPS = [
'activity', 'activity',
'member', 'member',
'note', 'note',
'permission'
] ]
MIDDLEWARE = [ MIDDLEWARE = [