Showing
1 changed file
with
33 additions
and
0 deletions
backend/api/utils.py
0 → 100644
1 | +import jwt | ||
2 | +import json | ||
3 | +from rest_framework import status | ||
4 | + | ||
5 | +from django.http import JsonResponse | ||
6 | +from django.core.exceptions import ObjectDoesNotExist | ||
7 | + | ||
8 | +from django.conf import settings | ||
9 | +from api.models import User | ||
10 | + | ||
11 | + | ||
12 | +def login_decorator(func): | ||
13 | + def wrapper(self, request, *args, **kwargs): | ||
14 | + if 'Authorization' not in request.headers: | ||
15 | + return JsonResponse({'Error': 'INVALID_LOGIN'}, status=status.HTTP_401_UNAUTHORIZED) | ||
16 | + | ||
17 | + request_token = request.headers['Authorization'] | ||
18 | + encode_token = request_token.encode('utf-8') | ||
19 | + | ||
20 | + try: | ||
21 | + payload = jwt.decode(encode_token, settings.SECRET_KEY, algorithm='HS256') | ||
22 | + user = User.objects.get(int_id=payload['int_id']) | ||
23 | + request.user = user | ||
24 | + | ||
25 | + except jwt.exceptions.DecodeError: | ||
26 | + return JsonResponse({'Error': 'INVALID_TOKEN'}, status=status.HTTP_400) | ||
27 | + | ||
28 | + except User.DoesNotExist: | ||
29 | + return JsonResponse({'Error': 'UNKNOWN_USER'}, status=status.HTTP_400) | ||
30 | + | ||
31 | + return func(self, request, *args, **kwargs) | ||
32 | + | ||
33 | + return wrapper | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
-
Please register or login to post a comment