Jelajahi Sumber

extended APIKey model with permission for each future model. Added 'template' for second db. Added customization for drf_yasg(swagger)

Apostol Mihai 2 tahun lalu
induk
melakukan
8b7ccf3578

+ 15 - 0
elo_api/api_src/admin.py

@@ -1 +1,16 @@
 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
+
+
+admin.site.unregister(APIKey_default)
+
+@admin.register(APIKey)
+class ClientAPIKeyModelAdmin(APIKeyModelAdmin):
+    pass
+
+
+
+
+#admin.site.register(APIKey)

+ 34 - 0
elo_api/api_src/migrations/0001_initial.py

@@ -0,0 +1,34 @@
+# Generated by Django 4.0.3 on 2022-04-11 10:40
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    initial = True
+
+    dependencies = [
+        ('auth', '0012_alter_user_first_name_max_length'),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='APIKey',
+            fields=[
+                ('id', models.CharField(editable=False, max_length=150, primary_key=True, serialize=False, unique=True)),
+                ('prefix', models.CharField(editable=False, max_length=8, unique=True)),
+                ('hashed_key', models.CharField(editable=False, max_length=150)),
+                ('created', models.DateTimeField(auto_now_add=True, db_index=True)),
+                ('name', models.CharField(default=None, help_text='A free-form name for the API key. Need not be unique. 50 characters max.', max_length=50)),
+                ('revoked', models.BooleanField(blank=True, default=False, help_text='If the API key is revoked, clients cannot use it anymore. (This cannot be undone.)')),
+                ('expiry_date', models.DateTimeField(blank=True, help_text='Once API key expires, clients cannot use it anymore.', null=True, verbose_name='Expires')),
+                ('permission', models.ManyToManyField(related_name='api_keys', to='auth.permission')),
+            ],
+            options={
+                'verbose_name': 'API key',
+                'verbose_name_plural': 'API keys',
+                'ordering': ('-created',),
+                'abstract': False,
+            },
+        ),
+    ]

+ 0 - 0
elo_api/api_src/migrations/__init__.py


+ 12 - 0
elo_api/api_src/models.py

@@ -0,0 +1,12 @@
+from django.db import models
+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")
+
+        class Meta(AbstractAPIKey.Meta):
+            verbose_name = "API key"
+            verbose_name_plural = "API keys"

+ 5 - 0
elo_api/api_src/permission.py

@@ -0,0 +1,5 @@
+from rest_framework_api_key.permissions import BaseHasAPIKey
+from .models import APIKey
+
+class HasAPIKey(BaseHasAPIKey):
+    model = APIKey

+ 1 - 1
elo_api/api_src/serializers.py

@@ -5,7 +5,7 @@ from rest_framework import serializers
 class UserSerializer(serializers.HyperlinkedModelSerializer):
     class Meta:
         model = User
-        fields = ['url', 'username', 'first_name', 'last_name','email', 'groups']
+        fields = ['url','id', 'username', 'first_name', 'last_name','email', 'groups']
 
 
 class GroupSerializer(serializers.HyperlinkedModelSerializer):

+ 4 - 5
elo_api/api_src/views.py

@@ -1,10 +1,9 @@
 from django.contrib.auth.models import User, Group
 from rest_framework import viewsets
-from rest_framework import permissions
 from .serializers import UserSerializer, GroupSerializer
 from rest_framework.views import APIView
-from rest_framework_api_key.permissions import HasAPIKey
-
+from .permission import HasAPIKey
+from rest_framework.permissions import IsAuthenticated
 
 class UserViewSet(viewsets.ModelViewSet):
     """
@@ -12,7 +11,7 @@ class UserViewSet(viewsets.ModelViewSet):
     """
     queryset = User.objects.all().order_by('-date_joined')
     serializer_class = UserSerializer
-    permission_classes = [HasAPIKey]
+    permission_classes = [HasAPIKey | IsAuthenticated]
 
 
 class GroupViewSet(viewsets.ModelViewSet):
@@ -21,4 +20,4 @@ class GroupViewSet(viewsets.ModelViewSet):
     """
     queryset = Group.objects.all()
     serializer_class = GroupSerializer
-    permission_classes = [HasAPIKey]
+    permission_classes = [HasAPIKey | IsAuthenticated]

TEMPAT SAMPAH
elo_api/db.sqlite3


+ 23 - 0
elo_api/elo_api/settings.py

@@ -37,6 +37,7 @@ INSTALLED_APPS = [
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
+    'api_src',
     'rest_framework',
     "rest_framework_api_key",
     'drf_yasg',
@@ -51,6 +52,20 @@ REST_FRAMEWORK = {
     ],
     'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
 }
+
+SWAGGER_SETTINGS = {
+   'SECURITY_DEFINITIONS': {
+      'Basic': {
+            'type': 'basic'
+      },
+      'Bearer': {
+            'type': 'apiKey',
+            'name': 'Authorization',
+            'in': 'header'
+      }
+   }
+}
+
 API_KEY_CUSTOM_HEADER = "HTTP_X_API_KEY"
 
 MIDDLEWARE = [
@@ -91,6 +106,14 @@ DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.sqlite3',
         'NAME': BASE_DIR / 'db.sqlite3',
+    },
+    'ELO_API': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': 'elo api db',
+        'USER': 'myprojectuser',
+        'PASSWORD': 'password',
+        'HOST': 'localhost',
+        'PORT': '',
     }
 }