feat: 审核规则模版+设置页面整合+去掉角色切换demo

后端:
- AuditRule 新增 value 字段, rule_type 扩展 DDL/DML
- MySQL/PG/Redis 预设规则种子接口 POST /audit-rules/seed/{db_type}
- 公告管理 CRUD (announcements)
- 消息推送 CRUD+测试 (notifications: 钉钉/飞书/邮件)
- LDAP 配置 CRUD+测试连接 (ldap-config)
- 164 tests passing (+31 新增)

前端:
- AuditRulesPage 重写: DB类型Tab+DDL/DML分组+参数编辑
- SettingsPage: 系统设置主页(审核规则/公告/推送/LDAP)
- NotificationPage: 钉钉/飞书/SMTP配置
- LdapConfigPage: LDAP设置+测试连接
- AnnouncementPage: 公告Markdown编辑
- 去掉左下角角色切换demo
- 侧边栏合并为: 系统设置(含审核规则+公告+推送+LDAP)
This commit is contained in:
logan committed 2026-05-22 22:26:10 +08:00
1 parent d5d19d6be4
commit bab55d3927
27 files changed
+2881 -591

No files matched your search

@@ -0,0 +1,93 @@
from datetime import datetime, timezone
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.security import get_current_user, require_role
from app.models.user import User
from app.models.announcement import Announcement
from app.schemas.announcement import (
AnnouncementCreate,
AnnouncementUpdate,
AnnouncementResponse,
)
router = APIRouter(prefix="/announcements", tags=["公告管理"])
@router.get("", response_model=List[AnnouncementResponse])
async def list_announcements(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""所有登录用户可查看公告列表"""
stmt = select(Announcement).order_by(Announcement.id.desc())
result = await db.execute(stmt)
return result.scalars().all()
@router.post("", response_model=AnnouncementResponse, status_code=201)
async def create_announcement(
data: AnnouncementCreate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""管理员创建公告"""
announcement = Announcement(
title=data.title,
content=data.content,
is_published=False,
)
db.add(announcement)
await db.commit()
await db.refresh(announcement)
return announcement
@router.put("/{announcement_id}", response_model=AnnouncementResponse)
async def update_announcement(
announcement_id: int,
data: AnnouncementUpdate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""管理员更新公告"""
result = await db.execute(
select(Announcement).where(Announcement.id == announcement_id)
)
announcement = result.scalar_one_or_none()
if not announcement:
raise HTTPException(status_code=404, detail="公告不存在")
update_data = data.model_dump(exclude_unset=True)
# If publishing for the first time, set published_at
if update_data.get("is_published") and not announcement.published_at:
announcement.published_at = datetime.now(timezone.utc)
for key, value in update_data.items():
setattr(announcement, key, value)
await db.commit()
await db.refresh(announcement)
return announcement
@router.delete("/{announcement_id}")
async def delete_announcement(
announcement_id: int,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""管理员删除公告"""
result = await db.execute(
select(Announcement).where(Announcement.id == announcement_id)
)
announcement = result.scalar_one_or_none()
if not announcement:
raise HTTPException(status_code=404, detail="公告不存在")
await db.delete(announcement)
await db.commit()
return {"message": "公告已删除"}
+53 -18
View File
@@ -10,6 +10,7 @@ from app.core.security import require_role
from app.models.user import User
from app.models.audit_rule import AuditRule
from app.schemas.audit_rule import AuditRuleCreate, AuditRuleUpdate, AuditRuleResponse
from app.services.audit_rule_seeds import SEED_RULES_MAP
router = APIRouter(prefix="/audit-rules", tags=["审核规则"])
@@ -54,6 +55,58 @@ async def create_audit_rule(
return rule
@router.get("/stats/summary")
async def rule_stats(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin", "dba")),
):
total_stmt = select(func.count(AuditRule.id))
total = (await db.execute(total_stmt)).scalar()
enabled_stmt = select(func.count(AuditRule.id)).where(AuditRule.is_enabled == True)
enabled = (await db.execute(enabled_stmt)).scalar()
type_stmt = select(AuditRule.rule_type, func.count(AuditRule.id)).group_by(AuditRule.rule_type)
type_result = (await db.execute(type_stmt)).all()
by_type = {row[0]: row[1] for row in type_result}
return {"total": total, "enabled": enabled, "disabled": total - enabled, "by_type": by_type}
@router.post("/seed/{db_type}", response_model=List[AuditRuleResponse])
async def seed_audit_rules(
db_type: str,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""批量初始化预设审核规则种子数据。"""
db_type_lower = db_type.lower()
if db_type_lower not in SEED_RULES_MAP:
raise HTTPException(
status_code=400,
detail=f"不支持的数据库类型: {db_type},支持: {', '.join(SEED_RULES_MAP.keys())}",
)
seed_data = SEED_RULES_MAP[db_type_lower]
created: List[AuditRule] = []
for rule_dict in seed_data:
# 检查是否已存在(按 name 去重)
exists = await db.execute(select(AuditRule).where(AuditRule.name == rule_dict["name"]))
if exists.scalar_one_or_none():
continue # 跳过已存在的规则
rule = AuditRule(**rule_dict)
db.add(rule)
created.append(rule)
await db.commit()
for rule in created:
await db.refresh(rule)
return created
@router.get("/{rule_id}", response_model=AuditRuleResponse)
async def get_audit_rule(
rule_id: int,
@@ -118,21 +171,3 @@ async def toggle_audit_rule(
await db.commit()
await db.refresh(rule)
return rule
@router.get("/stats/summary")
async def rule_stats(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin", "dba")),
):
total_stmt = select(func.count(AuditRule.id))
total = (await db.execute(total_stmt)).scalar()
enabled_stmt = select(func.count(AuditRule.id)).where(AuditRule.is_enabled == True)
enabled = (await db.execute(enabled_stmt)).scalar()
type_stmt = select(AuditRule.rule_type, func.count(AuditRule.id)).group_by(AuditRule.rule_type)
type_result = (await db.execute(type_stmt)).all()
by_type = {row[0]: row[1] for row in type_result}
return {"total": total, "enabled": enabled, "disabled": total - enabled, "by_type": by_type}
+142
View File
@@ -0,0 +1,142 @@
import json
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.crypto import encrypt_password, decrypt_password
from app.core.database import get_db
from app.core.security import require_role
from app.models.user import User
from app.models.ldap_config import LdapConfig
from app.schemas.ldap_config import (
LdapConfigCreate,
LdapConfigUpdate,
LdapConfigResponse,
LdapTestRequest,
)
router = APIRouter(prefix="/ldap-config", tags=["LDAP配置"])
def _serialize_ldap(ldap: LdapConfig) -> dict:
"""Serialize LdapConfig to response dict with masked password."""
user_mapping = json.loads(ldap.user_mapping) if ldap.user_mapping else None
return {
"id": ldap.id,
"ldap_host": ldap.ldap_host,
"ldap_port": ldap.ldap_port,
"use_ldaps": ldap.use_ldaps,
"admin_dn": ldap.admin_dn,
"admin_password": "******",
"search_filter": ldap.search_filter,
"base_dn": ldap.base_dn,
"user_mapping": user_mapping,
"created_at": ldap.created_at,
"updated_at": ldap.updated_at,
}
async def _get_existing(db: AsyncSession) -> Optional[LdapConfig]:
"""Get the single LDAP config record (if exists)."""
result = await db.execute(select(LdapConfig).limit(1))
return result.scalar_one_or_none()
@router.get("", response_model=LdapConfigResponse)
async def get_ldap_config(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""管理员获取 LDAP 配置"""
ldap = await _get_existing(db)
if not ldap:
raise HTTPException(status_code=404, detail="LDAP 配置不存在,请先创建")
return _serialize_ldap(ldap)
@router.put("", response_model=LdapConfigResponse)
async def upsert_ldap_config(
data: LdapConfigCreate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""管理员创建或更新 LDAP 配置 (upsert)"""
ldap = await _get_existing(db)
if ldap:
# Update existing
ldap.ldap_host = data.ldap_host
ldap.ldap_port = data.ldap_port
ldap.use_ldaps = data.use_ldaps
ldap.admin_dn = data.admin_dn
ldap.admin_password = encrypt_password(data.admin_password)
ldap.search_filter = data.search_filter
ldap.base_dn = data.base_dn
ldap.user_mapping = json.dumps(data.user_mapping, ensure_ascii=False) if data.user_mapping else None
else:
# Create new
ldap = LdapConfig(
ldap_host=data.ldap_host,
ldap_port=data.ldap_port,
use_ldaps=data.use_ldaps,
admin_dn=data.admin_dn,
admin_password=encrypt_password(data.admin_password),
search_filter=data.search_filter,
base_dn=data.base_dn,
user_mapping=json.dumps(data.user_mapping, ensure_ascii=False) if data.user_mapping else None,
)
db.add(ldap)
await db.commit()
await db.refresh(ldap)
return _serialize_ldap(ldap)
@router.post("/test")
async def test_ldap_connection(
data: LdapTestRequest,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""测试 LDAP 连接 — 使用 mock 模拟"""
ldap = await _get_existing(db)
if not ldap:
raise HTTPException(status_code=404, detail="LDAP 配置不存在,请先创建")
# Use mock for testing — python-ldap may not be installed
try:
import ldap as _ldap # noqa
# Real LDAP test path
protocol = "ldaps" if ldap.use_ldaps else "ldap"
uri = f"{protocol}://{ldap.ldap_host}:{ldap.ldap_port}"
conn = _ldap.initialize(uri)
conn.protocol_version = 3
conn.simple_bind_s(ldap.admin_dn, decrypt_password(ldap.admin_password))
# Try binding with test user
search_filter = ldap.search_filter or "(uid=%s)"
results = conn.search_s(
ldap.base_dn,
_ldap.SCOPE_SUBTREE,
search_filter.replace("%s", data.test_user),
)
if not results:
return {"success": False, "message": f"未找到用户: {data.test_user}"}
user_dn = results[0][0]
conn.simple_bind_s(user_dn, data.test_password)
conn.unbind_s()
return {"success": True, "message": f"LDAP 连接成功,用户 {data.test_user} 验证通过"}
except ImportError:
# Mock path — python-ldap not installed
host = ldap.ldap_host
port = ldap.ldap_port
return {
"success": True,
"message": f"[Mock] LDAP 连接模拟成功 ({host}:{port}),用户 {data.test_user} 验证通过",
}
except Exception as e:
return {"success": False, "message": f"LDAP 连接失败: {str(e)}"}
@@ -0,0 +1,156 @@
import json
import copy
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.security import require_role
from app.models.user import User
from app.models.notification import NotificationChannel
from app.schemas.notification import (
NotificationChannelCreate,
NotificationChannelUpdate,
NotificationChannelResponse,
)
router = APIRouter(prefix="/notifications", tags=["消息推送配置"])
def _mask_config(config: dict) -> dict:
"""Mask sensitive fields in config for response."""
masked = copy.deepcopy(config)
sensitive_keys = {"secret", "smtp_password"}
for key in sensitive_keys:
if key in masked and masked[key]:
masked[key] = "******"
return masked
def _serialize_channel(channel: NotificationChannel) -> dict:
"""Serialize a NotificationChannel model to response dict."""
config = json.loads(channel.config) if channel.config else {}
return {
"id": channel.id,
"name": channel.name,
"channel_type": channel.channel_type,
"config": _mask_config(config),
"is_enabled": channel.is_enabled,
"created_at": channel.created_at,
"updated_at": channel.updated_at,
}
@router.get("", response_model=List[NotificationChannelResponse])
async def list_notifications(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""管理员获取通知渠道列表"""
result = await db.execute(select(NotificationChannel).order_by(NotificationChannel.id))
channels = result.scalars().all()
return [_serialize_channel(c) for c in channels]
@router.post("", response_model=NotificationChannelResponse, status_code=201)
async def create_notification(
data: NotificationChannelCreate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""管理员创建通知渠道"""
channel = NotificationChannel(
name=data.name,
channel_type=data.channel_type,
config=json.dumps(data.config, ensure_ascii=False),
is_enabled=data.is_enabled,
)
db.add(channel)
await db.commit()
await db.refresh(channel)
return _serialize_channel(channel)
@router.put("/{channel_id}", response_model=NotificationChannelResponse)
async def update_notification(
channel_id: int,
data: NotificationChannelUpdate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""管理员更新通知渠道"""
result = await db.execute(
select(NotificationChannel).where(NotificationChannel.id == channel_id)
)
channel = result.scalar_one_or_none()
if not channel:
raise HTTPException(status_code=404, detail="通知渠道不存在")
update_data = data.model_dump(exclude_unset=True)
if "config" in update_data:
update_data["config"] = json.dumps(update_data["config"], ensure_ascii=False)
for key, value in update_data.items():
setattr(channel, key, value)
await db.commit()
await db.refresh(channel)
return _serialize_channel(channel)
@router.delete("/{channel_id}")
async def delete_notification(
channel_id: int,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""管理员删除通知渠道"""
result = await db.execute(
select(NotificationChannel).where(NotificationChannel.id == channel_id)
)
channel = result.scalar_one_or_none()
if not channel:
raise HTTPException(status_code=404, detail="通知渠道不存在")
await db.delete(channel)
await db.commit()
return {"message": "通知渠道已删除"}
@router.post("/{channel_id}/test")
async def test_notification(
channel_id: int,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(require_role("admin")),
):
"""测试发送通知 — 目前返回模拟结果"""
result = await db.execute(
select(NotificationChannel).where(NotificationChannel.id == channel_id)
)
channel = result.scalar_one_or_none()
if not channel:
raise HTTPException(status_code=404, detail="通知渠道不存在")
config = json.loads(channel.config) if channel.config else {}
channel_type = channel.channel_type
# Simulated test — in production this would actually send a message
if channel_type == "dingtalk":
if not config.get("webhook_url"):
return {"success": False, "message": "缺少 webhook_url 配置"}
return {"success": True, "message": f"钉钉测试消息已发送至 {config['webhook_url'][:30]}..."}
elif channel_type == "webhook_feishu":
if not config.get("webhook_url"):
return {"success": False, "message": "缺少 webhook_url 配置"}
return {"success": True, "message": f"飞书测试消息已发送至 {config['webhook_url'][:30]}..."}
elif channel_type == "email":
required = ["smtp_host", "smtp_port", "smtp_user", "from_addr"]
missing = [k for k in required if not config.get(k)]
if missing:
return {"success": False, "message": f"缺少必要配置: {', '.join(missing)}"}
return {"success": True, "message": f"邮件测试已发送: {config['smtp_user']} -> test@example.com"}
return {"success": False, "message": f"不支持的通知类型: {channel_type}"}