36 lines
1.3 KiB
Python
36 lines
1.3 KiB
Python
from fastapi import APIRouter, Depends, Header
|
|
|
|
from backend.app.api.deps import get_auth_service
|
|
from backend.app.core.error_codes import ErrorCode
|
|
from backend.app.core.exceptions import AppException
|
|
from backend.app.schemas.auth import LoginRequest
|
|
from backend.app.schemas.common import success_payload
|
|
from backend.app.services.auth_service import AuthService
|
|
|
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
|
|
|
|
|
@router.post("/login")
|
|
def login(payload: LoginRequest, auth_service: AuthService = Depends(get_auth_service)) -> dict:
|
|
user = auth_service.login(payload.username, payload.role_type)
|
|
if not user:
|
|
raise AppException(code=ErrorCode.UNAUTHORIZED, message="账号不存在或角色不匹配", status_code=400)
|
|
return success_payload(user)
|
|
|
|
|
|
@router.get("/me")
|
|
def me(
|
|
authorization: str | None = Header(default=None),
|
|
auth_service: AuthService = Depends(get_auth_service),
|
|
) -> dict:
|
|
token = (authorization or "").removeprefix("Bearer").strip()
|
|
user = auth_service.get_me(token)
|
|
if not user:
|
|
raise AppException(code=ErrorCode.UNAUTHORIZED, message="未登录或登录失效", status_code=401)
|
|
return success_payload(user)
|
|
|
|
|
|
@router.post("/logout")
|
|
def logout() -> dict:
|
|
return success_payload({"success": True})
|