67 lines
1.9 KiB
Python
67 lines
1.9 KiB
Python
"""
|
|
认证路由
|
|
"""
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi.security import HTTPBearer
|
|
from sqlalchemy.orm import Session
|
|
from datetime import timedelta
|
|
|
|
from database import get_db
|
|
from models import User
|
|
from schemas import Token, UserLogin, UserChangePassword
|
|
from auth import (
|
|
verify_password,
|
|
get_password_hash,
|
|
create_access_token,
|
|
get_current_user
|
|
)
|
|
|
|
router = APIRouter(prefix="/auth", tags=["认证"])
|
|
security = HTTPBearer()
|
|
|
|
|
|
@router.post("/login", response_model=Token)
|
|
def login(credentials: UserLogin, db: Session = Depends(get_db)):
|
|
"""用户登录"""
|
|
user = db.query(User).filter(User.username == credentials.username).first()
|
|
|
|
if not user or not verify_password(credentials.password, user.hashed_password):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="用户名或密码错误",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
access_token = create_access_token(data={"sub": user.username})
|
|
return {"access_token": access_token, "token_type": "bearer"}
|
|
|
|
|
|
@router.post("/change-password")
|
|
def change_password(
|
|
data: UserChangePassword,
|
|
current_user: User = Depends(get_current_user),
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""修改密码"""
|
|
# 验证旧密码
|
|
if not verify_password(data.old_password, current_user.hashed_password):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="旧密码错误"
|
|
)
|
|
|
|
# 更新密码
|
|
current_user.hashed_password = get_password_hash(data.new_password)
|
|
db.commit()
|
|
|
|
return {"message": "密码修改成功"}
|
|
|
|
|
|
@router.get("/me")
|
|
def get_me(current_user: User = Depends(get_current_user)):
|
|
"""获取当前用户信息"""
|
|
return {
|
|
"username": current_user.username,
|
|
"created_at": current_user.created_at
|
|
}
|