|
|
|
@ -4,7 +4,7 @@ import jwt |
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request |
|
|
|
from sqlalchemy import select |
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession |
|
|
|
from passlib.context import CryptContext |
|
|
|
import bcrypt |
|
|
|
|
|
|
|
from database import get_db |
|
|
|
from models import User, UserRole, Role, RolePermission, Permission |
|
|
|
@ -12,8 +12,6 @@ from schemas import LoginRequest, TokenResponse, UserOut, RoleOut |
|
|
|
from config import settings |
|
|
|
|
|
|
|
router = APIRouter(prefix="/api/auth", tags=["auth"]) |
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") |
|
|
|
|
|
|
|
|
|
|
|
async def get_permission_codes(db: AsyncSession, role_ids: list[uuid.UUID]) -> list[str]: |
|
|
|
result = await db.execute( |
|
|
|
@ -53,7 +51,7 @@ async def get_user_roles(db: AsyncSession, user_id: uuid.UUID) -> list[RoleOut]: |
|
|
|
async def login(req: LoginRequest, db: AsyncSession = Depends(get_db)): |
|
|
|
result = await db.execute(select(User).where(User.username == req.username)) |
|
|
|
user = result.scalar_one_or_none() |
|
|
|
if not user or not pwd_context.verify(req.password, user.password_hash): |
|
|
|
if not user or not bcrypt.checkpw(req.password.encode('utf-8'), user.password_hash.encode('utf-8')): |
|
|
|
raise HTTPException(401, "用户名或密码错误") |
|
|
|
if user.status != "active": |
|
|
|
raise HTTPException(403, "账户已被禁用") |
|
|
|
@ -97,4 +95,4 @@ async def get_me(request: Request, db: AsyncSession = Depends(get_db)): |
|
|
|
|
|
|
|
|
|
|
|
def hash_password(password: str) -> str: |
|
|
|
return pwd_context.hash(password) |
|
|
|
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') |