casbin官网
简单记录下casbin的练手

安装

2021.11.29casbinv2
go install github.com/casbin/casbin/v2
model.conf
[role_definition]
g = _, _, _

[request_definition]
r = sub, dom, obj, act       //sub-用户,dom-域,obj-资源,act-操作

[policy_definition]
p = sub, dom, obj, act

[matchers]
m = g(r.sub, p.sub, r.dom) && r.act == p.act && r.dom == p.dom && keyMatch(r.obj, p.obj)

[policy_effect]
e = some(where (p.eft == allow))     // 任意一条 policy rule 满足, 则最终结果为 allow

持久化存储权限到mysql并初始化

func Casbin() *casbin.Enforcer{
	a, _ := gormadapter.NewAdapter("mysql", "user_name:user_passwd@tcp(127.0.0.1:3306)/") // Your driver and data source.
	e, err := casbin.NewEnforcer("./model.conf", a)
	if err != nil {
		log.Fatal("载入casbin配置出错")
	}

	e.LoadPolicy() // 从数据库载入配置
	return e
}

func InitCasbin()(e *casbin.Enforcer ,err error) {
	e = Casbin()
	gh_dev, gh, data1, read, write, hh_dev, hh_admin, root, gh_admin,hh,data2,zr,gp,lc,mdw,pzc := "gh_dev", "gh","data1","read","write","hh_dev","hh_admin","root","gh_admin","hh","data2","zr","gp","lc","mdw","pzc"

	p_pilicies := [][]string{
		{gh_dev, gh, "/root*", get},
		{gh_dev, gh, "/root/age*", post},
		{hh_dev, hh, "/root*", get},
		{hh_dev, hh, "/root/age*", post},
		{gh_admin, gh, "/root*", post},
		{hh_admin, hh, "/root*", post},
		{root, gh, "/root*", get},
		{root, gh, "/root*", post},
		{root, hh, "/root*", get},
		{root, hh, "/root*", post},
	}
	g_pilicies := [][]string{
		{gh_admin, gh_dev, gh},
		{hh_admin, hh_dev, hh},
		{zr, gh_dev, gh},
		{lc, gh_admin, gh},
		{xm, system, gh},
		{xm, system, hh}
	}

	_, err = e.AddPolicies(p_pilicies)                 
	if err != nil {
		log.Fatalf("添加p失败,错误:%v",err)
		return nil, err
	}
	_, err = e.AddGroupingPolicies(g_pilicies)
	if err != nil {
		log.Fatalf("添加g失败,错误:%v",err)
		return nil, err
	}
	return e,nil
}

编写检查权限函数

func check(e *casbin.Enforcer, sub, dom, obj, act string) {
	ok, _ := e.Enforce(sub, dom, obj, act)
	if ok {
		fmt.Printf("%s的%s对%s有%s权限\n",dom, sub, obj, act)
	} else {
		fmt.Printf("权限不足:%s的%s对%s没有%s权限\n",dom, sub, obj, act)
	}
}

main函数

func main() {
	e, err := InitCasbin()            // 初始化casbin
	if err != nil {
		log.Fatalf("初始化失败,err:%v",err)
		return
	}
	url1 := "/root/"
	url2 := "/root/age?15"
	url4 := "/home/name"

	check(e, "zr", "gh", url1, "get")
	check(e, "zr", "gh", url2, "post")
	check(e, "zr", "gh", url1, "post")         // 没有权限
	check(e, "zr", "hh", url1, "get")          // 没有权限
	check(e, "zr", "gh", url4, "get")          // 没有权限
	check(e, "zr", "gh", "/root/name", "post") // 没有权限
	check(e, "lc", "gh", url1, "get")
	check(e, "lc", "gh", url2, "post")
	check(e, "lc", "gh", url1, "post")
	check(e, "lc", "gh", "/", "get")  // 没有权限
	check(e, "lc", "hh", url1, "get") // 没有权限
	e.AddPolicy("zr","gh","/root/name*","get") 		//为zr添加gh的/root/name的get权限
	e.AddGroupingPolicy("Jay","gh_admin","gh")		// 为Jay添加gh的admin角色
	fmt.Println("-------添加权限后-----------")
	check(e, "zr", "gh", "/root/name?15", "get") // 有权限
	check(e, "Jay", "gh", "/root", "get") // 有权限
}

运行结果:

gh的zr对/root/有get权限
gh的zr对/root/age?15有post权限
权限不足:gh的zr对/root/没有post权限
权限不足:hh的zr对/root/没有get权限
权限不足:gh的zr对/home/name没有get权限
权限不足:gh的zr对/root/name没有post权限
gh的lc对/root/有get权限
gh的lc对/root/age?15有post权限
权限不足:hh的pzc对data2没有write权限
hh的system对data2有write权限
gh的system对data1有read权限
-------添加权限后-----------
gh的zr对/root/name?15有get权限
gh的Jay对/root有get权限

改进

root
{root, gh, "/root*", get},
{root, gh, "/root*", post},
{root, hh, "/root*", get},
{root, hh, "/root*", post},
rootusers
type User struct {
	ID       uint
	UserName string `gorm:"type:varchar(32);not null;index;"`
	Name     string `gorm:"type:varchar(32);not null;"`
	Role     string `gorm:"type:varchar(32);not null;"`
	Domain   string `gorm:"type:varchar(32);"`
	IsDelete uint8  `gorm:"default: 0"`
	gorm.Model
}
root
//  判断是否是root用户
func isRoot(sub string) bool {
	userModels, err := GetRootUser()
	if err != nil {
		panic(fmt.Errorf("获取root用户名单失败,原因:%v", err))
		return false
	}
	for _, userModel := range userModels {
		if sub == userModel.UserName {
			return true
		}
	}
	return false
}
//  获取root用户列表
func GetRootUser(){
	user := []*User{}
	err := CasbinDb.Where("role = ? AND is_delete = ?", "root", 0).Find(&user).Error
	if err != nil {
		return nil, err
	}
	return user, nil
}

用interface类型接口包装上面函数

func KeyMatchFunc(arg ...interface{}) (interface{}, error) {
	sub := arg[0].(string)
	return isRoot(sub), nil
}
casbinenforcer
e.AddFunction("isRoot", KeyMatchFunc)
model.confmatchersisRoot
[matchers]
m = g(r.sub, p.sub, r.dom) && r.act == p.act && r.dom == p.dom && keyMatch(r.obj, p.obj) || isRoot(r.sub)

现在数据库表中数据为:在这里插入图片描述

新增的测试用例为

url1 := "/root/"
check(e, "root1", "hh", url1, "get")
check(e, "root2", "dsda", url1, "get")
check(e, "root3", "sda", url1, "get") // 没有权限,因为数据库中没有root3用户

运行结果:

hh的root1对/root/有get权限
dsda的root2对/root/有get权限
权限不足:sda的root3对/root/没有get权限