Files
opc-backend/seed_permissions.py

60 lines
2.8 KiB
Python
Raw Permalink Normal View History

import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
django.setup()
from users.models import Permission, Role, RolePermission
def seed():
print("--- 正在初始化权限节点数据 ---")
# 账号权限组 (Account)
account_group, _ = Permission.objects.get_or_create(
code="menu:account", defaults={"name": "账号与用户权限组", "type": "MENU"}
)
# 子节点
users_menu, _ = Permission.objects.get_or_create(
code="menu:account:users", defaults={"name": "用户管理菜单", "type": "MENU", "parent": account_group, "path": "/admin/users"}
)
roles_menu, _ = Permission.objects.get_or_create(
code="menu:account:roles", defaults={"name": "角色管理菜单", "type": "MENU", "parent": account_group, "path": "/admin/roles"}
)
perms_menu, _ = Permission.objects.get_or_create(
code="menu:account:permissions", defaults={"name": "权限树管理菜单", "type": "MENU", "parent": account_group, "path": "/admin/permissions"}
)
# API 权限
Permission.objects.get_or_create(code="api:users:read", defaults={"name": "查询用户列表", "type": "API", "parent": users_menu, "method": "GET", "path": "/api/v1/users/"})
Permission.objects.get_or_create(code="api:users:write", defaults={"name": "新增/编辑用户", "type": "API", "parent": users_menu, "method": "POST", "path": "/api/v1/users/"})
Permission.objects.get_or_create(code="api:users:delete", defaults={"name": "删除用户", "type": "API", "parent": users_menu, "method": "DELETE", "path": "/api/v1/users/{id}/"})
# 业务权限组 (Business)
biz_group, _ = Permission.objects.get_or_create(
code="menu:business", defaults={"name": "业务管理权限组", "type": "MENU"}
)
tasks_menu, _ = Permission.objects.get_or_create(
code="menu:business:tasks", defaults={"name": "全站任务管理", "type": "MENU", "parent": biz_group, "path": "/admin/tasks"}
)
cert_menu, _ = Permission.objects.get_or_create(
code="menu:business:certs", defaults={"name": "资质审核管理", "type": "MENU", "parent": biz_group, "path": "/admin/certifications"}
)
ent_menu, _ = Permission.objects.get_or_create(
code="menu:business:enterprises", defaults={"name": "入驻企业管理", "type": "MENU", "parent": biz_group, "path": "/admin/enterprises"}
)
print("权限节点初始化完成!")
# 为 ADMIN 角色自动分配所有权限
admin_role = Role.objects.filter(code='ADMIN').first()
if admin_role:
print("正在为 ADMIN 角色自动挂载所有权限...")
all_perms = Permission.objects.all()
for p in all_perms:
RolePermission.objects.get_or_create(role=admin_role, permission=p)
print("ADMIN 角色权限挂载完毕!")
if __name__ == '__main__':
seed()