├── .gitignore ├── LICENSE ├── README.md ├── adapter.go ├── adapter_test.go ├── examples ├── casbin_rule.sql ├── casbin_rule_sqlite.sql ├── rbac_model.conf └── rbac_policy.csv ├── go.mod └── go.sum /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | .idea 14 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # casbin-sqlx-adapter 2 | sqlx adapter for Casbin https://github.com/casbin/casbin 3 | 4 | Based on [sqlx](https://github.com/jmoiron/sqlx), and tested in [MySQL](https://github.com/go-sql-driver/mysql). 5 | 6 | ## Installation 7 | 8 | go get github.com/memwey/casbin-sqlx-adapter 9 | 10 | ## NOTICE 11 | 12 | The v2 version of Casbin has some break change, check for the [detail](https://github.com/casbin/casbin/releases/tag/v2.0.0). If you are still using v1 version, use `0.1.x` of this project. And if you have been using the package before, and wanting to upgrade, check the following massage. 13 | 14 | The adapter maintained by Casbin team introduce a **BREAKING CHANGE** by changing the column name from **p_type** to **ptype**, see the issue in [gorm-adapter](https://github.com/casbin/gorm-adapter/issues/156) and [xorm-adapter](https://github.com/casbin/xorm-adapter/issues/53). Thought I think the adapter layer is able to imply its own storage detail, I follow this **BREAKING CHANGE** in version `0.3.0` in case of developers may port to different adapters. 15 | 16 | The implement is kind of different from the [official one](https://casbin.org/docs/adapters). In this implement you should create the database and table on your own. 17 | 18 | In my opinion, in a general PRODUCTION environment, the business code is only allow to do DML but not DDL. 19 | 20 | The filtered adapter feature has been added in some adapter implements such as [Xorm Adapter](https://github.com/casbin/xorm-adapter). However, it's not yet documented in the [doc](https://casbin.org/docs/en/adapters). I will add it after it's documented. See this [issue](https://github.com/casbin/casbin/issues/707). 21 | 22 | ## Usage example 23 | 24 | ```go 25 | opts := &AdapterOptions{ 26 | DriverName: "mysql", 27 | DataSourceName: "root:1234@tcp(127.0.0.1:3306)/yourdb", 28 | TableName: "casbin_rule", 29 | // or reuse an existing connection: 30 | // DB: myDBConn, 31 | } 32 | 33 | a := NewAdapterFromOptions(opts) 34 | // Casbin v2 may return an error 35 | e, err := casbin.NewEnforcer("examples/rbac_model.conf", a) 36 | if err != nil { 37 | panic(err) 38 | } 39 | ``` 40 | 41 | ## Thank 42 | 43 | Special thanks to [Casbin](https://github.com/casbin). They provide a superb authorization library. 44 | 45 | Special thanks to [sqlx](https://github.com/jmoiron/sqlx). It provides a brilliant set of extensions on go's standard `database/sql` library. 46 | 47 | And this project is inspected by [Xorm Adapter](https://github.com/casbin/xorm-adapter), [Gorm Adapter](https://github.com/casbin/gorm-adapter), [Beego ORM Adapter](https://github.com/casbin/beego-orm-adapter) and [MySQL adapter 48 | ](https://github.com/casbin/mysql-adapter). Thanks all of them. 49 | 50 | ## Others 51 | 52 | This is a very first opensource of me and if this project violates any of the opensource guidelines, please contact me. The project is far from perfect, issues and pull requesets are very welcome. 53 | 54 | ## License 55 | 56 | This project is under Apache 2.0 License. See the [LICENSE](LICENSE) file for the full license text. 57 | -------------------------------------------------------------------------------- /adapter.go: -------------------------------------------------------------------------------- 1 | package sqlxadapter 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | 7 | "github.com/casbin/casbin/v2/model" 8 | "github.com/casbin/casbin/v2/persist" 9 | "github.com/jmoiron/sqlx" 10 | ) 11 | 12 | // CasbinRule ... 13 | type CasbinRule struct { 14 | ID int64 `db:"id"` 15 | PType string `db:"ptype"` 16 | V0 string `db:"v0"` 17 | V1 string `db:"v1"` 18 | V2 string `db:"v2"` 19 | V3 string `db:"v3"` 20 | V4 string `db:"v4"` 21 | V5 string `db:"v5"` 22 | } 23 | 24 | // Adapter represents the sqlx adapter for policy storage. 25 | type Adapter struct { 26 | db *sqlx.DB 27 | tableName string 28 | isFiltered bool 29 | } 30 | 31 | // Filter ... 32 | type Filter struct { 33 | PType []string 34 | V0 []string 35 | V1 []string 36 | V2 []string 37 | V3 []string 38 | V4 []string 39 | V5 []string 40 | } 41 | 42 | // AdapterOptions contains all possible configuration options. 43 | type AdapterOptions struct { 44 | DriverName string 45 | DataSourceName string 46 | TableName string 47 | DB *sqlx.DB 48 | } 49 | 50 | func finalizer(a *Adapter) { 51 | a.db.Close() 52 | } 53 | 54 | func loadPolicyLine(line CasbinRule, model model.Model) { 55 | lineText := line.PType 56 | if line.V0 != "" { 57 | lineText += ", " + line.V0 58 | } 59 | if line.V1 != "" { 60 | lineText += ", " + line.V1 61 | } 62 | if line.V2 != "" { 63 | lineText += ", " + line.V2 64 | } 65 | if line.V3 != "" { 66 | lineText += ", " + line.V3 67 | } 68 | if line.V4 != "" { 69 | lineText += ", " + line.V4 70 | } 71 | if line.V5 != "" { 72 | lineText += ", " + line.V5 73 | } 74 | persist.LoadPolicyLine(lineText, model) 75 | } 76 | 77 | func savePolicyLine(ptype string, rule []string) CasbinRule { 78 | line := CasbinRule{} 79 | line.PType = ptype 80 | if len(rule) > 0 { 81 | line.V0 = rule[0] 82 | } 83 | if len(rule) > 1 { 84 | line.V1 = rule[1] 85 | } 86 | if len(rule) > 2 { 87 | line.V2 = rule[2] 88 | } 89 | if len(rule) > 3 { 90 | line.V3 = rule[3] 91 | } 92 | if len(rule) > 4 { 93 | line.V4 = rule[4] 94 | } 95 | if len(rule) > 5 { 96 | line.V5 = rule[5] 97 | } 98 | return line 99 | } 100 | 101 | func (a *Adapter) dropTable() { 102 | _, err := a.db.Exec(fmt.Sprintf("DELETE FROM %s", a.tableName)) 103 | if err != nil { 104 | panic(err) 105 | } 106 | } 107 | 108 | func (a *Adapter) ensureTable() { 109 | _, err := a.db.Exec(fmt.Sprintf("SELECT 1 FROM %s LIMIT 1", a.tableName)) 110 | if err != nil { 111 | panic(err) 112 | } 113 | } 114 | 115 | func (a *Adapter) insertPolicyLine(line *CasbinRule) (err error) { 116 | query := fmt.Sprintf( 117 | "INSERT INTO %s (ptype, v0, v1, v2, v3, v4, v5) VALUES (:ptype, :v0, :v1, :v2, :v3, :v4, :v5)", 118 | a.tableName, 119 | ) 120 | _, err = a.db.NamedExec(query, line) 121 | if err != nil { 122 | return 123 | } 124 | return 125 | } 126 | 127 | func (a *Adapter) deletePolicyLine(line *CasbinRule) (err error) { 128 | query := fmt.Sprintf( 129 | "DELETE FROM %s WHERE ptype = :ptype AND v0 = :v0 AND v1 = :v1 AND v2 = :v2 AND v3 = :v3 AND v4 = :v4 AND v5 = :v5", 130 | a.tableName, 131 | ) 132 | _, err = a.db.NamedExec(query, line) 133 | if err != nil { 134 | return 135 | } 136 | return 137 | } 138 | 139 | // NewAdapter is the constructor for Adapter 140 | // Deprecated: Use NewAdapterFromOptions instead 141 | func NewAdapter(driverName string, dataSourceName string) *Adapter { 142 | db, err := sqlx.Connect(driverName, dataSourceName) 143 | if err != nil { 144 | panic(err) 145 | } 146 | a := &Adapter{ 147 | db: db, 148 | tableName: "casbin_rule", 149 | } 150 | a.ensureTable() 151 | // Call the destructor when the object is released. 152 | runtime.SetFinalizer(a, finalizer) 153 | return a 154 | } 155 | 156 | // NewAdapterByDB is the constructor for Adapter with existed connection 157 | // Deprecated: Use NewAdapterFromOptions instead 158 | func NewAdapterByDB(db *sqlx.DB) *Adapter { 159 | a := &Adapter{ 160 | db: db, 161 | tableName: "casbin_rule", 162 | } 163 | a.ensureTable() 164 | return a 165 | } 166 | 167 | // NewAdapterFromOptions is the constructor for Adapter with existed connection 168 | func NewAdapterFromOptions(opts *AdapterOptions) *Adapter { 169 | a := &Adapter{tableName: "casbin_rule"} 170 | if opts.TableName != "" { 171 | a.tableName = opts.TableName 172 | } 173 | if opts.DB != nil { 174 | a.db = opts.DB 175 | } else { 176 | db, err := sqlx.Connect(opts.DriverName, opts.DataSourceName) 177 | if err != nil { 178 | panic(err) 179 | } 180 | a.db = db 181 | runtime.SetFinalizer(a, finalizer) 182 | } 183 | a.ensureTable() 184 | return a 185 | } 186 | 187 | // LoadPolicy loads policy from database. 188 | func (a *Adapter) LoadPolicy(model model.Model) error { 189 | var lines []CasbinRule 190 | err := a.db.Select(&lines, fmt.Sprintf("SELECT * FROM %s", a.tableName)) 191 | if err != nil { 192 | return err 193 | } 194 | for _, line := range lines { 195 | loadPolicyLine(line, model) 196 | } 197 | return nil 198 | } 199 | 200 | // SavePolicy saves policy to database. 201 | func (a *Adapter) SavePolicy(model model.Model) (err error) { 202 | a.dropTable() 203 | for ptype, ast := range model["p"] { 204 | for _, rule := range ast.Policy { 205 | line := savePolicyLine(ptype, rule) 206 | err = a.insertPolicyLine(&line) 207 | if err != nil { 208 | return 209 | } 210 | } 211 | } 212 | for ptype, ast := range model["g"] { 213 | for _, rule := range ast.Policy { 214 | line := savePolicyLine(ptype, rule) 215 | err = a.insertPolicyLine(&line) 216 | if err != nil { 217 | return 218 | } 219 | } 220 | } 221 | return 222 | } 223 | 224 | // AddPolicy adds a policy rule to the storage. 225 | func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) (err error) { 226 | line := savePolicyLine(ptype, rule) 227 | err = a.insertPolicyLine(&line) 228 | if err != nil { 229 | return 230 | } 231 | return err 232 | } 233 | 234 | // RemovePolicy removes a policy rule from the storage. 235 | func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) (err error) { 236 | line := savePolicyLine(ptype, rule) 237 | err = a.deletePolicyLine(&line) 238 | if err != nil { 239 | return 240 | } 241 | return err 242 | } 243 | 244 | // RemoveFilteredPolicy removes policy rules that match the filter from the storage. 245 | func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) (err error) { 246 | line := CasbinRule{} 247 | line.PType = ptype 248 | if fieldIndex <= 0 && 0 < fieldIndex+len(fieldValues) { 249 | line.V0 = fieldValues[0-fieldIndex] 250 | } 251 | if fieldIndex <= 1 && 1 < fieldIndex+len(fieldValues) { 252 | line.V1 = fieldValues[1-fieldIndex] 253 | } 254 | if fieldIndex <= 2 && 2 < fieldIndex+len(fieldValues) { 255 | line.V2 = fieldValues[2-fieldIndex] 256 | } 257 | if fieldIndex <= 3 && 3 < fieldIndex+len(fieldValues) { 258 | line.V3 = fieldValues[3-fieldIndex] 259 | } 260 | if fieldIndex <= 4 && 4 < fieldIndex+len(fieldValues) { 261 | line.V4 = fieldValues[4-fieldIndex] 262 | } 263 | if fieldIndex <= 5 && 5 < fieldIndex+len(fieldValues) { 264 | line.V5 = fieldValues[5-fieldIndex] 265 | } 266 | err = a.rawDelete(&line) 267 | if err != nil { 268 | return 269 | } 270 | return 271 | } 272 | 273 | func (a *Adapter) rawDelete(line *CasbinRule) (err error) { 274 | query := fmt.Sprintf("DELETE FROM %s WHERE ptype = :ptype", a.tableName) 275 | if line.V0 != "" { 276 | query += " AND v0 = :v0" 277 | } 278 | if line.V1 != "" { 279 | query += " AND v1 = :v1" 280 | } 281 | if line.V2 != "" { 282 | query += " AND v2 = :v2" 283 | } 284 | if line.V3 != "" { 285 | query += " AND v3 = :v3" 286 | } 287 | if line.V4 != "" { 288 | query += " AND v4 = :v4" 289 | } 290 | if line.V5 != "" { 291 | query += " AND v5 = :v5" 292 | } 293 | _, err = a.db.NamedExec(query, line) 294 | if err != nil { 295 | return 296 | } 297 | return 298 | } 299 | 300 | // IsFiltered returns true if the loaded policy has been filtered. 301 | func (a *Adapter) IsFiltered() bool { 302 | return a.isFiltered 303 | } 304 | -------------------------------------------------------------------------------- /adapter_test.go: -------------------------------------------------------------------------------- 1 | package sqlxadapter 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "strings" 7 | "testing" 8 | 9 | "github.com/casbin/casbin/v2" 10 | _ "github.com/go-sql-driver/mysql" 11 | "github.com/jmoiron/sqlx" 12 | _ "github.com/lib/pq" 13 | ) 14 | 15 | var ( 16 | driverName = "mysql" 17 | dataSourceName = "root:mariadb@tcp(127.0.0.1:3306)/abc" 18 | ) 19 | 20 | func testGetPolicy(t *testing.T, e *casbin.Enforcer, res [][]string) { 21 | t.Helper() 22 | myRes := e.GetPolicy() 23 | log.Print("Policy: ", myRes) 24 | 25 | m := make(map[string]bool, len(res)) 26 | for _, value := range res { 27 | key := strings.Join(value, ",") 28 | m[key] = true 29 | } 30 | 31 | for _, value := range myRes { 32 | key := strings.Join(value, ",") 33 | if !m[key] { 34 | t.Error("Policy: ", myRes, ", supposed to be ", res) 35 | break 36 | } 37 | } 38 | } 39 | 40 | func initPolicy(t *testing.T) { 41 | 42 | var err error 43 | 44 | // Because the DB is empty at first, 45 | // so we need to load the policy from the file adapter (.CSV) first. 46 | e, err := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") 47 | if err != nil { 48 | t.Fatal(err) 49 | } 50 | 51 | a := NewAdapter(driverName, dataSourceName) 52 | // This is a trick to save the current policy to the DB. 53 | // We can't call e.SavePolicy() because the adapter in the enforcer is still the file adapter. 54 | // The current policy means the policy in the Casbin enforcer (aka in memory). 55 | err = a.SavePolicy(e.GetModel()) 56 | if err != nil { 57 | panic(err) 58 | } 59 | 60 | // Clear the current policy. 61 | e.ClearPolicy() 62 | testGetPolicy(t, e, [][]string{}) 63 | 64 | // Load the policy from DB. 65 | err = a.LoadPolicy(e.GetModel()) 66 | if err != nil { 67 | panic(err) 68 | } 69 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) 70 | } 71 | 72 | func testSaveLoad(t *testing.T) { 73 | // Initialize some policy in DB. 74 | initPolicy(t) 75 | // Note: you don't need to look at the above code 76 | // if you already have a working DB with policy inside. 77 | 78 | // Now the DB has policy, so we can provide a normal use case. 79 | // Create an adapter and an enforcer. 80 | // NewEnforcer() will load the policy automatically. 81 | a := NewAdapter(driverName, dataSourceName) 82 | e, err := casbin.NewEnforcer("examples/rbac_model.conf", a) 83 | if err != nil { 84 | t.Fatal(err) 85 | } 86 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) 87 | } 88 | 89 | func testAutoSave(t *testing.T) { 90 | // Initialize some policy in DB. 91 | initPolicy(t) 92 | // Note: you don't need to look at the above code 93 | // if you already have a working DB with policy inside. 94 | var err error 95 | // Now the DB has policy, so we can provide a normal use case. 96 | // Create an adapter and an enforcer. 97 | // NewEnforcer() will load the policy automatically. 98 | a := NewAdapter(driverName, dataSourceName) 99 | e, err := casbin.NewEnforcer("examples/rbac_model.conf", a) 100 | if err != nil { 101 | t.Fatal(err) 102 | } 103 | 104 | // AutoSave is enabled by default. 105 | // Now we disable it. 106 | e.EnableAutoSave(false) 107 | 108 | logErr := func(action string) { 109 | if err != nil { 110 | t.Fatalf("test action[%s] failed, err: %v", action, err) 111 | } 112 | } 113 | 114 | // Because AutoSave is disabled, the policy change only affects the policy in Casbin enforcer, 115 | // it doesn't affect the policy in the storage. 116 | _, err = e.AddPolicy("alice", "data1", "write") 117 | logErr("AddPolicy") 118 | // Reload the policy from the storage to see the effect. 119 | err = e.LoadPolicy() 120 | logErr("LoadPolicy") 121 | // This is still the original policy. 122 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) 123 | 124 | // Now we enable the AutoSave. 125 | e.EnableAutoSave(true) 126 | 127 | // Because AutoSave is enabled, the policy change not only affects the policy in Casbin enforcer, 128 | // but also affects the policy in the storage. 129 | _, err = e.AddPolicy("alice", "data1", "write") 130 | logErr("AddPolicy2") 131 | // Reload the policy from the storage to see the effect. 132 | err = e.LoadPolicy() 133 | logErr("LoadPolicy2") 134 | // The policy has a new rule: {"alice", "data1", "write"}. 135 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}, {"alice", "data1", "write"}}) 136 | 137 | // Remove the added rule. 138 | _, err = e.RemovePolicy("alice", "data1", "write") 139 | logErr("RemovePolicy") 140 | err = e.LoadPolicy() 141 | logErr("LoadPolicy3") 142 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) 143 | 144 | // Remove "data2_admin" related policy rules via a filter. 145 | // Two rules: {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"} are deleted. 146 | _, err = e.RemoveFilteredPolicy(0, "data2_admin") 147 | logErr("RemoveFilteredPolicy") 148 | err = e.LoadPolicy() 149 | logErr("LoadPolicy4") 150 | 151 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}}) 152 | 153 | } 154 | 155 | func TestAdapters(t *testing.T) { 156 | setupDatabase(t) 157 | testSaveLoad(t) 158 | testAutoSave(t) 159 | } 160 | 161 | // Make sure the initial casbin_rule table exists 162 | func setupDatabase(t *testing.T) { 163 | migration, err := os.ReadFile("examples/casbin_rule.sql") 164 | if err != nil { 165 | t.Fatalf("failed to load casbin_rule sql migration: %s", err) 166 | } 167 | 168 | db, err := sqlx.Connect(driverName, dataSourceName) 169 | if err != nil { 170 | t.Fatalf("failed to connect to database: %s", err) 171 | } 172 | defer db.Close() 173 | 174 | _, err = db.Exec(string(migration)) 175 | if err != nil { 176 | t.Fatalf("failed to run casbin_rule sql migration: %s", err) 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /examples/casbin_rule.sql: -------------------------------------------------------------------------------- 1 | 2 | CREATE TABLE IF NOT EXISTS `casbin_rule` ( 3 | `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, 4 | `ptype` VARCHAR(32) NOT NULL DEFAULT '', 5 | `v0` VARCHAR(255) NOT NULL DEFAULT '', 6 | `v1` VARCHAR(255) NOT NULL DEFAULT '', 7 | `v2` VARCHAR(255) NOT NULL DEFAULT '', 8 | `v3` VARCHAR(255) NOT NULL DEFAULT '', 9 | `v4` VARCHAR(255) NOT NULL DEFAULT '', 10 | `v5` VARCHAR(255) NOT NULL DEFAULT '', 11 | PRIMARY KEY (`id`) 12 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 13 | -------------------------------------------------------------------------------- /examples/casbin_rule_sqlite.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS `casbin_rule` ( 2 | `id` INTEGER, 3 | `ptype` VARCHAR(32) NOT NULL DEFAULT '', 4 | `v0` VARCHAR(255) NOT NULL DEFAULT '', 5 | `v1` VARCHAR(255) NOT NULL DEFAULT '', 6 | `v2` VARCHAR(255) NOT NULL DEFAULT '', 7 | `v3` VARCHAR(255) NOT NULL DEFAULT '', 8 | `v4` VARCHAR(255) NOT NULL DEFAULT '', 9 | `v5` VARCHAR(255) NOT NULL DEFAULT '', 10 | PRIMARY KEY (`id`) 11 | ); -------------------------------------------------------------------------------- /examples/rbac_model.conf: -------------------------------------------------------------------------------- 1 | [request_definition] 2 | r = sub, obj, act 3 | 4 | [policy_definition] 5 | p = sub, obj, act 6 | 7 | [role_definition] 8 | g = _, _ 9 | 10 | [policy_effect] 11 | e = some(where (p.eft == allow)) 12 | 13 | [matchers] 14 | m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act -------------------------------------------------------------------------------- /examples/rbac_policy.csv: -------------------------------------------------------------------------------- 1 | p, alice, data1, read 2 | p, bob, data2, write 3 | p, data2_admin, data2, read 4 | p, data2_admin, data2, write 5 | g, alice, data2_admin -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/memwey/casbin-sqlx-adapter 2 | 3 | go 1.20 4 | 5 | require ( 6 | github.com/casbin/casbin/v2 v2.79.0 7 | github.com/go-sql-driver/mysql v1.7.1 8 | github.com/jmoiron/sqlx v1.3.5 9 | github.com/lib/pq v1.10.9 10 | ) 11 | 12 | require github.com/casbin/govaluate v1.1.0 // indirect 13 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/casbin/casbin/v2 v2.79.0 h1:6/Q1Ud/fiJ1S999Aa1vT3XqwhNKXvsa9Q3oeCnH0bUU= 2 | github.com/casbin/casbin/v2 v2.79.0/go.mod h1:jX8uoN4veP85O/n2674r2qtfSXI6myvxW85f6TH50fw= 3 | github.com/casbin/govaluate v1.1.0 h1:6xdCWIpE9CwHdZhlVQW+froUrCsjb6/ZYNcXODfLT+E= 4 | github.com/casbin/govaluate v1.1.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A= 5 | github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= 6 | github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= 7 | github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= 8 | github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= 9 | github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= 10 | github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= 11 | github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ= 12 | github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= 13 | github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= 14 | github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= 15 | github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg= 16 | github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= 17 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 18 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 19 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 20 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 21 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 22 | golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= 23 | --------------------------------------------------------------------------------