from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_simplejwt.exceptions import InvalidToken
from jwt.exceptions import InvalidTokenError


class SafeJWTAuthentication(JWTAuthentication):
    def authenticate(self, request):
        header = self.get_header(request)

        if header is None:
            return None
        
        raw_token = self.get_raw_token(request)
        if raw_token is None:
            return None
        
        try:
            validated_token = self.get_validated_token(raw_token)
        except (InvalidTokenError, InvalidToken, AuthenticationFailed) as e:
            return None
        
        return self.get_user(validated_token), validated_token