lty/qy_lty/userapp/authentication.py
2026-03-17 13:17:02 +08:00

32 lines
1.0 KiB
Python

from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import AuthenticationFailed
from .utils import get_user_id_from_token
from .models import ParadiseUser
import logging
logger = logging.getLogger(__name__)
class RedisTokenAuthentication(BaseAuthentication):
def authenticate(self, request):
authorization = request.headers.get('Authorization')
if not authorization:
return None
if len(authorization.split(' ')) < 2:
return None
token = authorization.split(' ')[1]
if not token:
return None
logger.debug(f"Authorization header: {token}") # 使用日志记录
user_id = get_user_id_from_token(token)
if not user_id:
raise AuthenticationFailed('Invalid token')
try:
user = ParadiseUser.objects.get(id=user_id)
except ParadiseUser.DoesNotExist:
raise AuthenticationFailed('User not found')
return (user, None)