from fastapi import APIRouter, Depends, HTTPException from fastapi.security import OAuth2PasswordRequestForm from app.core.security import verify_password, create_access_token, user_db router = APIRouter(prefix="/auth", tags=["auth"]) @router.post("/login", description="登录") async def login(form_data: OAuth2PasswordRequestForm = Depends()): user = user_db.get(form_data.username) if not user: raise HTTPException(status_code=401, detail="用户名不存在", headers={"WWW-Authenticate": "Bearer"}) elif not verify_password(form_data.password, user["password"]): raise HTTPException(status_code=401, detail="密码错误", headers={"WWW-Authenticate": "Bearer"}) access_token = create_access_token(data={"sub": user["username"]}) return { "access_token": access_token, "token_type": "bearer" }