From 54bb58048ef8a739beea1c7e93f7fdbefa728a9d Mon Sep 17 00:00:00 2001 From: veypi Date: Sun, 15 Feb 2026 19:47:45 +0800 Subject: [PATCH] =?UTF-8?q?fix(auth):=20=E5=88=9B=E5=BB=BA=E9=80=9A?= =?UTF-8?q?=E9=85=8D=E7=AC=A6=E6=9D=83=E9=99=90=E5=89=8D=E5=85=88=E5=88=9B?= =?UTF-8?q?=E5=BB=BA=20permission=20=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复 initRole 中外键约束错误: - 在创建 scope:*:* 的 role_permission 前,先确保 permission 记录存在 - 避免 Error 1452 外键约束失败 --- auth/auth.go | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/auth/auth.go b/auth/auth.go index 784f148..533d806 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -347,9 +347,28 @@ func (a *appAuth) initRole(roleCode string) error { } } - // 为通配符权限创建特殊记录 + // 为通配符权限创建记录 if hasWildcard { wildcardPermID := fmt.Sprintf("%s:*:*", a.scope) + + // 先确保通配符 permission 存在 + var perm models.Permission + err := cfg.DB().Where("id = ?", wildcardPermID).First(&perm).Error + if err != nil { + // 创建通配符 permission + perm = models.Permission{ + ID: wildcardPermID, + Scope: a.scope, + Resource: "*", + Action: "*", + Description: fmt.Sprintf("%s wildcard permission", a.scope), + } + if err := cfg.DB().Create(&perm).Error; err != nil { + return fmt.Errorf("failed to create wildcard permission: %w", err) + } + } + + // 创建 role_permission 关联 var count int64 cfg.DB().Model(&models.RolePermission{}). Where("role_id = ? AND permission_id = ?", role.ID, wildcardPermID).