394 lines
16 KiB
Python
394 lines
16 KiB
Python
"""权限管理:角色(菜单授权矩阵)、用户(挂角色 / 启停 / 重置密码)、在线会话、操作日志。
|
||
|
||
进入这一页需要「权限管理」授权,写操作还要 rw,由 security.guard 拦。
|
||
两条自我保护规则:
|
||
· 内置「管理员」角色永远保留权限管理授权,也删不掉;
|
||
· 不让最后一个可管理权限的账号被停用 / 删除 / 降权。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import audit, security
|
||
from ..constants import LEVELS, LEVEL_RANK, MENU_KEYS, MENU_LABELS, LEVEL_LABELS, merge_levels
|
||
from ..db import get_db
|
||
from ..models import AuditLog, Role, RoleMenu, User, UserRole, UserSession
|
||
from ..schemas import RoleIn, RolePatch, UserIn, UserPatch
|
||
|
||
router = APIRouter()
|
||
|
||
ADMIN_ROLE = "管理员"
|
||
|
||
|
||
def _role_menus(db: Session, role_id: int) -> dict[str, str]:
|
||
return {g.menu: g.level for g in db.query(RoleMenu).filter(RoleMenu.role_id == role_id).all()}
|
||
|
||
|
||
def _set_role_menus(db: Session, role: Role, menus: dict) -> None:
|
||
"""整体替换角色的菜单授权(矩阵里改一格也是整行覆盖)。"""
|
||
clean = security.normalize_menus(menus)
|
||
if role.is_builtin and role.name == ADMIN_ROLE:
|
||
clean["rbac"] = "rw" # 管理员不能被自己关在门外
|
||
# 逐条 ORM 删除后再插:批量 delete() 会把旧对象留在 identity map 里,
|
||
# 主键相同时 SQLAlchemy 会告警,甚至让随后的读取拿到改之前的旧级别
|
||
for row in db.query(RoleMenu).filter(RoleMenu.role_id == role.id).all():
|
||
db.delete(row)
|
||
db.flush()
|
||
for menu, level in clean.items():
|
||
db.add(RoleMenu(role_id=role.id, menu=menu, level=level))
|
||
db.commit()
|
||
|
||
|
||
def _set_user_roles(db: Session, user: User, role_ids: list[int]) -> None:
|
||
ids = sorted({int(r) for r in role_ids if r})
|
||
for rid in ids:
|
||
if db.get(Role, rid) is None:
|
||
raise HTTPException(status_code=400, detail="角色不存在")
|
||
# 同 _set_role_menus:先 ORM 删除再插入,避免主键冲突的旧对象残留在 identity map
|
||
for row in db.query(UserRole).filter(UserRole.user_id == user.id).all():
|
||
db.delete(row)
|
||
db.flush()
|
||
for rid in ids:
|
||
db.add(UserRole(user_id=user.id, role_id=rid))
|
||
db.commit()
|
||
|
||
|
||
def _menus_of_role_ids(db: Session, role_ids) -> dict[str, str]:
|
||
"""预判:这几个角色挂上去之后用户会拿到什么权限(用于改角色前的自我保护判断)。"""
|
||
maps = []
|
||
for rid in {int(r) for r in role_ids if r}:
|
||
role = db.get(Role, rid)
|
||
if role is not None:
|
||
maps.append(_role_menus(db, role.id))
|
||
return merge_levels(*maps)
|
||
|
||
|
||
def _rbac_managers(db: Session, exclude_id: int | None = None) -> int:
|
||
"""还有几个可用账号拥有「权限管理 · 可编辑」。"""
|
||
n = 0
|
||
for u in db.query(User).filter(User.active.is_(True)).all():
|
||
if exclude_id is not None and u.id == exclude_id:
|
||
continue
|
||
if u.menus.get("rbac") == "rw":
|
||
n += 1
|
||
return n
|
||
|
||
|
||
def _effective_role_ids(user: User, role_ids) -> list[int]:
|
||
"""没传角色 = 保持原样;传了 = 整体替换。"""
|
||
return [int(r) for r in role_ids] if role_ids is not None else [r.id for r in user.roles]
|
||
|
||
|
||
# ---------------------------------------------------------------------- 元信息
|
||
@router.get("/rbac/meta")
|
||
def meta():
|
||
return {
|
||
"menus": [{"key": k, "label": v} for k, v in
|
||
[(k, MENU_LABELS[k]) for k in MENU_KEYS]],
|
||
"levels": [{"value": v, "label": LEVEL_LABELS[v]} for v in ("rw", "ro", "")],
|
||
"actions": [
|
||
{"value": "create", "label": "新增"},
|
||
{"value": "update", "label": "修改"},
|
||
{"value": "delete", "label": "删除"},
|
||
{"value": "login", "label": "登录"},
|
||
{"value": "logout", "label": "退出"},
|
||
{"value": "password", "label": "改密码"},
|
||
{"value": "revoke", "label": "下线"},
|
||
],
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------- 角色
|
||
@router.get("/rbac/roles")
|
||
def list_roles(db: Session = Depends(get_db)):
|
||
users = db.query(User).all()
|
||
counts: dict[int, int] = {}
|
||
for u in users:
|
||
for r in u.roles:
|
||
counts[r.id] = counts.get(r.id, 0) + 1
|
||
out = []
|
||
for r in db.query(Role).order_by(Role.id).all():
|
||
d = r.to_dict()
|
||
d["user_count"] = counts.get(r.id, 0)
|
||
out.append(d)
|
||
return out
|
||
|
||
|
||
@router.post("/rbac/roles")
|
||
def create_role(body: RoleIn, request: Request, db: Session = Depends(get_db)):
|
||
name = (body.name or "").strip()
|
||
if not name:
|
||
raise HTTPException(status_code=400, detail="角色名不能为空")
|
||
if db.query(Role).filter(Role.name == name).count():
|
||
raise HTTPException(status_code=400, detail=f"角色「{name}」已存在")
|
||
role = Role(name=name[:64], description=(body.description or "").strip() or None,
|
||
is_builtin=False)
|
||
db.add(role)
|
||
db.commit()
|
||
_set_role_menus(db, role, body.menus)
|
||
audit.note(request, f"新建角色「{role.name}」")
|
||
return role.to_dict()
|
||
|
||
|
||
@router.patch("/rbac/roles/{rid}")
|
||
def update_role(rid: int, body: RolePatch, request: Request, db: Session = Depends(get_db)):
|
||
role = db.get(Role, rid)
|
||
if role is None:
|
||
raise HTTPException(status_code=404, detail="角色不存在")
|
||
if body.name is not None:
|
||
name = body.name.strip()
|
||
if not name:
|
||
raise HTTPException(status_code=400, detail="角色名不能为空")
|
||
if db.query(Role).filter(Role.name == name, Role.id != rid).count():
|
||
raise HTTPException(status_code=400, detail=f"角色「{name}」已存在")
|
||
if role.is_builtin and role.name == ADMIN_ROLE and name != ADMIN_ROLE:
|
||
raise HTTPException(status_code=400, detail="内置「管理员」角色不能改名")
|
||
role.name = name[:64]
|
||
if body.description is not None:
|
||
role.description = body.description.strip() or None
|
||
db.commit()
|
||
if body.menus is not None:
|
||
before = _role_menus(db, rid)
|
||
_set_role_menus(db, role, body.menus)
|
||
db.expire(role)
|
||
if before != _role_menus(db, rid):
|
||
_kick_role_users(db, rid) # 权限变了,让他们重新登录取新权限
|
||
audit.note(request, f"调整角色「{role.name}」的菜单授权,已下线该角色下的用户")
|
||
else:
|
||
audit.note(request, f"修改角色「{role.name}」")
|
||
else:
|
||
audit.note(request, f"修改角色「{role.name}」")
|
||
return role.to_dict()
|
||
|
||
|
||
def _kick_role_users(db: Session, rid: int) -> None:
|
||
for uid in [u.id for u in db.query(User).all()
|
||
if any(r.id == rid for r in u.roles)]:
|
||
security.revoke_all(db, uid)
|
||
|
||
|
||
@router.delete("/rbac/roles/{rid}")
|
||
def delete_role(rid: int, request: Request, me: User = Depends(security.current_user),
|
||
db: Session = Depends(get_db)):
|
||
role = db.get(Role, rid)
|
||
if role is None:
|
||
raise HTTPException(status_code=404, detail="角色不存在")
|
||
if role.is_builtin:
|
||
raise HTTPException(status_code=400, detail="内置角色不能删除,可以改它的菜单授权")
|
||
if any(r.id == rid for r in me.roles):
|
||
raise HTTPException(status_code=400, detail="不能删除自己正在使用的角色")
|
||
if db.query(UserRole).filter(UserRole.role_id == rid).count():
|
||
raise HTTPException(status_code=400, detail="该角色下还有用户,请先给他们换角色")
|
||
db.delete(role) # Role.grants 是 delete-orphan,菜单授权行跟着一起删
|
||
db.commit()
|
||
audit.note(request, f"删除角色「{role.name}」")
|
||
return {"ok": True}
|
||
|
||
|
||
# ---------------------------------------------------------------------- 用户
|
||
@router.get("/rbac/users")
|
||
def list_users(db: Session = Depends(get_db)):
|
||
online = {}
|
||
for s in db.query(UserSession).all():
|
||
online[s.user_id] = online.get(s.user_id, 0) + 1
|
||
out = []
|
||
for u in db.query(User).order_by(User.id).all():
|
||
d = u.to_dict()
|
||
d["online"] = online.get(u.id, 0)
|
||
out.append(d)
|
||
return out
|
||
|
||
|
||
@router.post("/rbac/users")
|
||
def create_user(body: UserIn, request: Request, db: Session = Depends(get_db)):
|
||
name = (body.name or "").strip()
|
||
username = (body.username or "").strip()
|
||
password = (body.password or "").strip()
|
||
if not name or not username:
|
||
raise HTTPException(status_code=400, detail="姓名和登录账号都要填")
|
||
if len(password) < 6:
|
||
raise HTTPException(status_code=400, detail="初始密码至少 6 位")
|
||
if db.query(User).filter(User.username == username).count():
|
||
raise HTTPException(status_code=400, detail=f"登录账号「{username}」已存在")
|
||
role_ids = body.role_ids or _default_role_ids(db)
|
||
if not role_ids:
|
||
raise HTTPException(status_code=400, detail="至少要给账号挂一个角色")
|
||
pw_hash, salt = security.hash_password(password)
|
||
user = User(name=name[:64], username=username[:64], password_hash=pw_hash,
|
||
password_salt=salt, active=bool(body.active))
|
||
db.add(user)
|
||
db.commit()
|
||
_set_user_roles(db, user, role_ids)
|
||
audit.note(request, f"新建账号 {user.username}({user.name})")
|
||
return user.to_dict()
|
||
|
||
|
||
def _default_role_ids(db: Session) -> list[int]:
|
||
role = db.query(Role).filter(Role.name == "部门成员").one_or_none()
|
||
return [role.id] if role else []
|
||
|
||
|
||
@router.patch("/rbac/users/{uid}")
|
||
def update_user(uid: int, body: UserPatch, request: Request,
|
||
me: User = Depends(security.current_user), db: Session = Depends(get_db)):
|
||
user = db.get(User, uid)
|
||
if user is None:
|
||
raise HTTPException(status_code=404, detail="用户不存在")
|
||
|
||
# 先把所有校验跑完再落库:否则角色/密码改了一半时后面报 400,库里已经是新值了
|
||
name = None
|
||
if body.name is not None:
|
||
name = body.name.strip()
|
||
if not name:
|
||
raise HTTPException(status_code=400, detail="姓名不能为空")
|
||
new_ids: list[int] | None = None
|
||
if body.role_ids is not None:
|
||
ids = _effective_role_ids(user, body.role_ids)
|
||
if sorted(ids) != sorted(r.id for r in user.roles):
|
||
if user.id == me.id:
|
||
raise HTTPException(status_code=400, detail="不能修改自己的角色")
|
||
after = _menus_of_role_ids(db, ids)
|
||
if user.menus.get("rbac") == "rw" and after.get("rbac") != "rw" \
|
||
and not _rbac_managers(db, exclude_id=user.id):
|
||
raise HTTPException(status_code=400, detail="系统里要保留一个可管理权限的账号")
|
||
new_ids = ids
|
||
password = (body.password or "").strip()
|
||
if password and len(password) < 6:
|
||
raise HTTPException(status_code=400, detail="新密码至少 6 位")
|
||
if body.active is not None and user.id == me.id and not body.active:
|
||
raise HTTPException(status_code=400, detail="不能停用自己的账号")
|
||
if body.active is False and user.menus.get("rbac") == "rw" \
|
||
and not _rbac_managers(db, exclude_id=user.id):
|
||
raise HTTPException(status_code=400, detail="系统里要保留一个可管理权限的账号")
|
||
|
||
changed_role = False
|
||
if name:
|
||
user.name = name[:64]
|
||
if new_ids is not None:
|
||
_set_user_roles(db, user, new_ids)
|
||
changed_role = True
|
||
if password:
|
||
user.password_hash, user.password_salt = security.hash_password(password)
|
||
security.revoke_all(db, user.id) # 改密即下线,旧 token 立即失效
|
||
if body.active is not None:
|
||
user.active = bool(body.active)
|
||
if not user.active:
|
||
security.revoke_all(db, user.id)
|
||
db.commit()
|
||
if changed_role:
|
||
security.revoke_all(db, user.id) # 权限变了,强制重新登录
|
||
db.expire(user)
|
||
what = []
|
||
if name:
|
||
what.append("改名")
|
||
if new_ids is not None:
|
||
what.append("改角色")
|
||
if password:
|
||
what.append("重置密码")
|
||
if body.active is not None:
|
||
what.append("启用" if body.active else "停用")
|
||
audit.note(request, f"修改账号 {user.username}" + (f":{'、'.join(what)}" if what else ""))
|
||
return user.to_dict()
|
||
|
||
|
||
@router.delete("/rbac/users/{uid}")
|
||
def delete_user(uid: int, request: Request, me: User = Depends(security.current_user),
|
||
db: Session = Depends(get_db)):
|
||
user = db.get(User, uid)
|
||
if user is None:
|
||
raise HTTPException(status_code=404, detail="用户不存在")
|
||
if user.id == me.id:
|
||
raise HTTPException(status_code=400, detail="不能删除自己,可以换一个角色或让别人删")
|
||
username = user.username
|
||
if not db.query(User).filter(User.active.is_(True), User.id != uid).count():
|
||
raise HTTPException(status_code=400, detail="至少要保留一个可用账号")
|
||
if user.active and user.menus.get("rbac") == "rw" and not _rbac_managers(db, exclude_id=user.id):
|
||
raise HTTPException(status_code=400, detail="系统里要保留一个可管理权限的账号")
|
||
security.revoke_all(db, user.id)
|
||
db.delete(user) # user_roles 是 secondary 关联,删用户时 SQLAlchemy 自己会清
|
||
db.commit()
|
||
audit.note(request, f"删除账号 {username}")
|
||
return {"ok": True}
|
||
|
||
|
||
@router.post("/rbac/users/{uid}/revoke")
|
||
def revoke_user_sessions(uid: int, request: Request, db: Session = Depends(get_db)):
|
||
user = db.get(User, uid)
|
||
if user is None:
|
||
raise HTTPException(status_code=404, detail="用户不存在")
|
||
security.revoke_all(db, uid)
|
||
audit.note(request, f"强制下线 {user.username}")
|
||
return {"ok": True, "revoked": True}
|
||
|
||
|
||
# ---------------------------------------------------------------------- 在线会话
|
||
@router.get("/rbac/sessions")
|
||
def list_sessions(db: Session = Depends(get_db)):
|
||
users = {u.id: u for u in db.query(User).all()}
|
||
out = []
|
||
for s in db.query(UserSession).order_by(UserSession.created_at.desc()).all():
|
||
u = users.get(s.user_id)
|
||
if u is None:
|
||
continue
|
||
d = s.to_dict()
|
||
d["token"] = s.token # 下线要用真实 token,列表里只展示 token_hint
|
||
d.update({"user_id": u.id, "name": u.name, "username": u.username})
|
||
out.append(d)
|
||
return out
|
||
|
||
|
||
@router.delete("/rbac/sessions/{token}")
|
||
def revoke_session(token: str, request: Request, db: Session = Depends(get_db)):
|
||
sess = db.get(UserSession, token)
|
||
if sess is None:
|
||
raise HTTPException(status_code=404, detail="会话不存在或已失效")
|
||
target = db.get(User, sess.user_id)
|
||
db.delete(sess)
|
||
db.commit()
|
||
audit.note(request, f"下线一个登录会话:{target.username if target else '已删除的账号'}")
|
||
return {"ok": True}
|
||
|
||
|
||
# ---------------------------------------------------------------------- 操作日志
|
||
@router.get("/rbac/logs")
|
||
def list_logs(
|
||
username: str | None = None,
|
||
menu: str | None = None,
|
||
action: str | None = None,
|
||
days: int = Query(30, ge=1, le=365),
|
||
limit: int = Query(200, ge=1, le=1000),
|
||
offset: int = Query(0, ge=0),
|
||
db: Session = Depends(get_db),
|
||
):
|
||
from datetime import timedelta
|
||
|
||
from ..models import now as _now
|
||
|
||
q = db.query(AuditLog).filter(AuditLog.created_at >= _now() - timedelta(days=days))
|
||
if username:
|
||
q = q.filter(AuditLog.username == username)
|
||
if menu:
|
||
q = q.filter(AuditLog.menu == menu)
|
||
if action:
|
||
q = q.filter(AuditLog.action == action)
|
||
total = q.count()
|
||
rows = q.order_by(AuditLog.id.desc()).offset(offset).limit(limit).all()
|
||
return {"total": total, "items": [r.to_dict() for r in rows]}
|
||
|
||
|
||
@router.delete("/rbac/logs")
|
||
def clear_logs(days: int = Query(0, ge=0), db: Session = Depends(get_db)):
|
||
"""清空操作日志;days > 0 时只清 N 天以前的。"""
|
||
from datetime import timedelta
|
||
|
||
from ..models import now as _now
|
||
|
||
q = db.query(AuditLog)
|
||
if days > 0:
|
||
q = q.filter(AuditLog.created_at < _now() - timedelta(days=days))
|
||
n = q.count()
|
||
q.delete(synchronize_session=False)
|
||
db.commit()
|
||
return {"ok": True, "deleted": n}
|