@@ -0,0 +1,55 @@
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel
|
||||
import db
|
||||
import auth
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
class UserAuth(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
@router.post("/api/register")
|
||||
def register(user: UserAuth):
|
||||
if not user.username or not user.password:
|
||||
raise HTTPException(status_code=400, detail="用户名和密码不能为空")
|
||||
if len(user.username) < 3 or len(user.username) > 20:
|
||||
raise HTTPException(status_code=400, detail="用户名长度需在3-20个字符之间")
|
||||
if len(user.password) < 6:
|
||||
raise HTTPException(status_code=400, detail="密码长度至少6个字符")
|
||||
|
||||
existing_user = db.get_user_by_username(user.username)
|
||||
if existing_user:
|
||||
raise HTTPException(status_code=400, detail="用户名已存在")
|
||||
|
||||
hashed_password = auth.get_password_hash(user.password)
|
||||
new_user = db.create_user({"username": user.username, "password": hashed_password})
|
||||
|
||||
return {"message": "注册成功", "userId": new_user["id"]}
|
||||
|
||||
@router.post("/api/login")
|
||||
def login(user: UserAuth):
|
||||
if not user.username or not user.password:
|
||||
raise HTTPException(status_code=400, detail="用户名和密码不能为空")
|
||||
|
||||
db_user = db.get_user_by_username(user.username)
|
||||
if not db_user:
|
||||
raise HTTPException(status_code=401, detail="用户名或密码错误")
|
||||
|
||||
if not auth.verify_password(user.password, db_user["password"]):
|
||||
raise HTTPException(status_code=401, detail="用户名或密码错误")
|
||||
|
||||
token = auth.create_access_token({"id": db_user["id"], "username": db_user["username"]})
|
||||
return {
|
||||
"message": "登录成功",
|
||||
"token": token,
|
||||
"user": {"id": db_user["id"], "username": db_user["username"]}
|
||||
}
|
||||
|
||||
@router.get("/api/me")
|
||||
def get_me(current_user: dict = Depends(auth.get_current_user)):
|
||||
return {"user": {"id": current_user["id"], "username": current_user["username"]}}
|
||||
|
||||
@router.post("/api/logout")
|
||||
def logout():
|
||||
return {"message": "已退出登录"}
|
||||
Reference in New Issue
Block a user