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):
<<<<<<< HEAD
    authorization_header = request.headers.get('Authorization')
    print("Authorization header from request:", authorization_header)

    if not authorization_header:
        raise Exception("Authentication failed: No Authorization header")

    try:
        access_token = authorization_header  # If not using "Bearer " prefix
        payload = jwt.decode(access_token, settings.SECRET_KEY, algorithms=['HS256'])
        print("JWT payload:", payload)
    except jwt.ExpiredSignatureError:
        raise exceptions.AuthenticationFailed('Access token expired')
    except jwt.DecodeError:
        raise exceptions.AuthenticationFailed('Invalid token')
    except Exception as e:
        raise exceptions.AuthenticationFailed(str(e))

    user = EndUser.objects.filter(id=payload.get('user_id')).first()
    if not user:
        raise exceptions.AuthenticationFailed('User not found')

    return str(user.id)
=======
	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')
	return str(userID.id)
>>>>>>> d56746e (first commit)
