From 1d491e3d26fb3afa241c2f9cc0fec26c4d8663c0 Mon Sep 17 00:00:00 2001 From: Ludovic Stephan Date: Thu, 17 Aug 2017 18:40:06 +0200 Subject: [PATCH] Create auth backend for event specific models --- api/backends.py | 50 ++++++++++++++++++++++++++++++++++++++++++++++ api/event/views.py | 3 +++ 2 files changed, 53 insertions(+) create mode 100644 api/backends.py diff --git a/api/backends.py b/api/backends.py new file mode 100644 index 0000000..cc8aa4e --- /dev/null +++ b/api/backends.py @@ -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) + ) diff --git a/api/event/views.py b/api/event/views.py index 3497f3a..f38266d 100644 --- a/api/event/views.py +++ b/api/event/views.py @@ -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