Browse Source

Api key permissions based on model and request methods are now fully implemented through decorator

Apostol Mihai 2 years ago
parent
commit
8dd10fe5f1
3 changed files with 18 additions and 3 deletions
  1. 13 0
      elo_api/api_src/decorators.py
  2. 1 1
      elo_api/api_src/models.py
  3. 4 2
      elo_api/api_src/views.py

+ 13 - 0
elo_api/api_src/decorators.py

@@ -1,3 +1,16 @@
 from .models import APIKey
+from rest_framework.decorators import api_view, throttle_classes
 
+from django.shortcuts import render, HttpResponse
 
+def api_permission_required(model, request_method):
+    def decorator(view_func):
+        def wrap(request, *args, **kwargs):
+            header_key = request.META["HTTP_X_API_KEY"]
+            db_key = APIKey.objects.get_from_key(header_key)
+            if db_key.has_permission_method(model, request_method):
+                return view_func(request, *args, **kwargs)
+            else:
+                return HttpResponse("NO ACCES")
+        return wrap
+    return decorator

+ 1 - 1
elo_api/api_src/models.py

@@ -29,7 +29,7 @@ class APIKey(AbstractAPIKey):
 
         def has_permission_method(self, model, request_method):
             '''
-            Checks if the APIKey has request method permission on certain model
+            Checks if the APIKey has request method permission on certain model. 
             request_method can be POST, GET, PUT, DELETE
             '''
             permissions = self.get_all_permissions()

+ 4 - 2
elo_api/api_src/views.py

@@ -5,8 +5,9 @@ from rest_framework.views import APIView
 from .permission import HasAPIKey
 from rest_framework.permissions import IsAuthenticated
 from .models import APIKey
-from rest_framework.decorators import api_view, permission_classes
 from rest_framework.response import Response
+from django.utils.decorators import method_decorator
+from .decorators import api_permission_required
 
 
 class UserViewSet(viewsets.ModelViewSet):
@@ -32,7 +33,8 @@ class GroupViewSet(viewsets.ModelViewSet):
 
 class SnippetUSER(APIView):
     permission_classes = []
-    print(permission_classes)
+
+    @method_decorator(api_permission_required("user", "post"), name='dispatch')
     def get(self, request, format=None):
         snippets = User.objects.all()
         serializer = UserSerializer(snippets, many=True, context={'request': request})