auth.py 5.43 KB
"""认证路由:登录 / 登出 / 当前用户 / 自助改密。"""
import asyncio
import logging

from fastapi import APIRouter, Body, Depends, HTTPException, Response, status

from config import JWT_EXPIRE_HOURS
from src.database.models import (
    WikiOaDept,
    WikiOaPost,
    WikiOaRole,
    WikiOaUser,
    WikiOaUserPost,
    WikiOaUserRole,
)
from sqlalchemy import select
from src.database.session import AsyncSessionLocal
from src.services.identity.local import build_password_fields, get_identity_provider, verify_password
from src.services.identity.tokens import COOKIE_NAME, create_access_token, get_current_user
from src.services.memory.profile_gen import ensure_profile_on_login

logger = logging.getLogger(__name__)

router = APIRouter()


async def _user_payload(user: WikiOaUser) -> dict:
    """组装返回给前端的用户信息(含部门/岗位名与角色,供顶部展示与前端权限判定)。"""
    async with AsyncSessionLocal() as session:
        dept = await session.get(WikiOaDept, user.dept_id) if user.dept_id else None
        post = (
            await session.execute(
                select(WikiOaPost)
                .join(WikiOaUserPost, WikiOaUserPost.post_id == WikiOaPost.id)
                .where(WikiOaUserPost.user_id == user.id)
                .order_by(WikiOaPost.order_num)
            )
        ).scalars().first()
        role_codes = (
            await session.execute(
                select(WikiOaRole.role_code)
                .join(WikiOaUserRole, WikiOaUserRole.role_id == WikiOaRole.id)
                .where(WikiOaUserRole.user_id == user.id, WikiOaRole.del_flag == 0)
            )
        ).scalars().all()

    return {
        "id": user.id,
        "username": user.username,
        "displayName": user.display_name,
        "phone": user.phone,
        "isSuperadmin": bool(user.is_superadmin),
        "mustChangePwd": bool(user.must_change_pwd),
        "deptId": user.dept_id,
        "deptName": dept.dept_name if dept else None,
        "positionName": post.post_name if post else None,
        "storeName": user.store_name,
        "roles": list(role_codes),
    }


@router.post("/auth/login")
async def login(response: Response, data: dict = Body(...)):
    """账号(手机号)+ 密码登录,成功后种下 httpOnly cookie。"""
    account = (data.get("account") or "").strip()
    password = data.get("password") or ""

    if not account or not password:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="账号和密码不能为空")

    provider = get_identity_provider()
    user = await provider.authenticate(account, password)
    if user is None:
        # 不区分「账号不存在」与「密码错误」,避免账号枚举
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="账号或密码错误")

    token = create_access_token(user)
    response.set_cookie(
        key=COOKIE_NAME,
        value=token,
        httponly=True,
        samesite="lax",
        max_age=JWT_EXPIRE_HOURS * 3600,
        path="/",
    )

    # 首登画像生成:异步执行,不阻塞登录响应。
    # 生成完成前画像段落为空,不影响问答可用性。
    asyncio.create_task(ensure_profile_on_login(user.id))

    payload = await _user_payload(user)
    logger.info("[Auth] 登录成功: %s", user.username)
    return {"success": True, "user": payload, "token": token}


@router.post("/auth/logout")
async def logout(response: Response):
    """登出:清除 cookie。

    注意:本轮未引入 token 黑名单,已签发的 token 在有效期内理论上仍可用。
    这是不引入 Redis 的已知取舍,通过缩短 JWT_EXPIRE_HOURS 控制风险窗口。
    """
    response.delete_cookie(key=COOKIE_NAME, path="/")
    return {"success": True}


@router.get("/auth/me")
async def me(user: WikiOaUser = Depends(get_current_user)):
    """返回当前登录用户信息。"""
    return {"success": True, "user": await _user_payload(user)}


@router.post("/auth/change-password")
async def change_password(
    data: dict = Body(...),
    user: WikiOaUser = Depends(get_current_user),
):
    """用户自助改密:需校验旧密码。"""
    old_password = data.get("oldPassword") or ""
    new_password = data.get("newPassword") or ""

    if not old_password or not new_password:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="旧密码和新密码不能为空")
    if len(new_password) < 6:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="新密码长度不能少于 6 位")
    if new_password == old_password:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="新密码不能与旧密码相同")

    if not verify_password(old_password, user.password_salt, user.password_hash):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="旧密码错误")

    password_hash, password_salt = build_password_fields(new_password)
    async with AsyncSessionLocal() as session:
        db_user = await session.get(WikiOaUser, user.id)
        if db_user is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
        db_user.password_hash = password_hash
        db_user.password_salt = password_salt
        db_user.must_change_pwd = 0  # 改密后解除首登强制改密
        await session.commit()

    logger.info("[Auth] 用户自助修改密码: %s", user.username)
    return {"success": True}