Преглед изворни кода

added more option in admin page for API key customization and permissions

Apostol Mihai пре 2 година
родитељ
комит
98507210f2

+ 4 - 1
elo_api/api_src/admin.py

@@ -2,12 +2,15 @@ from django.contrib import admin
 from rest_framework_api_key.admin import APIKeyModelAdmin
 from rest_framework_api_key.models import APIKey as APIKey_default
 from .models import APIKey
-
+from django.contrib.auth.models import Permission
 
 admin.site.unregister(APIKey_default)
+admin.site.register(Permission)
+
 
 @admin.register(APIKey)
 class ClientAPIKeyModelAdmin(APIKeyModelAdmin):
+    filter_horizontal = ['permission']
     pass
 
 

+ 3 - 0
elo_api/api_src/decorators.py

@@ -0,0 +1,3 @@
+from .models import APIKey
+
+

+ 4 - 0
elo_api/api_src/models.py

@@ -4,6 +4,10 @@ from rest_framework_api_key.models import AbstractAPIKey, BaseAPIKeyManager
 from django.contrib.auth.models import User, Permission
 from django.contrib import contenttypes
 
+
+
+
+
 class APIKey(AbstractAPIKey):
         permission = models.ManyToManyField(Permission, related_name="api_keys")
 

+ 17 - 1
elo_api/api_src/permission.py

@@ -1,5 +1,21 @@
 from rest_framework_api_key.permissions import BaseHasAPIKey
 from .models import APIKey
+from rest_framework import permissions
 
 class HasAPIKey(BaseHasAPIKey):
-    model = APIKey
+    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

+ 9 - 2
elo_api/api_src/views.py

@@ -2,8 +2,12 @@ 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
+from .permission import HasAPIKey, HAsKeyPermissionn
 from rest_framework.permissions import IsAuthenticated
+from .models import APIKey
+from rest_framework.decorators import api_view, permission_classes
+
+
 
 class UserViewSet(viewsets.ModelViewSet):
     """
@@ -11,7 +15,10 @@ class UserViewSet(viewsets.ModelViewSet):
     """
     queryset = User.objects.all().order_by('-date_joined')
     serializer_class = UserSerializer
-    permission_classes = [HasAPIKey | IsAuthenticated]
+    keys = APIKey.objects.all()
+    for i in keys:
+        print()
+    permission_classes = [HasAPIKey | IsAuthenticated | HAsKeyPermissionn]
 
 
 class GroupViewSet(viewsets.ModelViewSet):

BIN
elo_api/db.sqlite3