Create auth backend for event specific models

This commit is contained in:
Ludovic Stephan 2017-08-17 18:40:06 +02:00
parent 0b1641a002
commit 1d491e3d26
2 changed files with 53 additions and 0 deletions

50
api/backends.py Normal file
View file

@ -0,0 +1,50 @@
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import MethodNotAllowed
from rest_framework.compat import is_authenticated
class EventSpecificPermissions(BasePermission):
perms_map = {
'GET': [],
'OPTIONS': [],
'HEAD': [],
'POST': ['%(prefix)sadd_%(model_name)s'],
'PUT': ['%(prefix)schange_%(model_name)s'],
'PATCH': ['%(prefix)schange_%(model_name)s'],
'DELETE': ['%(prefix)sdelete_%(model_name)s'],
}
def get_required_permissions(self, method, view, model_cls):
if view.event:
kwargs = {
'prefix': "event_",
'model_name': model_cls._meta.model_name
}
else:
kwargs = {
'prefix': model_cls._meta.app_label+".",
'model_name': model_cls._meta.model_name
}
if method not in self.perms_map:
raise MethodNotAllowed(method)
return [perm % kwargs for perm in self.perms_map[method]]
def has_permission(self, request, view):
if hasattr(view, 'get_queryset'):
queryset = view.get_queryset()
else:
queryset = getattr(view, 'queryset', None)
perms = self.get_required_permissions(request.method, view,
queryset.model)
return (
request.user and
is_authenticated(request.user) and
request.user.has_perms(perms, view.event)
)

View file

@ -12,6 +12,7 @@ from .serializers import (
ActivitySerializer, ActivityTagSerializer, ActivityTemplateSerializer,
EventSerializer, PlaceSerializer,
)
from api.backends import EventSpecificPermissions
User = get_user_model()
@ -59,6 +60,8 @@ class EventSpecificModelViewSet(EventModelViewSet):
Useful for models that extends EventSpecificMixin
"""
permission_classes = (EventSpecificPermissions,)
def get_queryset(self):
"""
Warning : You may want to override this method