feat: add JWT authentication and AGENTS.md
This commit is contained in:
51
api/app/routers/auth.py
Normal file
51
api/app/routers/auth.py
Normal file
@@ -0,0 +1,51 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import get_db
|
||||
from app.models.user_settings import UserSettings
|
||||
from app.schemas.auth import LoginRequest, TokenResponse, ChangePasswordRequest
|
||||
from app.utils.auth import (
|
||||
hash_password, verify_password, create_access_token,
|
||||
get_current_user, set_default_password
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["认证"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
def login(data: LoginRequest, db: Session = Depends(get_db)):
|
||||
settings = db.query(UserSettings).filter(UserSettings.id == 1).first()
|
||||
if not settings:
|
||||
settings = UserSettings(id=1)
|
||||
db.add(settings)
|
||||
db.commit()
|
||||
db.refresh(settings)
|
||||
|
||||
set_default_password(db, settings)
|
||||
|
||||
if not verify_password(data.password, settings.password_hash):
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
token = create_access_token({"sub": str(settings.id)})
|
||||
return TokenResponse(access_token=token)
|
||||
|
||||
|
||||
@router.post("/change-password")
|
||||
def change_password(
|
||||
data: ChangePasswordRequest,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
get_current_user(request)
|
||||
|
||||
settings = db.query(UserSettings).filter(UserSettings.id == 1).first()
|
||||
if not settings:
|
||||
raise HTTPException(status_code=500, detail="用户设置不存在")
|
||||
|
||||
if not verify_password(data.old_password, settings.password_hash):
|
||||
raise HTTPException(status_code=400, detail="原密码错误")
|
||||
|
||||
settings.password_hash = hash_password(data.new_password)
|
||||
db.commit()
|
||||
|
||||
return {"message": "密码修改成功"}
|
||||
Reference in New Issue
Block a user