From 90b2896ded7926660de8b32d3cefe2b0dedc80bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Jastrz=C4=99bski?= Date: Wed, 13 Oct 2021 16:01:31 +0200 Subject: [PATCH] Add ApiTokenRequiredMixin --- shynet/api/mixins.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 shynet/api/mixins.py diff --git a/shynet/api/mixins.py b/shynet/api/mixins.py new file mode 100644 index 0000000..380e009 --- /dev/null +++ b/shynet/api/mixins.py @@ -0,0 +1,24 @@ +from django.http import JsonResponse +from django.contrib.auth.models import AnonymousUser +from .models import ApiToken + + +class ApiTokenRequiredMixin: + def _get_user_by_token(self, request): + token = request.headers.get('Authorization') + if not token or not token.startswith('Token '): + return AnonymousUser() + + token = token.split(' ')[1] + api_token = ApiToken.objects.filter(value=token).first() + if not api_token: + return AnonymousUser() + + return api_token.user + + def dispatch(self, request, *args, **kwargs): + request.user = self._get_user_by_token(request) + if not request.user.is_authenticated: + return JsonResponse(data={}, status=403) + + return super().dispatch(request, *args, **kwargs)