fix(auth): 创建通配符权限前先创建 permission 记录

修复 initRole 中外键约束错误:
- 在创建 scope:*:* 的 role_permission 前,先确保 permission 记录存在
- 避免 Error 1452 外键约束失败
v3
veypi 1 week ago
parent 33eabfa013
commit 54bb58048e

@ -347,9 +347,28 @@ func (a *appAuth) initRole(roleCode string) error {
} }
} }
// 为通配符权限创建特殊记录 // 为通配符权限创建记录
if hasWildcard { if hasWildcard {
wildcardPermID := fmt.Sprintf("%s:*:*", a.scope) 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 var count int64
cfg.DB().Model(&models.RolePermission{}). cfg.DB().Model(&models.RolePermission{}).
Where("role_id = ? AND permission_id = ?", role.ID, wildcardPermID). Where("role_id = ? AND permission_id = ?", role.ID, wildcardPermID).

Loading…
Cancel
Save