Files
boss_dp/server/core/authentication.py
Your Name 2e143fb0c0 哈哈
2026-02-14 16:50:02 +08:00

39 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- 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)