Casbin中文文档
环境
- go:1.15
- casbin:v2
- mysql:5.7
代码
package mycasbinimport ("fmt""github.com/casbin/casbin/v2""github.com/casbin/casbin/v2/model"gormAdapter "github.com/casbin/gorm-adapter/v3""gorm.io/driver/mysql""gorm.io/gorm""testing"
)var conf = `
[request_definition]
r = sub, obj, act[policy_definition]
p = sub, obj, act[policy_effect]
e = some(where (p.eft == allow))[matchers]
m = r.sub == p.sub && (keyMatch2(r.obj, p.obj) || keyMatch(r.obj, p.obj)) && (r.act == p.act)
`func TestCheckRole(t *testing.T) {db, err := gorm.Open(mysql.Open("name:pwd@tcp(127.0.0.1:3306)/casbin?charset=utf8&parseTime=True&loc=Local"))if err != nil {panic("连接数据库失败")}// 默认创建或读取 casbin_rule数据表Apter, err := gormAdapter.NewAdapterByDB(db)if err != nil {panic(err)}m, err := model.NewModelFromString(conf)if err != nil {panic(err)}e, err := casbin.NewSyncedEnforcer(m, Apter)if err != nil {panic(err)}// 从数据库中加载policy规则;err = e.LoadPolicy()if err != nil {panic(err)}// 增加策略_, _ = e.AddNamedPolicy("p", []string{"2", "/test2", "GET"})_, _ = e.AddNamedPolicy("p", []string{"3", "/test3", "GET"})// 删除策略_, _ = e.RemoveFilteredPolicy(0, "3")//匹配策略res, err := e.Enforce("3", "/test2", "GET")if err == nil && res {fmt.Println("可以访问!!!")return}fmt.Println("权限不足:", err, res)// 获取策略信息fmt.Println(e.GetPolicy())fmt.Println(e.GetAllActions())fmt.Println(e.GetAdapter())fmt.Println(e.GetAllSubjects())fmt.Println(e.GetAllObjects())
}