unis_hrms/app/api/v1/system.py

372 lines
15 KiB
Python

"""系统管理: 用户 / 角色 / 权限 / 菜单 / 公告 / 通知 / 操作日志."""
from __future__ import annotations
from typing import Annotated
from fastapi import APIRouter, Depends, Query
from sqlalchemy import delete, func, select, update
from ...core.deps import AuthContext, Session, get_auth_context, require_perm
from ...core.errors import AppError
from ...core.permissions import MODULES
from ...core.security import hash_password
from ..crud import CrudSpec, build_router
from ...models.rbac import (
Announcement, Menu, Notification, OperationLog, Permission,
RefreshToken, Role, RolePermission, User, UserRole,
)
from ...schemas.common import Message
from ...schemas.system import (
AnnouncementCreate, AnnouncementRead, AnnouncementUpdate,
AssignPermissionsPayload, AssignRolesPayload, MenuCreate, MenuRead, MenuUpdate,
NotificationRead, OperationLogRead, ResetPasswordPayload,
RoleCreate, RoleRead, RoleUpdate, UserCreate, UserRead, UserUpdate,
)
router = APIRouter()
def _row_to_dict(obj, extra: dict | None = None) -> dict:
data = {c.name: getattr(obj, c.name) for c in obj.__table__.columns}
data.update(extra or {})
return data
# ------------------------------------------------------------------- 用户账号
async def attach_user_roles(session, rows: list[User]) -> None:
if not rows:
return
ids = [r.id for r in rows]
pairs = (
await session.execute(
select(UserRole.user_id, Role.id, Role.code, Role.name, Role.data_scope)
.join(Role, Role.id == UserRole.role_id)
.where(UserRole.user_id.in_(ids))
)
).all()
grouped: dict[int, list[dict]] = {i: [] for i in ids}
for user_id, rid, code, name, scope in pairs:
grouped[user_id].append({"id": rid, "code": code, "name": name, "data_scope": scope})
for row in rows:
row.__dict__["roles"] = grouped.get(row.id, [])
row.__dict__["role_ids"] = [r["id"] for r in grouped.get(row.id, [])]
def read_user(obj: User) -> dict:
return _row_to_dict(obj, {"roles": obj.__dict__.get("roles") or [],
"role_ids": obj.__dict__.get("role_ids") or []})
async def _user_before(action, data, obj, auth, session):
if action == "create":
if not data.get("password"):
raise AppError("请设置初始密码", "password_required")
data["password_hash"] = hash_password(data.pop("password"))
data.pop("password", None)
# role_ids 不是 user 表的列:先摘出来暂存,等 after_write 拿到 user_id 再写关联表,
# 否则「新建用户时勾选的角色」会被静默丢弃,账号建出来什么模块都打不开。
role_ids = data.pop("role_ids", None)
if role_ids is not None:
auth.__dict__["_pending_role_ids"] = list(role_ids)
if data.get("is_superuser") and not auth.user.is_superuser:
raise AppError("只有超级管理员可以授予超级权限", "forbidden", 403)
return data
async def _user_after(action, obj, auth, session):
"""落库 _user_before 暂存的角色绑定(新增与编辑用户共用)。"""
role_ids = auth.__dict__.pop("_pending_role_ids", None)
if role_ids is None:
return
role_ids = sorted({int(rid) for rid in role_ids})
if role_ids:
found = (await session.execute(select(Role.id).where(Role.id.in_(role_ids)))).scalars().all()
if len(found) != len(role_ids):
raise AppError("包含不存在的角色", "bad_role")
await session.execute(delete(UserRole).where(UserRole.user_id == obj.id))
for rid in role_ids:
session.add(UserRole(user_id=obj.id, role_id=rid))
await session.flush()
# 角色变了 => 旧的刷新令牌作废,避免长时间沿用过期权限组合
await session.execute(delete(RefreshToken).where(RefreshToken.user_id == obj.id))
async def _user_delete(obj, auth, session):
if obj.is_superuser:
raise AppError("超级管理员账号不可删除", "protected")
await session.execute(delete(UserRole).where(UserRole.user_id == obj.id))
await session.execute(delete(RefreshToken).where(RefreshToken.user_id == obj.id))
async def _users_filter_hook(stmt, filters, session):
"""``?role_ids=1,2`` —— 角色不是 user 表字段,用关联表子查询过滤。"""
ids = [int(v) for v in str(filters.get("role_ids") or "").split(",") if v.strip().isdigit()]
if not ids:
return stmt
sub = select(UserRole.user_id).where(UserRole.role_id.in_(ids))
return stmt.where(User.id.in_(sub))
async def _users_list_hook(stmt, auth, session):
if not auth.can("system:user:read") or auth.data_scope == "self":
return stmt.where(User.id == auth.user.id)
return stmt
users_custom = APIRouter()
@users_custom.get("/me", summary="当前用户(兼容路径)", include_in_schema=False)
async def users_me(session: Session, auth: AuthCtxDep):
await attach_user_roles(session, [auth.user])
return read_user(auth.user)
async def _role_before(action, data, obj, auth, session):
if obj is not None and obj.is_builtin:
if data.get("code") and data["code"] != obj.code:
raise AppError("内置角色的编码不允许修改", "protected")
if data.get("is_active") is False:
raise AppError("内置角色不允许停用", "protected")
if data.get("data_scope") and data["data_scope"] not in ("all", "dept_tree", "dept", "self"):
raise AppError("数据范围取值不合法", "bad_scope")
return data
async def _role_delete(obj, auth, session):
if obj.is_builtin:
raise AppError("内置角色不可删除", "protected")
users = (
await session.execute(select(func.count()).select_from(UserRole).where(UserRole.role_id == obj.id))
).scalar_one()
if users:
raise AppError(f"该角色下还有 {users} 个用户,请先解除关联", "in_use")
await session.execute(delete(RolePermission).where(RolePermission.role_id == obj.id))
async def attach_role_counts(session, rows: list[Role]) -> None:
if not rows:
return
ids = [r.id for r in rows]
perm_counts = dict(
(await session.execute(
select(RolePermission.role_id, func.count()).where(RolePermission.role_id.in_(ids))
.group_by(RolePermission.role_id)
)).all()
)
user_counts = dict(
(await session.execute(
select(UserRole.role_id, func.count()).where(UserRole.role_id.in_(ids))
.group_by(UserRole.role_id)
)).all()
)
for row in rows:
row.__dict__["permission_count"] = int(perm_counts.get(row.id, 0))
row.__dict__["user_count"] = int(user_counts.get(row.id, 0))
def read_role(obj: Role) -> dict:
return _row_to_dict(obj, {"permission_count": obj.__dict__.get("permission_count", 0),
"user_count": obj.__dict__.get("user_count", 0)})
AuthCtxDep = Annotated[AuthContext, Depends(get_auth_context)]
user_router = build_router(
CrudSpec(
model=User, create=UserCreate, update=UserUpdate, read=UserRead,
module="system", resource="user", label="用户", prefix="/users", tag="系统管理",
search_fields=("username", "name", "phone", "email"), filters=("is_active", "employee_id"),
order_by="id", order="asc", label_field="name", after_read=attach_user_roles,
before_write=_user_before, after_write=_user_after, extra_query=("role_ids",),
filter_hook=_users_filter_hook, on_delete=_user_delete, list_hook=_users_list_hook,
),
preface=[users_custom],
)
@user_router.post("/{item_id}/roles", response_model=Message, summary="分配角色")
async def assign_roles(
item_id: int, payload: AssignRolesPayload, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("system:user:assign_role"))],
):
user = await session.get(User, item_id)
if not user:
raise AppError("用户不存在", "not_found", 404)
roles = (await session.execute(select(Role).where(Role.id.in_(payload.role_ids)))).scalars().all()
if len(roles) != len(set(payload.role_ids)):
raise AppError("包含不存在的角色", "bad_role")
await session.execute(delete(UserRole).where(UserRole.user_id == item_id))
for role in roles:
session.add(UserRole(user_id=item_id, role_id=role.id))
await session.execute(delete(RefreshToken).where(RefreshToken.user_id == item_id))
await session.commit()
return Message(message=f"已为 {user.name} 配置 {len(roles)} 个角色")
@user_router.post("/{item_id}/reset-password", response_model=Message, summary="重置密码")
async def reset_password(
item_id: int, payload: ResetPasswordPayload, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("system:user:reset"))],
):
user = await session.get(User, item_id)
if not user:
raise AppError("用户不存在", "not_found", 404)
user.password_hash = hash_password(payload.password)
await session.execute(delete(RefreshToken).where(RefreshToken.user_id == item_id))
await session.commit()
return Message(message=f"{user.name} 的密码已重置")
router.include_router(user_router)
role_router = build_router(
CrudSpec(
model=Role, create=RoleCreate, update=RoleUpdate, read=RoleRead,
module="system", resource="role", label="角色", prefix="/roles", tag="系统管理",
search_fields=("code", "name"), filters=("is_active", "data_scope"),
order_by="sort", order="asc",
after_read=attach_role_counts, before_write=_role_before, on_delete=_role_delete,
)
)
@role_router.get("/{item_id}/permissions", summary="角色的权限 ID")
async def role_permissions(
item_id: int, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("system:role:read"))],
):
ids = (
await session.execute(select(RolePermission.permission_id).where(RolePermission.role_id == item_id))
).scalars().all()
return {"role_id": item_id, "permission_ids": list(ids)}
@role_router.put("/{item_id}/permissions", response_model=Message, summary="保存角色权限")
async def save_role_permissions(
item_id: int, payload: AssignPermissionsPayload, session: Session,
auth: Annotated[AuthContext, Depends(require_perm("system:role:assign"))],
):
role = await session.get(Role, item_id)
if not role:
raise AppError("角色不存在", "not_found", 404)
if role.code == "super_admin":
raise AppError("超级管理员默认拥有全部权限,无需配置", "protected")
valid = set(
(await session.execute(select(Permission.id).where(Permission.id.in_(payload.permission_ids))))
.scalars().all()
)
if set(payload.permission_ids) - valid:
raise AppError("包含无效的权限项", "bad_permission")
await session.execute(delete(RolePermission).where(RolePermission.role_id == item_id))
for pid in payload.permission_ids:
session.add(RolePermission(role_id=item_id, permission_id=pid))
if payload.data_scope:
role.data_scope = payload.data_scope
await session.commit()
return Message(message=f"角色「{role.name}」的权限已更新")
router.include_router(role_router)
@router.get("/permissions", summary="权限清单(按模块分组)")
async def permission_catalogue(session: Session, auth: AuthCtxDep):
rows = (
await session.execute(select(Permission).order_by(Permission.module, Permission.resource))
).scalars().all()
grouped: dict[str, dict] = {}
for perm in rows:
module_meta = MODULES.get(perm.module, {})
resource_meta = module_meta.get("resources", {}).get(perm.resource, {})
module = grouped.setdefault(
perm.module,
{"module": perm.module, "label": module_meta.get("label", perm.module),
"icon": module_meta.get("icon"), "resources": {}},
)
resource = module["resources"].setdefault(
perm.resource,
{"resource": perm.resource, "label": resource_meta.get("label", perm.resource), "actions": []},
)
resource["actions"].append({"id": perm.id, "code": perm.code, "name": perm.name,
"action": perm.action})
for module in grouped.values():
module["resources"] = list(module["resources"].values())
return {"modules": list(grouped.values()), "total": len(rows)}
# ------------------------------------------------------------------ 菜单导航
menu_router = build_router(
CrudSpec(
model=Menu, create=MenuCreate, update=MenuUpdate, read=MenuRead,
module="system", resource="menu", label="菜单", prefix="/menus", tag="系统管理",
search_fields=("name", "path"), filters=("platform", "visible"), order_by="sort", order="asc",
)
)
@menu_router.get("/tree", summary="菜单树(管理视图)")
async def menu_tree(
session: Session,
auth: Annotated[AuthContext, Depends(require_perm("system:menu:read"))],
platform: str = Query("web"),
):
rows = (
await session.execute(select(Menu).where(Menu.platform == platform).order_by(Menu.sort, Menu.id))
).scalars().all()
nodes = {m.id: {**_row_to_dict(m), "children": []} for m in rows}
roots = []
for node in nodes.values():
parent = nodes.get(node["parent_id"])
(parent["children"] if parent else roots).append(node)
return roots
router.include_router(menu_router)
# --------------------------------------------------------------- 公告 / 通知
router.include_router(build_router(CrudSpec(
model=Announcement, create=AnnouncementCreate, update=AnnouncementUpdate, read=AnnouncementRead,
module="system", resource="announcement", label="公告", prefix="/announcements", tag="系统管理",
search_fields=("title", "content"), filters=("category", "level", "is_published", "target"),
order_by="published_at", order="desc",
)))
async def _notification_scope(stmt, auth, session):
return stmt.where(Notification.user_id == auth.user.id)
notification_router = build_router(CrudSpec(
model=Notification, create=NotificationRead, update=NotificationRead, read=NotificationRead,
module="selfservice", resource="home", label="站内消息", prefix="/notifications", tag="员工自助",
search_fields=("title",), filters=("category", "is_read"), order_by="created_at", order="desc",
list_hook=_notification_scope, write=False, options=False,
))
@notification_router.post("/read-all", response_model=Message, summary="全部标记已读")
async def notifications_read_all(session: Session, auth: AuthCtxDep):
await session.execute(
update(Notification)
.where(Notification.user_id == auth.user.id, Notification.is_read.is_(False))
.values(is_read=True)
)
await session.commit()
return Message(message="已全部标记为已读")
router.include_router(notification_router)
# ------------------------------------------------------------------ 操作日志
router.include_router(build_router(CrudSpec(
model=OperationLog, create=OperationLogRead, update=OperationLogRead, read=OperationLogRead,
module="system", resource="log", label="操作日志", prefix="/logs", tag="系统管理",
search_fields=("username", "module", "action", "path"), filters=("user_id", "module", "action", "method", "status_code"),
date_range_fields=("created_at",), order_by="created_at", order="desc",
write=False, deletable=False, options=False,
)))