diff --git a/akarpov/music/api/views.py b/akarpov/music/api/views.py index 759cd95..9189729 100644 --- a/akarpov/music/api/views.py +++ b/akarpov/music/api/views.py @@ -401,9 +401,15 @@ def post(self, request, *args, **kwargs): try: user_id = self.request.data.get("user_id", None) if user_id: - user = User.objects.cache().get(id=user_id) - if user != self.request.user: - return Response(status=403) + user_id_int = None + try: + user_id_int = int(user_id) + except ValueError: + ... + if user_id_int: + user = User.objects.cache().get(id=user_id_int) + if user != self.request.user: + return Response(status=403) except User.DoesNotExist: ... diff --git a/akarpov/users/api/authentification.py b/akarpov/users/api/authentification.py index 499e138..a2555d1 100644 --- a/akarpov/users/api/authentification.py +++ b/akarpov/users/api/authentification.py @@ -1,6 +1,8 @@ +from drf_spectacular.extensions import OpenApiAuthenticationExtension +from drf_spectacular.plumbing import build_bearer_security_scheme_object from rest_framework.authentication import BaseAuthentication -from akarpov.users.models import UserAPIToken +from akarpov.users.models import User, UserAPIToken from akarpov.users.tasks import set_last_active_token @@ -19,4 +21,14 @@ def authenticate(self, request): return None set_last_active_token.delay(token.token) - return token.user, token + return User.objects.cache().get(id=token.user_id), token + + +class UserTokenAuthenticationExtension(OpenApiAuthenticationExtension): + target_class = "akarpov.users.api.authentification.UserTokenAuthentication" + name = "UserTokenAuthentication" + + def get_security_definition(self, auto_schema): + return build_bearer_security_scheme_object( + header_name="Authorization", token_prefix="Bearer" + ) diff --git a/akarpov/users/api/views.py b/akarpov/users/api/views.py index a46e798..468fbe1 100644 --- a/akarpov/users/api/views.py +++ b/akarpov/users/api/views.py @@ -18,6 +18,8 @@ ) from akarpov.users.models import User +from .authentification import UserTokenAuthentication # noqa: F401 + class UserRegisterAPIViewSet(generics.CreateAPIView): """Creates new user and sends verification email""" diff --git a/config/settings/base.py b/config/settings/base.py index 632b5be..f83a164 100644 --- a/config/settings/base.py +++ b/config/settings/base.py @@ -529,6 +529,11 @@ {"url": "http://127.0.0.1:8000", "description": "Local Development server"}, {"url": "https://new.akarpov.ru", "description": "Production server"}, ], + "EXTENSIONS": { + "authentication": [ + "akarpov.users.api.authentification.UserTokenAuthenticationExtension" + ], + }, } # CKEDITOR