refactor:重构route-service-repositories,删除测试代码
This commit is contained in:
+29
-2
@@ -1,4 +1,4 @@
|
||||
"""认证服务:JWT 签发/校验(HS256)+ 密码哈希/校验。
|
||||
"""认证服务:登录业务 + JWT 签发/校验(HS256)+ 密码哈希/校验。
|
||||
|
||||
密码用 stdlib PBKDF2(免 bcrypt 依赖),存储格式自描述:
|
||||
pbkdf2_sha256$600000$<salt_hex>$<digest_hex>
|
||||
@@ -9,8 +9,12 @@ import secrets
|
||||
import time
|
||||
|
||||
import jwt
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from config.settings import settings
|
||||
from model.sys_user import SysUser
|
||||
from repositories.sys_user import SysUserRepo
|
||||
from utils.exceptions import ForbiddenError, ParamError
|
||||
|
||||
_ITERATIONS = 600_000
|
||||
|
||||
@@ -43,4 +47,27 @@ def verify_password(password: str, stored: str) -> bool:
|
||||
except ValueError:
|
||||
return False
|
||||
calc = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), int(iters))
|
||||
return hmac.compare_digest(calc.hex(), digest)
|
||||
return hmac.compare_digest(calc.hex(), digest)
|
||||
|
||||
|
||||
# ---- 登录业务(路由层只编排,不碰数据/逻辑) ----
|
||||
def user_payload(u: SysUser) -> dict:
|
||||
"""对外暴露的用户信息(不含密码等敏感字段)。"""
|
||||
return {
|
||||
"id": u.id,
|
||||
"username": u.username,
|
||||
"user_type": u.user_type,
|
||||
"employee_role": u.employee_role,
|
||||
"customer_level": u.customer_level,
|
||||
"status": u.status,
|
||||
}
|
||||
|
||||
|
||||
async def login(db: AsyncSession, username: str, password: str) -> dict:
|
||||
"""校验账号密码与状态,成功签发 token 并返回用户信息;失败抛业务异常。"""
|
||||
user = await SysUserRepo(db).get_by_username(username)
|
||||
if user is None or not verify_password(password, user.password_hash):
|
||||
raise ParamError("用户名或密码错误")
|
||||
if user.status != "正常":
|
||||
raise ForbiddenError("账号状态异常,无法登录")
|
||||
return {"token": create_token(user.id), "user": user_payload(user)}
|
||||
Reference in New Issue
Block a user