├── .gitignore ├── demo ├── v1 │ ├── go.mod │ ├── go.sum │ └── v1_demo.go └── v2 │ ├── go.mod │ ├── go.sum │ └── v2_demo.go ├── go.mod ├── go.sum ├── adapter_test.go ├── adapter.go ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .idea/ 3 | -------------------------------------------------------------------------------- /demo/v1/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/qiangmzsx/string-adapter/demo/v1 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/casbin/casbin v1.9.1 7 | github.com/qiangmzsx/string-adapter v1.0.0 8 | ) 9 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/qiangmzsx/string-adapter/v2 2 | 3 | go 1.18 4 | 5 | require github.com/casbin/casbin/v2 v2.63.0 6 | 7 | require github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect 8 | -------------------------------------------------------------------------------- /demo/v2/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/qiangmzsx/string-adapter/demo/v2 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/casbin/casbin/v2 v2.63.0 7 | github.com/qiangmzsx/string-adapter/v2 v2.0.1 8 | ) 9 | 10 | require github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect 11 | -------------------------------------------------------------------------------- /demo/v1/go.sum: -------------------------------------------------------------------------------- 1 | github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible h1:1G1pk05UrOh0NlF1oeaaix1x8XzrfjIDK47TY0Zehcw= 2 | github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= 3 | github.com/casbin/casbin v1.9.1 h1:ucjbS5zTrmSLtH4XogqOG920Poe6QatdXtz1FEbApeM= 4 | github.com/casbin/casbin v1.9.1/go.mod h1:z8uPsfBJGUsnkagrt3G8QvjgTKFMBJ32UP8HpZllfog= 5 | github.com/qiangmzsx/string-adapter v1.0.0 h1:pFAwLvCEyCfoBPrJKoGXsLThREMwKZKvE0pEHbrX+Mw= 6 | github.com/qiangmzsx/string-adapter v1.0.0/go.mod h1:wMGE3VUIt9myT1P9l3oFLt83Kpz1jl0V4qyyBQDP3bc= 7 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible h1:1G1pk05UrOh0NlF1oeaaix1x8XzrfjIDK47TY0Zehcw= 2 | github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= 3 | github.com/casbin/casbin/v2 v2.63.0 h1:+xd5gRceCk+IGzIJgUSZQtypZuOzZDHgHvU0FlmBCVA= 4 | github.com/casbin/casbin/v2 v2.63.0/go.mod h1:vByNa/Fchek0KZUgG5wEsl7iFsiviAYKRtgrQfcJqHg= 5 | github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= 6 | github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= 7 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 8 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 9 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 10 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 11 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 12 | golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= 13 | -------------------------------------------------------------------------------- /demo/v2/go.sum: -------------------------------------------------------------------------------- 1 | github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible h1:1G1pk05UrOh0NlF1oeaaix1x8XzrfjIDK47TY0Zehcw= 2 | github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= 3 | github.com/casbin/casbin/v2 v2.1.0/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= 4 | github.com/casbin/casbin/v2 v2.63.0 h1:+xd5gRceCk+IGzIJgUSZQtypZuOzZDHgHvU0FlmBCVA= 5 | github.com/casbin/casbin/v2 v2.63.0/go.mod h1:vByNa/Fchek0KZUgG5wEsl7iFsiviAYKRtgrQfcJqHg= 6 | github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= 7 | github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= 8 | github.com/qiangmzsx/string-adapter/v2 v2.0.1 h1:FTxf2cTzguYaB0sfgnDigrvkO0w7Sh9mMabsKF3xPOo= 9 | github.com/qiangmzsx/string-adapter/v2 v2.0.1/go.mod h1:PElPB7b7HnGKTsuADAffFpOQXHqjEGJz1+U1a6yR5wA= 10 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 11 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 12 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 13 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 14 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 15 | golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= 16 | -------------------------------------------------------------------------------- /demo/v1/v1_demo.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The string-adapter Authors. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "fmt" 19 | 20 | scas "github.com/qiangmzsx/string-adapter" 21 | 22 | "github.com/casbin/casbin" 23 | "github.com/casbin/casbin/model" 24 | ) 25 | 26 | func main() { 27 | 28 | modelText := ` 29 | [request_definition] 30 | r = sub, obj, act 31 | 32 | [policy_definition] 33 | p = sub, obj, act 34 | 35 | [role_definition] 36 | g = _, _ 37 | g2 = _, _ 38 | 39 | [policy_effect] 40 | e = some(where (p.eft == allow)) 41 | 42 | [matchers] 43 | m = g(r.sub, p.sub) && g2(r.obj, p.obj) && r.act == p.act` 44 | 45 | m := model.Model{} 46 | 47 | m.LoadModelFromText(modelText) 48 | 49 | line := ` 50 | p, alice, data1, read 51 | p, bob, data2, write 52 | p, data_group_admin, data_group, write 53 | 54 | g, alice, data_group_admin 55 | g2, data1, data_group 56 | g2, data2, data_group 57 | ` 58 | sa := scas.NewAdapter(line) 59 | 60 | // Initialize a Gorm adapter and use it in a Casbin enforcer: 61 | // The adapter will use the MySQL database named "casbin". 62 | // If it doesn't exist, the adapter will create it automatically. 63 | // You can also use an already existing gorm instance with gormadapter.NewAdapterByDB(gormInstance) 64 | //a, _ := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/") // Your driver and data source. 65 | // e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) 66 | e := casbin.NewEnforcer(m, sa) 67 | 68 | // Or you can use an existing DB "abc" like this: 69 | // The adapter will use the table named "casbin_rule". 70 | // If it doesn't exist, the adapter will create it automatically. 71 | // a := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/abc", true) 72 | 73 | // Load the policy from DB. 74 | e.LoadPolicy() 75 | 76 | // Check the permission. 77 | if res := e.Enforce("alice", "data1", "read"); res { 78 | fmt.Println("permitted") 79 | } else { 80 | fmt.Println("rejected") 81 | } 82 | 83 | // Modify the policy. 84 | // e.AddPolicy(...) 85 | // e.RemovePolicy(...) 86 | 87 | // Save the policy back to DB. 88 | e.SavePolicy() 89 | } 90 | -------------------------------------------------------------------------------- /demo/v2/v2_demo.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The string-adapter Authors. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "fmt" 19 | 20 | scas "github.com/qiangmzsx/string-adapter/v2" 21 | 22 | "github.com/casbin/casbin/v2" 23 | "github.com/casbin/casbin/v2/model" 24 | ) 25 | 26 | func main() { 27 | 28 | modelText := ` 29 | [request_definition] 30 | r = sub, obj, act 31 | 32 | [policy_definition] 33 | p = sub, obj, act 34 | 35 | [role_definition] 36 | g = _, _ 37 | g2 = _, _ 38 | 39 | [policy_effect] 40 | e = some(where (p.eft == allow)) 41 | 42 | [matchers] 43 | m = g(r.sub, p.sub) && g2(r.obj, p.obj) && r.act == p.act` 44 | 45 | m := model.NewModel() 46 | 47 | m.LoadModelFromText(modelText) 48 | 49 | line := ` 50 | p, alice, data1, read 51 | p, bob, data2, write 52 | p, data_group_admin, data_group, write 53 | 54 | g, alice, data_group_admin 55 | g2, data1, data_group 56 | g2, data2, data_group 57 | ` 58 | sa := scas.NewAdapter(line) 59 | 60 | // Initialize a Gorm adapter and use it in a Casbin enforcer: 61 | // The adapter will use the MySQL database named "casbin". 62 | // If it doesn't exist, the adapter will create it automatically. 63 | // You can also use an already existing gorm instance with gormadapter.NewAdapterByDB(gormInstance) 64 | //a, _ := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/") // Your driver and data source. 65 | // e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) 66 | e, _ := casbin.NewEnforcer(m, sa) 67 | 68 | // Or you can use an existing DB "abc" like this: 69 | // The adapter will use the table named "casbin_rule". 70 | // If it doesn't exist, the adapter will create it automatically. 71 | // a := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/abc", true) 72 | 73 | // Load the policy from DB. 74 | e.LoadPolicy() 75 | 76 | // Check the permission. 77 | if res, _ := e.Enforce("alice", "data1", "read"); res { 78 | fmt.Println("permitted") 79 | } else { 80 | fmt.Println("rejected") 81 | } 82 | 83 | // Modify the policy. 84 | // e.AddPolicy(...) 85 | // e.RemovePolicy(...) 86 | 87 | // Save the policy back to DB. 88 | e.SavePolicy() 89 | } 90 | -------------------------------------------------------------------------------- /adapter_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The string-adapter Authors. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package string_adapter 16 | 17 | import ( 18 | "testing" 19 | 20 | "github.com/casbin/casbin/v2" 21 | "github.com/casbin/casbin/v2/model" 22 | ) 23 | 24 | func Test_KeyMatchRbac(t *testing.T) { 25 | conf := ` 26 | [request_definition] 27 | r = sub, obj, act 28 | 29 | [policy_definition] 30 | p = sub, obj, act 31 | 32 | [role_definition] 33 | g = _ , _ 34 | 35 | [policy_effect] 36 | e = some(where (p.eft == allow)) 37 | 38 | [matchers] 39 | m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act) 40 | ` 41 | line := ` 42 | p, alice, /alice_data/*, (GET)|(POST) 43 | p, alice, /alice_data/resource1, POST 44 | p, data_group_admin, /admin/*, POST 45 | p, data_group_admin, /bob_data/*, POST 46 | g, alice, data_group_admin 47 | ` 48 | sa := NewAdapter(line) 49 | md := model.NewModel() 50 | err := md.LoadModelFromText(conf) 51 | if err != nil { 52 | t.Error(err) 53 | return 54 | } 55 | e, _ := casbin.NewEnforcer(md, sa) 56 | sub := "alice" 57 | obj := "/alice_data/login" 58 | act := "POST" 59 | if res, _ := e.Enforce(sub, obj, act); res != true { 60 | t.Error("**error**") 61 | } 62 | } 63 | 64 | func Test_StringRbac(t *testing.T) { 65 | conf := ` 66 | [request_definition] 67 | r = sub, obj, act 68 | 69 | [policy_definition] 70 | p = sub, obj, act 71 | 72 | [role_definition] 73 | g = _ , _ 74 | 75 | [policy_effect] 76 | e = some(where (p.eft == allow)) 77 | 78 | [matchers] 79 | m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act 80 | ` 81 | line := ` 82 | p, alice, data1, read 83 | p, data_group_admin, data3, read 84 | p, data_group_admin, data3, write 85 | g, alice, data_group_admin 86 | ` 87 | sa := NewAdapter(line) 88 | md := model.NewModel() 89 | err := md.LoadModelFromText(conf) 90 | if err != nil { 91 | t.Error(err) 92 | return 93 | } 94 | e, _ := casbin.NewEnforcer(md, sa) 95 | sub := "alice" // the user that wants to access a resource. 96 | obj := "data1" // the resource that is going to be accessed. 97 | act := "read" // the operation that the user performs on the resource. 98 | if res, _ := e.Enforce(sub, obj, act); res != true { 99 | t.Error("**error**") 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /adapter.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The string-adapter Authors. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package string_adapter 16 | 17 | import ( 18 | "bytes" 19 | "errors" 20 | "strings" 21 | 22 | "github.com/casbin/casbin/v2/model" 23 | "github.com/casbin/casbin/v2/persist" 24 | "github.com/casbin/casbin/v2/util" 25 | ) 26 | 27 | /*type Adapter interface { 28 | // LoadPolicy loads all policy rules from the storage. 29 | LoadPolicy(model model.Model) error 30 | // SavePolicy saves all policy rules to the storage. 31 | SavePolicy(model model.Model) error 32 | 33 | // AddPolicy adds a policy rule to the storage. 34 | // This is part of the Auto-Save feature. 35 | AddPolicy(sec string, ptype string, rule []string) error 36 | // RemovePolicy removes a policy rule from the storage. 37 | // This is part of the Auto-Save feature. 38 | RemovePolicy(sec string, ptype string, rule []string) error 39 | // RemoveFilteredPolicy removes policy rules that match the filter from the storage. 40 | // This is part of the Auto-Save feature. 41 | RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error 42 | }*/ 43 | 44 | type Adapter struct { 45 | Line string 46 | } 47 | 48 | func NewAdapter(line string) *Adapter { 49 | return &Adapter{ 50 | Line: line, 51 | } 52 | } 53 | 54 | func (sa *Adapter) LoadPolicy(model model.Model) error { 55 | if sa.Line == "" { 56 | return errors.New("invalid line, line cannot be empty") 57 | } 58 | strs := strings.Split(sa.Line, "\n") 59 | for _, str := range strs { 60 | if str == "" { 61 | continue 62 | } 63 | persist.LoadPolicyLine(str, model) 64 | } 65 | 66 | return nil 67 | } 68 | 69 | func (sa *Adapter) SavePolicy(model model.Model) error { 70 | var tmp bytes.Buffer 71 | for ptype, ast := range model["p"] { 72 | for _, rule := range ast.Policy { 73 | tmp.WriteString(ptype + ", ") 74 | tmp.WriteString(util.ArrayToString(rule)) 75 | tmp.WriteString("\n") 76 | } 77 | } 78 | 79 | for ptype, ast := range model["g"] { 80 | for _, rule := range ast.Policy { 81 | tmp.WriteString(ptype + ", ") 82 | tmp.WriteString(util.ArrayToString(rule)) 83 | tmp.WriteString("\n") 84 | } 85 | } 86 | sa.Line = strings.TrimRight(tmp.String(), "\n") 87 | return nil 88 | } 89 | 90 | func (sa *Adapter) AddPolicy(sec string, ptype string, rule []string) error { 91 | return errors.New("not implemented") 92 | } 93 | 94 | func (sa *Adapter) RemovePolicy(sec string, ptype string, rule []string) error { 95 | sa.Line = "" 96 | return nil 97 | } 98 | 99 | func (sa *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { 100 | return errors.New("not implemented") 101 | } 102 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # string-adapter 2 | string adapter for Casbin https://github.com/casbin/casbin 3 | 4 | # Installation 5 | 6 | go get github.com/qiangmzsx/string-adapter 7 | 8 | 9 | 10 | # Simple Example 11 | ## casbin v1 12 | ```go 13 | package main 14 | 15 | import ( 16 | "fmt" 17 | "github.com/casbin/casbin" 18 | scas "github.com/qiangmzsx/string-adapter" 19 | "github.com/casbin/casbin/file-adapter" 20 | ) 21 | 22 | func main() { 23 | KeyMatchRbac() 24 | //StringRbac() 25 | //UserRbac() 26 | } 27 | 28 | func KeyMatchRbac() { 29 | conf := ` 30 | [request_definition] 31 | r = sub, obj, act 32 | 33 | [policy_definition] 34 | p = sub, obj, act 35 | 36 | [role_definition] 37 | g = _ , _ 38 | 39 | [policy_effect] 40 | e = some(where (p.eft == allow)) 41 | 42 | [matchers] 43 | m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act) 44 | ` 45 | line := ` 46 | p, alice, /alice_data/*, (GET)|(POST) 47 | p, alice, /alice_data/resource1, POST 48 | p, data_group_admin, /admin/*, POST 49 | p, data_group_admin, /bob_data/*, POST 50 | g, alice, data_group_admin 51 | ` 52 | sa := scas.NewAdapter(line) 53 | e := casbin.NewEnforcer(casbin.NewModel(conf), sa) 54 | sub := "alice" 55 | obj := "/alice_data1/login" 56 | act := "POST" 57 | if e.Enforce(sub, obj, act) == true { 58 | fmt.Println("**YES**") 59 | } else { 60 | fmt.Println("--NO--") 61 | } 62 | } 63 | 64 | func StringRbac() { 65 | conf := ` 66 | [request_definition] 67 | r = sub, obj, act 68 | 69 | [policy_definition] 70 | p = sub, obj, act 71 | 72 | [role_definition] 73 | g = _ , _ 74 | 75 | [policy_effect] 76 | e = some(where (p.eft == allow)) 77 | 78 | [matchers] 79 | m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act 80 | ` 81 | line := ` 82 | p, alice, data1, read 83 | p, data_group_admin, data3, read 84 | p, data_group_admin, data3, write 85 | g, alice, data_group_admin 86 | ` 87 | sa := scas.NewAdapter(line) 88 | e := casbin.NewEnforcer(casbin.NewModel(conf), sa) 89 | sub := "alice" // the user that wants to access a resource. 90 | obj := "data1" // the resource that is going to be accessed. 91 | act := "write" // the operation that the user performs on the resource. 92 | if e.Enforce(sub, obj, act) == true { 93 | fmt.Println("**YES**") 94 | } else { 95 | fmt.Println("--NO--") 96 | } 97 | } 98 | ``` 99 | 100 | ## casbin v2 101 | ```go 102 | package main 103 | 104 | import ( 105 | "fmt" 106 | 107 | scas "github.com/qiangmzsx/string-adapter/v2" 108 | 109 | "github.com/casbin/casbin/v2" 110 | "github.com/casbin/casbin/v2/model" 111 | ) 112 | 113 | func main() { 114 | 115 | modelText := ` 116 | [request_definition] 117 | r = sub, obj, act 118 | 119 | [policy_definition] 120 | p = sub, obj, act 121 | 122 | [role_definition] 123 | g = _, _ 124 | g2 = _, _ 125 | 126 | [policy_effect] 127 | e = some(where (p.eft == allow)) 128 | 129 | [matchers] 130 | m = g(r.sub, p.sub) && g2(r.obj, p.obj) && r.act == p.act` 131 | 132 | m := model.NewModel() 133 | 134 | m.LoadModelFromText(modelText) 135 | 136 | line := ` 137 | p, alice, data1, read 138 | p, bob, data2, write 139 | p, data_group_admin, data_group, write 140 | 141 | g, alice, data_group_admin 142 | g2, data1, data_group 143 | g2, data2, data_group 144 | ` 145 | sa := scas.NewAdapter(line) 146 | 147 | // Initialize a Gorm adapter and use it in a Casbin enforcer: 148 | // The adapter will use the MySQL database named "casbin". 149 | // If it doesn't exist, the adapter will create it automatically. 150 | // You can also use an already existing gorm instance with gormadapter.NewAdapterByDB(gormInstance) 151 | //a, _ := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/") // Your driver and data source. 152 | // e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) 153 | e, _ := casbin.NewEnforcer(m, sa) 154 | 155 | // Or you can use an existing DB "abc" like this: 156 | // The adapter will use the table named "casbin_rule". 157 | // If it doesn't exist, the adapter will create it automatically. 158 | // a := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/abc", true) 159 | 160 | // Load the policy from DB. 161 | e.LoadPolicy() 162 | 163 | // Check the permission. 164 | if res, _ := e.Enforce("alice", "data1", "read"); res { 165 | fmt.Println("permitted") 166 | } else { 167 | fmt.Println("rejected") 168 | } 169 | 170 | // Modify the policy. 171 | // e.AddPolicy(...) 172 | // e.RemovePolicy(...) 173 | 174 | // Save the policy back to DB. 175 | e.SavePolicy() 176 | } 177 | 178 | ``` 179 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------