From ee9777baaac4347c9de06b5caf2c1f52152417b3 Mon Sep 17 00:00:00 2001 From: kanade Date: Sat, 18 Sep 2021 09:52:54 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=A4=9A=E5=B1=82=E7=BA=A7?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E8=A7=92=E8=89=B2=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- acs.go | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) 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 +}