rbac.py 16.3 KB
"""角色与权限资源管理路由。"""
from datetime import datetime

from fastapi import APIRouter, Body, Depends, HTTPException, Request, status
from pypinyin import Style, lazy_pinyin
from sqlalchemy import select

from src.database.models import (
    WikiOaRole,
    WikiOaRoleDept,
    WikiOaRoleSource,
    WikiOaSource,
    WikiOaUser,
)
from src.database.session import AsyncSessionLocal
from src.services.oa import enums
from src.services.oa.audit import log_oper
from src.services.oa.deps import require_perm
from src.services.oa.seed import ensure_rbac_seed

router = APIRouter()


# ==================================== 角色 ====================================

async def _gen_role_code(session, name: str) -> str:
    """角色编码:取名称拼音首字母;已占用则追加 2、3… 后缀。

    角色编码是代码里的枚举契约(enums.ROLE_* 常量、seed 的幂等匹配键),
    故必须全局唯一且含逻辑删除记录——已删编码不复用,避免权限张冠李戴。
    角色总量只有个位数,直接全量取出比对即可。
    """
    initials = lazy_pinyin(name.strip(), style=Style.FIRST_LETTER, errors=lambda x: x)
    base = "".join(c for c in "".join(initials).lower() if c.isalnum()) or "role"

    existing = {
        c for c in (await session.execute(select(WikiOaRole.role_code))).scalars().all() if c
    }
    if base not in existing:
        return base
    i = 2
    while f"{base}{i}" in existing:
        i += 1
    return f"{base}{i}"

def _role_payload(r: WikiOaRole) -> dict:
    return {
        "id": r.id,
        "roleCode": r.role_code,
        "roleName": r.role_name,
        "dataScope": r.data_scope,
        "orderNum": r.order_num,
        "isBuiltin": bool(r.is_builtin),
        "status": r.status,
        "remark": r.remark,
    }


@router.get("/oa/roles", dependencies=[Depends(require_perm("oa:role:list"))])
async def list_roles():
    async with AsyncSessionLocal() as session:
        rows = (
            await session.execute(
                select(WikiOaRole)
                .where(WikiOaRole.del_flag == enums.DEL_NORMAL)
                .order_by(WikiOaRole.order_num)
            )
        ).scalars().all()
    return {"success": True, "items": [_role_payload(r) for r in rows]}


@router.post("/oa/roles")
async def create_role(
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:role:add")),
):
    code = (data.get("roleCode") or "").strip()
    name = (data.get("roleName") or "").strip()
    if not name:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="角色名称不能为空")
    scope = int(data.get("dataScope") or enums.SCOPE_SELF)
    if scope not in enums.DATA_SCOPES:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="数据范围非法")
    async with AsyncSessionLocal() as session:
        # 角色编码:留空则按名称拼音首字母自动生成;全局唯一含已删、不可复用
        if not code:
            code = await _gen_role_code(session, name)
        dup = (
            await session.execute(select(WikiOaRole.id).where(WikiOaRole.role_code == code))
        ).scalars().first()
        if dup:
            raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="角色编码已存在")
        role = WikiOaRole(
            role_code=code, role_name=name, data_scope=scope,
            order_num=int(data.get("orderNum") or 0), is_builtin=0,
            status=enums.STATUS_ACTIVE, del_flag=enums.DEL_NORMAL,
            remark=(data.get("remark") or None),
        )
        session.add(role)
        await session.commit()
        rid = role.id
    await log_oper(operator=me, request=request, module="role", action="create",
                   target_type="role", target_id=rid, target_name=name, detail={"code": code, "scope": scope})
    return {"success": True, "id": rid}


@router.patch("/oa/roles/{role_id}")
async def update_role(
    role_id: str,
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:role:edit")),
):
    async with AsyncSessionLocal() as session:
        role = await session.get(WikiOaRole, role_id)
        if role is None or role.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
        if "roleName" in data:
            role.role_name = (data.get("roleName") or "").strip() or role.role_name
        if "dataScope" in data and int(data["dataScope"]) in enums.DATA_SCOPES:
            role.data_scope = int(data["dataScope"])
        if "orderNum" in data:
            role.order_num = int(data.get("orderNum") or 0)
        if "status" in data and data["status"] in enums.STATUSES:
            role.status = data["status"]
        if "remark" in data:
            role.remark = data.get("remark") or None
        # 自定义部门集合(data_scope=2 时生效),可随编辑一并保存
        if "deptIds" in data and isinstance(data["deptIds"], list):
            for rd in (
                await session.execute(select(WikiOaRoleDept).where(WikiOaRoleDept.role_id == role_id))
            ).scalars().all():
                await session.delete(rd)
            if role.data_scope == enums.SCOPE_CUSTOM:
                for did in set(data["deptIds"]):
                    session.add(WikiOaRoleDept(role_id=role_id, dept_id=did))
        role.updated_at = datetime.now()
        name = role.role_name
        await session.commit()
    await log_oper(operator=me, request=request, module="role", action="update",
                   target_type="role", target_id=role_id, target_name=name, detail=data)
    return {"success": True}


@router.delete("/oa/roles/{role_id}")
async def delete_role(
    role_id: str,
    request: Request,
    me: WikiOaUser = Depends(require_perm("oa:role:remove")),
):
    async with AsyncSessionLocal() as session:
        role = await session.get(WikiOaRole, role_id)
        if role is None or role.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
        if role.is_builtin:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="内置角色不可删除")
        role.del_flag = enums.DEL_DELETED
        role.updated_at = datetime.now()
        name = role.role_name
        await session.commit()
    await log_oper(operator=me, request=request, module="role", action="delete",
                   target_type="role", target_id=role_id, target_name=name)
    return {"success": True}


@router.get("/oa/roles/{role_id}/sources", dependencies=[Depends(require_perm("oa:role:list"))])
async def get_role_sources(role_id: str):
    async with AsyncSessionLocal() as session:
        ids = (
            await session.execute(
                select(WikiOaRoleSource.source_id).where(WikiOaRoleSource.role_id == role_id)
            )
        ).scalars().all()
        dept_ids = (
            await session.execute(
                select(WikiOaRoleDept.dept_id).where(WikiOaRoleDept.role_id == role_id)
            )
        ).scalars().all()
    return {"success": True, "sourceIds": list(ids), "deptIds": list(dept_ids)}


@router.put("/oa/roles/{role_id}/sources", dependencies=[Depends(require_perm("oa:role:assignPerm"))])
async def set_role_sources(role_id: str, data: dict = Body(...)):
    """全量覆盖角色的权限资源。"""
    source_ids = data.get("sourceIds") or []
    if not isinstance(source_ids, list):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="sourceIds 必须是数组")
    async with AsyncSessionLocal() as session:
        role = await session.get(WikiOaRole, role_id)
        if role is None or role.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
        valid = set(
            (
                await session.execute(
                    select(WikiOaSource.id).where(
                        WikiOaSource.id.in_(source_ids), WikiOaSource.del_flag == enums.DEL_NORMAL
                    )
                )
            ).scalars().all()
        )
        existing = (
            await session.execute(
                select(WikiOaRoleSource).where(WikiOaRoleSource.role_id == role_id)
            )
        ).scalars().all()
        existing_ids = {r.source_id for r in existing}
        for r in existing:
            if r.source_id not in valid:
                await session.delete(r)
        for sid in valid - existing_ids:
            session.add(WikiOaRoleSource(role_id=role_id, source_id=sid))
        await session.commit()
    return {"success": True}


@router.put("/oa/roles/{role_id}/data-scope", dependencies=[Depends(require_perm("oa:role:dataScope"))])
async def set_role_data_scope(role_id: str, data: dict = Body(...)):
    """设置数据范围;自定义(2)时同时覆盖 role_dept。"""
    scope = int(data.get("dataScope") or enums.SCOPE_SELF)
    if scope not in enums.DATA_SCOPES:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="数据范围非法")
    dept_ids = data.get("deptIds") or []
    async with AsyncSessionLocal() as session:
        role = await session.get(WikiOaRole, role_id)
        if role is None or role.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
        role.data_scope = scope
        role.updated_at = datetime.now()
        # 清空旧自定义部门
        for rd in (
            await session.execute(select(WikiOaRoleDept).where(WikiOaRoleDept.role_id == role_id))
        ).scalars().all():
            await session.delete(rd)
        if scope == enums.SCOPE_CUSTOM and isinstance(dept_ids, list):
            for did in set(dept_ids):
                session.add(WikiOaRoleDept(role_id=role_id, dept_id=did))
        await session.commit()
    return {"success": True}


# ==================================== 权限资源 ====================================

def _source_payload(s: WikiOaSource) -> dict:
    return {
        "id": s.id,
        "parentId": s.parent_id,
        "name": s.source_name,
        "type": s.source_type,
        "perm": s.perm,
        "path": s.route_path,
        "component": s.component,
        "icon": s.icon,
        "orderNum": s.order_num,
        "visible": bool(s.visible),
        "status": s.status,
    }


_AUTO_COMPS = ("__auto_interface_root__", "__auto_interface__")


@router.get("/oa/sources", dependencies=[Depends(require_perm("oa:source:list"))])
async def list_sources():
    """返回完整资源树:门户/系统/知识库 + 自动登记的「系统接口」分支(末尾)。"""
    async with AsyncSessionLocal() as session:
        rows = (
            await session.execute(
                select(WikiOaSource)
                .where(WikiOaSource.del_flag == enums.DEL_NORMAL)
                .order_by(WikiOaSource.order_num)
            )
        ).scalars().all()
    nodes = {s.id: {**_source_payload(s), "children": []} for s in rows}
    roots = []
    for node in nodes.values():
        parent = nodes.get(node["parentId"])
        (parent["children"] if parent else roots).append(node)
    return {"success": True, "items": roots}


@router.get("/oa/sources/flat", dependencies=[Depends(require_perm("oa:source:list"))])
async def list_sources_flat(types: str = ""):
    """按类型返回扁平资源列表(含自动登记的系统接口),供“资源权限”页类型筛选用。"""
    wanted = {t for t in types.split(",") if t} or set(enums.SOURCE_TYPES)
    async with AsyncSessionLocal() as session:
        rows = (
            await session.execute(
                select(WikiOaSource)
                .where(
                    WikiOaSource.del_flag == enums.DEL_NORMAL,
                    WikiOaSource.source_type.in_(list(wanted)),
                )
                .order_by(WikiOaSource.source_type, WikiOaSource.source_name)
            )
        ).scalars().all()
    return {"success": True, "items": [_source_payload(s) for s in rows]}


@router.post("/oa/sources/sync")
async def sync_sources(
    request: Request,
    me: WikiOaUser = Depends(require_perm("oa:source:list")),
):
    """一键同步「前端资源清单 + 后端接口」到资源表(幂等)。

    - 前端资源(目录/菜单/页面/按钮):以内置清单 seed._SOURCES 为准补全并剪除过期节点。
    - 后端接口:扫描全部路由自动登记为「系统接口」分支。
    二者启动时会自动同步;本接口用于出现问题时手动重新同步。
    """
    from src.services.oa.intercept import sync_interface_sources

    await ensure_rbac_seed()
    iface_count = await sync_interface_sources(request.app)
    async with AsyncSessionLocal() as session:
        total = (
            await session.execute(
                select(WikiOaSource.id).where(WikiOaSource.del_flag == enums.DEL_NORMAL)
            )
        ).scalars().all()
    await log_oper(operator=me, request=request, module="source", action="sync",
                   detail={"count": len(total), "interfaces": iface_count})
    return {"success": True, "count": len(total), "interfaces": iface_count}


@router.post("/oa/sources", dependencies=[Depends(require_perm("oa:source:add"))])
async def create_source(data: dict = Body(...)):
    name = (data.get("name") or "").strip()
    stype = (data.get("type") or "").strip()
    if not name or stype not in enums.SOURCE_TYPES:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="资源名称或类型非法")
    async with AsyncSessionLocal() as session:
        src = WikiOaSource(
            parent_id=(data.get("parentId") or None),
            source_name=name, source_type=stype,
            perm=(data.get("perm") or None),
            route_path=(data.get("path") or None),
            component=(data.get("component") or None),
            icon=(data.get("icon") or None),
            order_num=int(data.get("orderNum") or 0),
            visible=1 if data.get("visible", True) else 0,
            status=enums.STATUS_ACTIVE, del_flag=enums.DEL_NORMAL,
        )
        session.add(src)
        await session.commit()
        return {"success": True, "id": src.id}


@router.patch("/oa/sources/{source_id}", dependencies=[Depends(require_perm("oa:source:edit"))])
async def update_source(source_id: str, data: dict = Body(...)):
    async with AsyncSessionLocal() as session:
        src = await session.get(WikiOaSource, source_id)
        if src is None or src.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="资源不存在")
        if "name" in data:
            src.source_name = (data.get("name") or "").strip() or src.source_name
        if "type" in data and data["type"] in enums.SOURCE_TYPES:
            src.source_type = data["type"]
        if "perm" in data:
            src.perm = data.get("perm") or None
        if "path" in data:
            src.route_path = data.get("path") or None
        if "component" in data:
            src.component = data.get("component") or None
        if "icon" in data:
            src.icon = data.get("icon") or None
        if "orderNum" in data:
            src.order_num = int(data.get("orderNum") or 0)
        if "visible" in data:
            src.visible = 1 if data.get("visible") else 0
        if "status" in data and data["status"] in enums.STATUSES:
            src.status = data["status"]
        if "parentId" in data:
            src.parent_id = data.get("parentId") or None
        src.updated_at = datetime.now()
        await session.commit()
    return {"success": True}


@router.delete("/oa/sources/{source_id}", dependencies=[Depends(require_perm("oa:source:remove"))])
async def delete_source(source_id: str):
    async with AsyncSessionLocal() as session:
        src = await session.get(WikiOaSource, source_id)
        if src is None or src.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="资源不存在")
        child = (
            await session.execute(
                select(WikiOaSource.id).where(
                    WikiOaSource.parent_id == source_id, WikiOaSource.del_flag == enums.DEL_NORMAL
                )
            )
        ).scalars().first()
        if child:
            raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="请先删除子资源")
        src.del_flag = enums.DEL_DELETED
        src.updated_at = datetime.now()
        await session.commit()
    return {"success": True}