utils.py 999 Bytes
import jwt
import json
from rest_framework import status
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from api.models import User


def login_decorator(func):
    def wrapper(self, request, *args, **kwargs):
        if 'Authorization' not in request.headers:
            return JsonResponse({'Error': 'INVALID_LOGIN'}, status=status.HTTP_401_UNAUTHORIZED)
        encode_token = request.headers['Authorization']
        try:
            payload = jwt.decode(encode_token, settings.SECRET_KEY, algorithm='HS256')
            user = User.objects.get(int_id=payload['int_id'])
            request.user = user
        except jwt.exceptions.DecodeError:
            return JsonResponse({'Error': 'INVALID_TOKEN'}, status=status.HTTP_400)
        except User.DoesNotExist:
            return JsonResponse({'Error': 'UNKNOWN_USER'}, status=status.HTTP_400)
        return func(self, request, *args, **kwargs)
    return wrapper