第一次提交

This commit is contained in:
rjb
2026-01-19 00:09:36 +08:00
parent de4b5059e9
commit 6674060f2f
191 changed files with 40940 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""
创建数据库脚本
"""
import pymysql
import sys
import os
# 添加项目路径
sys.path.insert(0, '/app')
def create_database():
"""创建数据库"""
# 数据库连接信息(从环境变量或直接配置)
host = 'gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com'
port = 24936
user = 'root'
password = '!Rjb12191'
db_name = 'agent_db'
try:
# 连接到MySQL服务器不指定数据库
conn = pymysql.connect(
host=host,
port=port,
user=user,
password=password
)
cursor = conn.cursor()
# 创建数据库
cursor.execute(f"CREATE DATABASE IF NOT EXISTS {db_name} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
print(f"✅ 数据库 {db_name} 创建成功")
conn.commit()
conn.close()
return True
except Exception as e:
print(f"❌ 创建数据库失败: {e}")
return False
if __name__ == '__main__':
success = create_database()
sys.exit(0 if success else 1)

View File

@@ -0,0 +1,339 @@
#!/usr/bin/env python3
"""
生成Agent假数据
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sqlalchemy.orm import Session
from app.core.database import SessionLocal
from app.models.agent import Agent
from app.models.user import User
import random
from datetime import datetime, timedelta
# 假数据模板
AGENT_TEMPLATES = [
{
"name": "智能客服助手",
"description": "自动处理客户咨询提供7x24小时在线服务支持多轮对话和智能转接",
"status": "running"
},
{
"name": "数据分析Agent",
"description": "自动分析业务数据,生成可视化报表,支持多种数据源接入",
"status": "published"
},
{
"name": "内容生成助手",
"description": "基于LLM的内容创作工具支持文章、报告、营销文案等多种类型",
"status": "published"
},
{
"name": "邮件自动回复",
"description": "智能识别邮件内容,自动生成回复建议,提高工作效率",
"status": "draft"
},
{
"name": "代码审查Agent",
"description": "自动审查代码质量检测潜在bug和安全漏洞提供改进建议",
"status": "published"
},
{
"name": "会议纪要生成器",
"description": "自动记录会议内容,提取关键信息,生成结构化会议纪要",
"status": "running"
},
{
"name": "翻译助手",
"description": "支持多语言翻译,保持上下文连贯性,适用于文档和对话翻译",
"status": "published"
},
{
"name": "知识库问答",
"description": "基于企业知识库的智能问答系统,快速检索和回答专业问题",
"status": "running"
},
{
"name": "文档摘要生成",
"description": "自动提取文档关键信息,生成简洁准确的摘要,支持多种文档格式",
"status": "draft"
},
{
"name": "情感分析Agent",
"description": "分析文本情感倾向,监控用户反馈,识别潜在问题",
"status": "published"
},
{
"name": "任务调度助手",
"description": "智能分配和调度任务,优化资源利用,提高团队协作效率",
"status": "stopped"
},
{
"name": "API集成Agent",
"description": "连接多个外部API实现数据同步和业务流程自动化",
"status": "published"
},
{
"name": "报表自动化",
"description": "定时生成各类业务报表,自动发送给相关人员,支持多种数据源",
"status": "running"
},
{
"name": "智能推荐系统",
"description": "基于用户行为和偏好,提供个性化推荐,提升用户体验",
"status": "draft"
},
{
"name": "异常检测Agent",
"description": "实时监控系统运行状态,自动检测异常并发送告警通知",
"status": "published"
}
]
def generate_workflow_config(agent_type: str) -> dict:
"""生成工作流配置"""
# 根据不同的Agent类型生成不同的工作流配置
base_configs = {
"客服": {
"nodes": [
{
"id": "start-1",
"type": "start",
"position": {"x": 100, "y": 100},
"data": {"label": "开始"}
},
{
"id": "llm-1",
"type": "llm",
"position": {"x": 300, "y": 100},
"data": {
"label": "LLM处理",
"model": "gpt-4",
"prompt": "你是一个专业的客服助手,请友好地回答用户的问题。"
}
},
{
"id": "condition-1",
"type": "condition",
"position": {"x": 500, "y": 100},
"data": {
"label": "判断是否需要转人工",
"condition": "{{需要人工}}"
}
},
{
"id": "end-1",
"type": "end",
"position": {"x": 700, "y": 100},
"data": {"label": "结束"}
}
],
"edges": [
{"id": "e1", "source": "start-1", "target": "llm-1"},
{"id": "e2", "source": "llm-1", "target": "condition-1"},
{"id": "e3", "source": "condition-1", "target": "end-1"}
]
},
"数据分析": {
"nodes": [
{
"id": "start-1",
"type": "start",
"position": {"x": 100, "y": 100},
"data": {"label": "开始"}
},
{
"id": "data-source-1",
"type": "data_source",
"position": {"x": 300, "y": 100},
"data": {
"label": "数据源",
"source_type": "database"
}
},
{
"id": "process-1",
"type": "process",
"position": {"x": 500, "y": 100},
"data": {
"label": "数据处理",
"operation": "aggregate"
}
},
{
"id": "llm-1",
"type": "llm",
"position": {"x": 700, "y": 100},
"data": {
"label": "生成分析报告",
"model": "gpt-4"
}
},
{
"id": "end-1",
"type": "end",
"position": {"x": 900, "y": 100},
"data": {"label": "结束"}
}
],
"edges": [
{"id": "e1", "source": "start-1", "target": "data-source-1"},
{"id": "e2", "source": "data-source-1", "target": "process-1"},
{"id": "e3", "source": "process-1", "target": "llm-1"},
{"id": "e4", "source": "llm-1", "target": "end-1"}
]
},
"默认": {
"nodes": [
{
"id": "start-1",
"type": "start",
"position": {"x": 100, "y": 100},
"data": {"label": "开始"}
},
{
"id": "llm-1",
"type": "llm",
"position": {"x": 300, "y": 100},
"data": {
"label": "LLM处理",
"model": "gpt-3.5-turbo",
"prompt": "请处理用户请求。"
}
},
{
"id": "end-1",
"type": "end",
"position": {"x": 500, "y": 100},
"data": {"label": "结束"}
}
],
"edges": [
{"id": "e1", "source": "start-1", "target": "llm-1"},
{"id": "e2", "source": "llm-1", "target": "end-1"}
]
}
}
# 根据名称判断类型
if "客服" in agent_type:
return base_configs["客服"]
elif "数据" in agent_type:
return base_configs["数据分析"]
else:
return base_configs["默认"]
def generate_fake_agents(db: Session, username: str = "admin", count: int = None):
"""生成假数据"""
print("=" * 60)
print("生成Agent假数据")
print("=" * 60)
print()
# 查找用户
user = db.query(User).filter(User.username == username).first()
if not user:
print(f"❌ 未找到用户 '{username}',请先创建该用户")
return
print(f"✅ 找到用户: {user.username} (ID: {user.id})")
print()
# 确定要生成的数量
if count is None:
count = len(AGENT_TEMPLATES)
else:
count = min(count, len(AGENT_TEMPLATES))
print(f"📝 将生成 {count} 个Agent...")
print()
created_count = 0
skipped_count = 0
for i, template in enumerate(AGENT_TEMPLATES[:count]):
# 检查是否已存在同名Agent
existing = db.query(Agent).filter(
Agent.name == template["name"],
Agent.user_id == user.id
).first()
if existing:
print(f"⏭️ 跳过: {template['name']} (已存在)")
skipped_count += 1
continue
# 生成工作流配置
workflow_config = generate_workflow_config(template["name"])
# 随机生成创建时间过去30天内
days_ago = random.randint(0, 30)
created_at = datetime.now() - timedelta(days=days_ago)
updated_at = created_at + timedelta(hours=random.randint(1, 72))
# 创建Agent
agent = Agent(
name=template["name"],
description=template["description"],
workflow_config=workflow_config,
status=template["status"],
user_id=user.id,
version=random.randint(1, 5),
created_at=created_at,
updated_at=updated_at
)
db.add(agent)
created_count += 1
print(f"✅ 创建: {template['name']} (状态: {template['status']})")
# 提交事务
try:
db.commit()
print()
print("=" * 60)
print(f"✅ 成功生成 {created_count} 个Agent")
if skipped_count > 0:
print(f"⏭️ 跳过 {skipped_count} 个已存在的Agent")
print("=" * 60)
except Exception as e:
db.rollback()
print()
print("=" * 60)
print(f"❌ 生成失败: {e}")
print("=" * 60)
raise
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="生成Agent假数据")
parser.add_argument(
"--username",
type=str,
default="admin",
help="创建Agent的用户名默认: admin"
)
parser.add_argument(
"--count",
type=int,
default=None,
help="要生成的Agent数量默认: 生成所有模板)"
)
args = parser.parse_args()
db = SessionLocal()
try:
generate_fake_agents(db, username=args.username, count=args.count)
except Exception as e:
print(f"❌ 发生错误: {e}")
import traceback
traceback.print_exc()
finally:
db.close()

View File

@@ -0,0 +1,359 @@
"""
生成测试工作流 - 包含多个节点的完整工作流
用于验证工作流功能
"""
import sys
import os
from pathlib import Path
import json
from datetime import datetime
# 添加项目根目录到路径
sys.path.insert(0, str(Path(__file__).parent.parent))
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
from app.models.workflow import Workflow
from app.models.user import User
def generate_test_workflow():
"""生成测试工作流"""
# 创建数据库连接
engine = create_engine(settings.DATABASE_URL)
Session = sessionmaker(bind=engine)
session = Session()
try:
# 获取第一个用户
user = session.query(User).first()
if not user:
print("❌ 错误:数据库中没有用户,请先创建用户")
return
print(f"✅ 使用用户: {user.username} (ID: {user.id})")
# 定义测试工作流的节点
nodes = [
{
"id": "start-1",
"type": "start",
"position": {"x": 100, "y": 100},
"data": {
"label": "开始",
"description": "工作流开始节点"
}
},
{
"id": "llm-1",
"type": "llm",
"position": {"x": 300, "y": 100},
"data": {
"label": "LLM处理",
"provider": "deepseek",
"model": "deepseek-chat",
"prompt": "请分析用户输入的内容:{input}\n\n要求:\n1. 提取关键信息\n2. 判断内容类型\n3. 返回JSON格式{\"type\": \"类型\", \"keywords\": [\"关键词1\", \"关键词2\"], \"sentiment\": \"情感\"}",
"temperature": 0.7,
"max_tokens": 1500
}
},
{
"id": "condition-1",
"type": "condition",
"position": {"x": 500, "y": 100},
"data": {
"label": "判断类型",
"condition": "JSON.parse(input).type === 'question'"
}
},
{
"id": "llm-2",
"type": "llm",
"position": {"x": 700, "y": 50},
"data": {
"label": "回答问题",
"provider": "deepseek",
"model": "deepseek-chat",
"prompt": "用户提出了一个问题,请提供详细、准确的回答。\n\n问题:{input}\n\n要求:\n1. 回答要准确、专业\n2. 如果涉及技术问题,提供代码示例\n3. 回答要友好、易懂",
"temperature": 0.7,
"max_tokens": 2000
}
},
{
"id": "llm-3",
"type": "llm",
"position": {"x": 700, "y": 150},
"data": {
"label": "处理其他",
"provider": "deepseek",
"model": "deepseek-chat",
"prompt": "用户输入了其他类型的内容,请进行适当的处理。\n\n内容:{input}\n\n要求:\n1. 理解用户意图\n2. 提供合适的响应\n3. 保持友好和专业",
"temperature": 0.7,
"max_tokens": 1500
}
},
{
"id": "transform-1",
"type": "transform",
"position": {"x": 900, "y": 100},
"data": {
"label": "格式化输出",
"transform": "const data = typeof input === 'string' ? JSON.parse(input) : input;\nreturn JSON.stringify({\n success: true,\n result: data,\n timestamp: new Date().toISOString()\n}, null, 2);"
}
},
{
"id": "end-1",
"type": "end",
"position": {"x": 1100, "y": 100},
"data": {
"label": "结束",
"description": "工作流结束节点"
}
}
]
# 定义边(连接)
edges = [
{
"id": "edge-start-llm1",
"source": "start-1",
"target": "llm-1",
"sourceHandle": "bottom",
"targetHandle": "top",
"type": "smoothstep"
},
{
"id": "edge-llm1-condition",
"source": "llm-1",
"target": "condition-1",
"sourceHandle": "bottom",
"targetHandle": "top",
"type": "smoothstep"
},
{
"id": "edge-condition-llm2",
"source": "condition-1",
"target": "llm-2",
"sourceHandle": "top",
"targetHandle": "left",
"type": "smoothstep",
"label": "是问题"
},
{
"id": "edge-condition-llm3",
"source": "condition-1",
"target": "llm-3",
"sourceHandle": "bottom",
"targetHandle": "left",
"type": "smoothstep",
"label": "其他"
},
{
"id": "edge-llm2-transform",
"source": "llm-2",
"target": "transform-1",
"sourceHandle": "right",
"targetHandle": "left",
"type": "smoothstep"
},
{
"id": "edge-llm3-transform",
"source": "llm-3",
"target": "transform-1",
"sourceHandle": "right",
"targetHandle": "left",
"type": "smoothstep"
},
{
"id": "edge-transform-end",
"source": "transform-1",
"target": "end-1",
"sourceHandle": "right",
"targetHandle": "left",
"type": "smoothstep"
}
]
# 检查是否已存在同名工作流
existing = session.query(Workflow).filter(
Workflow.name == "智能问答工作流(测试)",
Workflow.user_id == user.id
).first()
if existing:
print(f"⏭️ 工作流已存在,更新现有工作流...")
existing.nodes = nodes
existing.edges = edges
existing.description = "一个包含多个节点的测试工作流用于验证工作流功能。包含开始节点、LLM节点、条件判断、数据转换、结束节点"
existing.status = "draft"
existing.updated_at = datetime.now()
workflow = existing
else:
# 创建新工作流
workflow = Workflow(
name="智能问答工作流(测试)",
description="一个包含多个节点的测试工作流用于验证工作流功能。包含开始节点、LLM节点、条件判断、数据转换、结束节点",
nodes=nodes,
edges=edges,
status="draft",
user_id=user.id
)
session.add(workflow)
session.commit()
session.refresh(workflow)
print(f"\n✅ 测试工作流创建成功!")
print(f" - 工作流ID: {workflow.id}")
print(f" - 工作流名称: {workflow.name}")
print(f" - 节点数量: {len(nodes)}")
print(f" - 连接数量: {len(edges)}")
print(f"\n📋 节点列表:")
for i, node in enumerate(nodes, 1):
print(f" {i}. {node['data']['label']} ({node['type']})")
print(f"\n🔗 连接关系:")
for i, edge in enumerate(edges, 1):
source_node = next(n for n in nodes if n['id'] == edge['source'])
target_node = next(n for n in nodes if n['id'] == edge['target'])
label = edge.get('label', '')
print(f" {i}. {source_node['data']['label']}{target_node['data']['label']} {label}")
print(f"\n💡 使用说明:")
print(f" 1. 在工作流列表中点击'编辑'按钮")
print(f" 2. 可以查看和修改工作流配置")
print(f" 3. 点击'运行'按钮测试工作流")
print(f" 4. 输入测试数据,例如:'什么是Python'")
except Exception as e:
session.rollback()
print(f"❌ 创建失败: {e}")
import traceback
traceback.print_exc()
finally:
session.close()
def generate_simple_test_workflow():
"""生成简单的测试工作流(仅包含基本节点)"""
# 创建数据库连接
engine = create_engine(settings.DATABASE_URL)
Session = sessionmaker(bind=engine)
session = Session()
try:
# 获取第一个用户
user = session.query(User).first()
if not user:
print("❌ 错误:数据库中没有用户,请先创建用户")
return
print(f"✅ 使用用户: {user.username} (ID: {user.id})")
# 定义简单工作流的节点
nodes = [
{
"id": "start-1",
"type": "start",
"position": {"x": 100, "y": 100},
"data": {
"label": "开始",
"description": "工作流开始"
}
},
{
"id": "llm-1",
"type": "llm",
"position": {"x": 300, "y": 100},
"data": {
"label": "LLM处理",
"provider": "deepseek",
"model": "deepseek-chat",
"prompt": "请回答用户的问题:{input}\n\n要求:\n1. 回答要准确、专业\n2. 语言要友好、易懂\n3. 如果问题不清楚,可以询问更多信息",
"temperature": 0.7,
"max_tokens": 1500
}
},
{
"id": "end-1",
"type": "end",
"position": {"x": 500, "y": 100},
"data": {
"label": "结束",
"description": "工作流结束"
}
}
]
# 定义边(连接)
edges = [
{
"id": "edge-start-llm",
"source": "start-1",
"target": "llm-1",
"sourceHandle": "bottom",
"targetHandle": "top",
"type": "smoothstep"
},
{
"id": "edge-llm-end",
"source": "llm-1",
"target": "end-1",
"sourceHandle": "right",
"targetHandle": "left",
"type": "smoothstep"
}
]
# 检查是否已存在同名工作流
existing = session.query(Workflow).filter(
Workflow.name == "简单问答工作流(测试)",
Workflow.user_id == user.id
).first()
if existing:
print(f"⏭️ 工作流已存在,更新现有工作流...")
existing.nodes = nodes
existing.edges = edges
existing.description = "一个简单的测试工作流包含开始、LLM处理、结束三个节点"
existing.status = "draft"
existing.updated_at = datetime.now()
workflow = existing
else:
# 创建新工作流
workflow = Workflow(
name="简单问答工作流(测试)",
description="一个简单的测试工作流包含开始、LLM处理、结束三个节点",
nodes=nodes,
edges=edges,
status="draft",
user_id=user.id
)
session.add(workflow)
session.commit()
session.refresh(workflow)
print(f"\n✅ 简单测试工作流创建成功!")
print(f" - 工作流ID: {workflow.id}")
print(f" - 工作流名称: {workflow.name}")
print(f" - 节点数量: {len(nodes)}")
print(f" - 连接数量: {len(edges)}")
except Exception as e:
session.rollback()
print(f"❌ 创建失败: {e}")
import traceback
traceback.print_exc()
finally:
session.close()
if __name__ == '__main__':
print("=" * 60)
print("生成复杂测试工作流(包含条件判断)")
print("=" * 60)
generate_test_workflow()
print("\n" + "=" * 60)
print("生成简单测试工作流(仅基本节点)")
print("=" * 60)
generate_simple_test_workflow()

File diff suppressed because it is too large Load Diff

190
backend/scripts/init_rbac_data.py Executable file
View File

@@ -0,0 +1,190 @@
#!/usr/bin/env python3
"""
初始化RBAC数据
创建系统角色和权限
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.core.database import SessionLocal
from app.models.permission import Role, Permission
import uuid
# 系统角色定义
SYSTEM_ROLES = [
{
"name": "admin",
"description": "系统管理员,拥有所有权限",
"is_system": True
},
{
"name": "developer",
"description": "开发者可以创建和管理工作流、Agent",
"is_system": True
},
{
"name": "viewer",
"description": "查看者,只能查看工作流和执行记录",
"is_system": True
},
{
"name": "operator",
"description": "操作员,可以执行工作流,但不能修改",
"is_system": True
}
]
# 权限定义
PERMISSIONS = [
# 工作流权限
{"name": "工作流-创建", "code": "workflow:create", "resource": "workflow", "action": "create", "description": "创建工作流"},
{"name": "工作流-查看", "code": "workflow:read", "resource": "workflow", "action": "read", "description": "查看工作流"},
{"name": "工作流-更新", "code": "workflow:update", "resource": "workflow", "action": "update", "description": "更新工作流"},
{"name": "工作流-删除", "code": "workflow:delete", "resource": "workflow", "action": "delete", "description": "删除工作流"},
{"name": "工作流-执行", "code": "workflow:execute", "resource": "workflow", "action": "execute", "description": "执行工作流"},
{"name": "工作流-分享", "code": "workflow:share", "resource": "workflow", "action": "share", "description": "分享工作流"},
# Agent权限
{"name": "Agent-创建", "code": "agent:create", "resource": "agent", "action": "create", "description": "创建Agent"},
{"name": "Agent-查看", "code": "agent:read", "resource": "agent", "action": "read", "description": "查看Agent"},
{"name": "Agent-更新", "code": "agent:update", "resource": "agent", "action": "update", "description": "更新Agent"},
{"name": "Agent-删除", "code": "agent:delete", "resource": "agent", "action": "delete", "description": "删除Agent"},
{"name": "Agent-执行", "code": "agent:execute", "resource": "agent", "action": "execute", "description": "执行Agent"},
{"name": "Agent-部署", "code": "agent:deploy", "resource": "agent", "action": "deploy", "description": "部署Agent"},
# 执行权限
{"name": "执行-查看", "code": "execution:read", "resource": "execution", "action": "read", "description": "查看执行记录"},
{"name": "执行-取消", "code": "execution:cancel", "resource": "execution", "action": "cancel", "description": "取消执行"},
# 数据源权限
{"name": "数据源-创建", "code": "data_source:create", "resource": "data_source", "action": "create", "description": "创建数据源"},
{"name": "数据源-查看", "code": "data_source:read", "resource": "data_source", "action": "read", "description": "查看数据源"},
{"name": "数据源-更新", "code": "data_source:update", "resource": "data_source", "action": "update", "description": "更新数据源"},
{"name": "数据源-删除", "code": "data_source:delete", "resource": "data_source", "action": "delete", "description": "删除数据源"},
# 模型配置权限
{"name": "模型配置-创建", "code": "model_config:create", "resource": "model_config", "action": "create", "description": "创建模型配置"},
{"name": "模型配置-查看", "code": "model_config:read", "resource": "model_config", "action": "read", "description": "查看模型配置"},
{"name": "模型配置-更新", "code": "model_config:update", "resource": "model_config", "action": "update", "description": "更新模型配置"},
{"name": "模型配置-删除", "code": "model_config:delete", "resource": "model_config", "action": "delete", "description": "删除模型配置"},
# 权限管理权限
{"name": "权限-管理", "code": "permission:manage", "resource": "permission", "action": "manage", "description": "管理权限和角色"},
]
# 角色权限映射
ROLE_PERMISSIONS = {
"admin": ["*"], # 所有权限
"developer": [
"workflow:create", "workflow:read", "workflow:update", "workflow:delete", "workflow:execute", "workflow:share",
"agent:create", "agent:read", "agent:update", "agent:delete", "agent:execute", "agent:deploy",
"execution:read", "execution:cancel",
"data_source:create", "data_source:read", "data_source:update", "data_source:delete",
"model_config:create", "model_config:read", "model_config:update", "model_config:delete"
],
"viewer": [
"workflow:read",
"agent:read",
"execution:read",
"data_source:read",
"model_config:read"
],
"operator": [
"workflow:read", "workflow:execute",
"agent:read", "agent:execute",
"execution:read", "execution:cancel"
]
}
def init_rbac_data():
"""初始化RBAC数据"""
db = SessionLocal()
try:
print("=" * 60)
print("初始化RBAC数据")
print("=" * 60)
print()
# 创建权限
print("创建权限...")
permission_map = {}
for perm_data in PERMISSIONS:
existing = db.query(Permission).filter(Permission.code == perm_data["code"]).first()
if existing:
print(f" 权限已存在: {perm_data['code']}")
permission_map[perm_data["code"]] = existing
else:
permission = Permission(
id=str(uuid.uuid4()),
name=perm_data["name"],
code=perm_data["code"],
resource=perm_data["resource"],
action=perm_data["action"],
description=perm_data["description"]
)
db.add(permission)
permission_map[perm_data["code"]] = permission
print(f" ✅ 创建权限: {perm_data['code']}")
db.commit()
print()
# 创建角色
print("创建角色...")
role_map = {}
for role_data in SYSTEM_ROLES:
existing = db.query(Role).filter(Role.name == role_data["name"]).first()
if existing:
print(f" 角色已存在: {role_data['name']}")
role_map[role_data["name"]] = existing
else:
role = Role(
id=str(uuid.uuid4()),
name=role_data["name"],
description=role_data["description"],
is_system=role_data["is_system"]
)
db.add(role)
role_map[role_data["name"]] = role
print(f" ✅ 创建角色: {role_data['name']}")
db.commit()
print()
# 分配权限给角色
print("分配权限给角色...")
for role_name, permission_codes in ROLE_PERMISSIONS.items():
role = role_map.get(role_name)
if not role:
continue
if permission_codes == ["*"]:
# 管理员拥有所有权限
role.permissions = list(permission_map.values())
print(f"{role_name}: 分配所有权限")
else:
# 分配指定权限
permissions = [permission_map[code] for code in permission_codes if code in permission_map]
role.permissions = permissions
print(f"{role_name}: 分配 {len(permissions)} 个权限")
db.commit()
print()
print("=" * 60)
print("✅ RBAC数据初始化完成")
print("=" * 60)
except Exception as e:
db.rollback()
print(f"❌ 初始化失败: {e}")
import traceback
traceback.print_exc()
finally:
db.close()
if __name__ == "__main__":
init_rbac_data()

72
backend/scripts/set_admin.py Executable file
View File

@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""
设置admin用户为管理员
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.core.database import SessionLocal
from app.models.user import User
from app.models.permission import Role
def set_admin():
"""设置admin用户为管理员"""
db = SessionLocal()
try:
print("=" * 60)
print("设置admin用户为管理员")
print("=" * 60)
print()
# 查找admin用户
admin_user = db.query(User).filter(User.username == "admin").first()
if not admin_user:
print("❌ 未找到admin用户请先创建admin用户")
return
print(f"找到用户: {admin_user.username} (ID: {admin_user.id})")
print(f"当前角色: {admin_user.role}")
print()
# 设置role字段为admin
admin_user.role = "admin"
print("✅ 已将role字段设置为admin")
# 如果存在admin角色也分配给用户
admin_role = db.query(Role).filter(Role.name == "admin").first()
if admin_role:
# 检查用户是否已经有admin角色
if admin_role not in admin_user.roles:
admin_user.roles.append(admin_role)
print("✅ 已分配admin角色给用户")
else:
print(" 用户已有admin角色")
else:
print(" admin角色不存在可能需要先运行init_rbac_data.py")
db.commit()
print()
print("=" * 60)
print("✅ admin用户已设置为管理员")
print("=" * 60)
print()
print("用户信息:")
print(f" 用户名: {admin_user.username}")
print(f" 邮箱: {admin_user.email}")
print(f" 角色: {admin_user.role}")
if admin_user.roles:
print(f" RBAC角色: {', '.join([r.name for r in admin_user.roles])}")
except Exception as e:
db.rollback()
print(f"❌ 设置失败: {e}")
import traceback
traceback.print_exc()
finally:
db.close()
if __name__ == "__main__":
set_admin()