Files
boss_dp/server/core/authentication.py

39 lines
1.1 KiB
Python
Raw Normal View History

2026-02-14 16:50:02 +08:00
# -*- coding: utf-8 -*-
"""
DRF 自定义认证后端 Cookie 中读取 auth_token 校验
"""
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
class TokenUser:
"""轻量用户对象(不依赖 Django auth 模块)。"""
def __init__(self, username: str):
self.username = username
self.is_authenticated = True
def __str__(self):
return self.username
class CookieTokenAuthentication(BaseAuthentication):
"""
从请求 Cookie 中读取 auth_token查数据库校验
"""
def authenticate(self, request):
token = request.COOKIES.get("auth_token")
if not token:
return None # 未携带 token交给权限类处理
# 延迟导入避免循环依赖
from server.models import AuthToken
try:
row = AuthToken.objects.get(token=token)
except AuthToken.DoesNotExist:
raise AuthenticationFailed("登录已失效,请重新登录")
return (TokenUser(row.username), token)