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 AppUser

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

	try:
		access_token = authorization_header

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

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

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