添加多层级用户角色判断

master
kanade 3 years ago
parent 14d190bf52
commit ee9777baaa

@ -6,7 +6,11 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
var Enforcer *casbin.Enforcer var Enforcer enforcer
type enforcer struct {
*casbin.Enforcer
}
type Config struct { type Config struct {
Db *gorm.DB Db *gorm.DB
@ -24,7 +28,7 @@ func InitEnforcer(config Config) error {
return err return err
} }
// 通过mysql适配器新建一个enforcer // 通过mysql适配器新建一个enforcer
Enforcer, err = casbin.NewEnforcer(config.ModelFile, adapter) Enforcer.Enforcer, err = casbin.NewEnforcer(config.ModelFile, adapter)
if err != nil { if err != nil {
return err return err
} }
@ -32,3 +36,27 @@ func InitEnforcer(config Config) error {
Enforcer.EnableLog(config.Log) Enforcer.EnableLog(config.Log)
return nil return nil
} }
// HasRoleDeepForUser @Title 递归判断用户角色
func (e *enforcer) HasRoleDeepForUser(name string, role string, domain ...string) (bool, error) {
roles, err := e.GetRolesForUser(name, domain...)
if err != nil {
return false, err
}
hasRole := false
for _, r := range roles {
if r == role {
hasRole = true
break
} else {
hasRole, err := e.HasRoleDeepForUser(name, r, domain...)
if err != nil {
return false, err
}
if hasRole {
return hasRole, nil
}
}
}
return hasRole, nil
}

Loading…
Cancel
Save