diff --git a/acs.go b/acs.go index 228cce0..e2ea14b 100644 --- a/acs.go +++ b/acs.go @@ -6,7 +6,11 @@ import ( "gorm.io/gorm" ) -var Enforcer *casbin.Enforcer +var Enforcer enforcer + +type enforcer struct { + *casbin.Enforcer +} type Config struct { Db *gorm.DB @@ -24,7 +28,7 @@ func InitEnforcer(config Config) error { return err } // 通过mysql适配器新建一个enforcer - Enforcer, err = casbin.NewEnforcer(config.ModelFile, adapter) + Enforcer.Enforcer, err = casbin.NewEnforcer(config.ModelFile, adapter) if err != nil { return err } @@ -32,3 +36,27 @@ func InitEnforcer(config Config) error { Enforcer.EnableLog(config.Log) 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 +}