from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth import get_user_model

User = get_user_model()

class VersionedJWTAuthentication(JWTAuthentication):
    """
    Odrzuca KAŻDY access token, którego token_version ≠ user.token_version.
    """
    def get_user(self, validated_token):
        user = super().get_user(validated_token)
        token_ver = int(validated_token.get("token_version", -1))
        user_ver  = int(getattr(user, "token_version", 0))
        if token_ver != user_ver:
            raise AuthenticationFailed("Token is no longer valid", code="token_stale")
        return user