You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.2 KiB
63 lines
1.2 KiB
package acs
|
|
|
|
import (
|
|
"github.com/casbin/casbin/v2"
|
|
"github.com/casbin/gorm-adapter/v3"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var Enforcer enforcer
|
|
|
|
type enforcer struct {
|
|
*casbin.Enforcer
|
|
}
|
|
|
|
type Config struct {
|
|
Db *gorm.DB
|
|
ModelFile string
|
|
Prefix string
|
|
TableName string
|
|
Log bool
|
|
}
|
|
|
|
// InitEnforcer @Title 初始化
|
|
func InitEnforcer(config Config) error {
|
|
// mysql 适配器
|
|
adapter, err := gormadapter.NewAdapterByDBUseTableName(config.Db, config.Prefix, config.TableName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// 通过mysql适配器新建一个enforcer
|
|
Enforcer.Enforcer, err = casbin.NewEnforcer(config.ModelFile, adapter)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// 日志记录
|
|
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
|
|
}
|