Files
boss_dp/server/api/auth.py
ddrwode 42b68ededd ha'ha
2026-02-25 19:10:13 +08:00

44 lines
1.3 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 -*-
"""
认证 API登录无需 Authorization
"""
import uuid
from rest_framework import status
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from server import config
from server.models import AuthToken
from server.serializers import LoginSerializer
@api_view(["POST"])
@authentication_classes([]) # 登录接口不校验 Authorization
@permission_classes([AllowAny])
def login(request):
"""
登录接口(支持 JSON 和 form-data
- 校验用户名/密码
- 生成 token写入数据库
- 返回 token前端可放到 Authorization 请求头)
- 下一次登录会生成新 token旧 token 自动失效
"""
ser = LoginSerializer(data=request.data)
ser.is_valid(raise_exception=True)
username = ser.validated_data["username"]
password = ser.validated_data["password"]
if username != config.ADMIN_USERNAME or password != config.ADMIN_PASSWORD:
return Response({"detail": "用户名或密码错误"}, status=status.HTTP_401_UNAUTHORIZED)
token = uuid.uuid4().hex
AuthToken.objects.update_or_create(
username=username,
defaults={"token": token},
)
return Response({"token": token})