Browse Source

added API key permission levels for CRUD request methods on models

Apostol Mihai 2 years ago
parent
commit
e2690221f7

+ 26 - 4
elo_api/api_src/models.py

@@ -3,9 +3,7 @@ from rest_framework_api_key.models import AbstractAPIKey, BaseAPIKeyManager
 
 from django.contrib.auth.models import User, Permission
 from django.contrib import contenttypes
-
-
-
+from django.contrib.auth.backends import ModelBackend
 
 
 class APIKey(AbstractAPIKey):
@@ -13,4 +11,28 @@ class APIKey(AbstractAPIKey):
 
         class Meta(AbstractAPIKey.Meta):
             verbose_name = "API key"
-            verbose_name_plural = "API keys"
+            verbose_name_plural = "API keys"
+
+        def get_all_permissions(self):
+            return self.permission.all()
+
+        def has_permission(self, model):
+            '''
+            Checks if the APIKey has any type of permission for a specific model
+            '''
+            permissions = self.get_all_permissions()
+            for i in permissions:
+                if model == i.content_type.model:
+                    return True
+            return False
+
+        def has_permission_method(self, model, request_method):
+            '''
+            Checks if the APIKey has request method permission on certain model
+            request_method can be POST, GET, PUT, DELETE
+            '''
+            permissions = self.get_all_permissions()
+            for i in permissions:
+                if model == i.content_type.model and request_method in i.codename:
+                    return True
+            return False

+ 0 - 15
elo_api/api_src/permission.py

@@ -4,18 +4,3 @@ from rest_framework import permissions
 
 class HasAPIKey(BaseHasAPIKey):
     model = APIKey
-
-
-class HAsKeyPermissionn(permissions.BasePermission):
-    """
-    Object-level permission to only allow owners of an object to edit it.
-    Assumes the model instance has an `owner` attribute.
-    """
-
-    def has_object_permission(self, request, view, obj):
-        print(request)
-        if request.method in permissions.SAFE_METHODS:
-            return True
-
-        # Instance must have an attribute named `owner`.
-        return obj.owner == request.user

+ 10 - 0
elo_api/api_src/utils.py

@@ -0,0 +1,10 @@
+
+def parse_request_method_name(method):
+    if method in ["POST", "post"]:
+        return "add"
+    if method in ["GET", "get"]:
+        return "view"
+    if method in ["PUT", "put"]:
+        return "change"
+    if method in ["DELETE", "delete"]:
+        return "delete"

+ 22 - 4
elo_api/api_src/views.py

@@ -2,11 +2,11 @@ from django.contrib.auth.models import User, Group
 from rest_framework import viewsets
 from .serializers import UserSerializer, GroupSerializer
 from rest_framework.views import APIView
-from .permission import HasAPIKey, HAsKeyPermissionn
+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
 
 
 class UserViewSet(viewsets.ModelViewSet):
@@ -18,7 +18,7 @@ class UserViewSet(viewsets.ModelViewSet):
     keys = APIKey.objects.all()
     for i in keys:
         print()
-    permission_classes = [HasAPIKey | IsAuthenticated | HAsKeyPermissionn]
+    permission_classes = [HasAPIKey | IsAuthenticated]
 
 
 class GroupViewSet(viewsets.ModelViewSet):
@@ -27,4 +27,22 @@ class GroupViewSet(viewsets.ModelViewSet):
     """
     queryset = Group.objects.all()
     serializer_class = GroupSerializer
-    permission_classes = [HasAPIKey | IsAuthenticated]
+    permission_classes = [HasAPIKey | IsAuthenticated]
+
+
+class SnippetUSER(APIView):
+    permission_classes = []
+    print(permission_classes)
+    def get(self, request, format=None):
+        snippets = User.objects.all()
+        serializer = UserSerializer(snippets, many=True, context={'request': request})
+        try:
+            header_key = request.META["HTTP_X_API_KEY"]
+        except:
+            header_key = request.META["HTTP_X_CSRFTOKEN"]
+        db_key = APIKey.objects.get_from_key(header_key)
+        #print(db_key.permission.all())
+        print(db_key.has_permission("user"))
+        print(db_key.has_permission_method("user", "add"))
+        #print(header_key.permission)
+        return Response(serializer.data)

BIN
elo_api/db.sqlite3


+ 2 - 1
elo_api/elo_api/settings.py

@@ -63,7 +63,8 @@ SWAGGER_SETTINGS = {
             'name': 'Authorization',
             'in': 'header'
       }
-   }
+   },
+   'JSON_EDITOR': True,
 }
 
 API_KEY_CUSTOM_HEADER = "HTTP_X_API_KEY"

+ 2 - 0
elo_api/elo_api/urls.py

@@ -49,4 +49,6 @@ urlpatterns = [
     re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
     path('', include(router.urls)),
     path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
+
+    path('snippets/', views.SnippetUSER.as_view()),
 ]