From 67017d9771c64064b2a3d6ab4a7fcbe99cace51f Mon Sep 17 00:00:00 2001 From: Abderrahmane Smimite Date: Wed, 17 Apr 2024 06:31:57 +0200 Subject: [PATCH] Experimental: support token authentication for API --- backend/ciso_assistant/settings.py | 2 ++ backend/ciso_assistant/urls.py | 3 ++- backend/core/apps.py | 2 ++ backend/core/signals.py | 9 +++++++++ 4 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 backend/core/signals.py diff --git a/backend/ciso_assistant/settings.py b/backend/ciso_assistant/settings.py index caeb7095c..c21e66d83 100644 --- a/backend/ciso_assistant/settings.py +++ b/backend/ciso_assistant/settings.py @@ -131,6 +131,7 @@ def set_ciso_assistant_url(_, __, event_dict): "serdes", "rest_framework", "drf_spectacular", + "rest_framework.authtoken", ] MIDDLEWARE = [ @@ -181,6 +182,7 @@ def set_ciso_assistant_url(_, __, event_dict): ], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", + "rest_framework.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", diff --git a/backend/ciso_assistant/urls.py b/backend/ciso_assistant/urls.py index 62b53e3cf..0bba1a75f 100644 --- a/backend/ciso_assistant/urls.py +++ b/backend/ciso_assistant/urls.py @@ -16,11 +16,12 @@ from django.urls import include, path from ciso_assistant import settings from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView - +from rest_framework.authtoken import views # beware of the order of url patterns, this can change de behavior in case of multiple matches and avoid giving identical paths that could cause conflicts urlpatterns = [ path("api/", include("core.urls")), + path('api-token-auth/', views.obtain_auth_token), path("serdes/", include("serdes.urls")), path("i18n/", include("django.conf.urls.i18n")), path('api/schema/', SpectacularAPIView.as_view(), name='schema'), diff --git a/backend/core/apps.py b/backend/core/apps.py index 4846d60cc..6f93e48fe 100644 --- a/backend/core/apps.py +++ b/backend/core/apps.py @@ -359,3 +359,5 @@ def ready(self): # avoid post_migrate handler if we are in the main, as it interferes with restore if not os.environ.get("RUN_MAIN"): post_migrate.connect(startup, sender=self) + + import core.signals diff --git a/backend/core/signals.py b/backend/core/signals.py new file mode 100644 index 000000000..697a46916 --- /dev/null +++ b/backend/core/signals.py @@ -0,0 +1,9 @@ +from django.conf import settings +from django.db.models.signals import post_save +from django.dispatch import receiver +from rest_framework.authtoken.models import Token + +@receiver(post_save, sender=settings.AUTH_USER_MODEL) +def create_auth_token(sender, instance=None, created=False, **kwargs): + if created: + Token.objects.create(user=instance) \ No newline at end of file