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
from .models import EndUser
from django.utils import timezone


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 = EndUser.objects.get(id=payload['user_id'])
	if userID is None:
		raise exceptions.AuthenticationFailed('User not found')


	userID.last_login = timezone.now()
	userID.save(update_fields=["last_login"])
	return str(userID.id)



