from django.contrib.auth.models import User
from rest_framework import exceptions
import jwt
from django.conf import settings
from rest_framework.response import Response
from rest_framework import status

def authenticated(request):
	authorization_header = request.headers.get('Authorization')
	print('authorization_header',authorization_header)
	if not authorization_header:
		raise Exception("Authentication failed")

	try:
		access_token = authorization_header
		print('access_token',access_token)

		payload = jwt.decode(
			access_token, settings.SECRET_KEY, algorithms=['HS256'])
		print('payload',payload)
	except jwt.ExpiredSignatureError:
		print('excep')
		raise exceptions.AuthenticationFailed('access_token expired')
	except IndexError:
		print('excep2')
		raise exceptions.AuthenticationFailed('Token prefix missing')

	userID = User.objects.get(id=payload['user_id'])
	if userID is None:
		raise exceptions.AuthenticationFailed('User not found')

	if not userID.is_active:
		raise exceptions.AuthenticationFailed('user is inactive')
	return str(userID.id)





# from rest_framework import authentication
# from django.contrib.auth import get_user_model
# from .models import *
# from rest_framework.authentication import BaseAuthentication
# from django.middleware.csrf import CsrfViewMiddleware
# class SafeJWTAuthentication(BaseAuthentication):

#     def authenticate(self, request):

#         User = get_user_model()
#         authorization_header = request.headers.get('Authorization')
#         print('authorization_header',authorization_header)
#         if not authorization_header:
#             return None
#         try:
#             access_token = authorization_header
#             print('access_token',access_token)

#             payload = jwt.decode(
#                 access_token, settings.SECRET_KEY, algorithms=['HS256'])
#             print('payload',payload)
#         except jwt.ExpiredSignatureError:
#             raise exceptions.AuthenticationFailed('access_token expired')
#         except IndexError:
#             raise exceptions.AuthenticationFailed('Token prefix missing')

        # userID = User.objects.get(id=payload['user_id'])
        # if userID is None:
        #     raise exceptions.AuthenticationFailed('User not found')

        # if not userID.is_active:
        #     raise exceptions.AuthenticationFailed('user is inactive')
        # return (str(userID.id),None)