├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .releaserc.json ├── LICENSE ├── README.md ├── adapter.go ├── adapter_test.go ├── examples ├── rbac_model.conf └── rbac_policy.csv ├── go.mod └── go.sum /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | 7 | test: 8 | runs-on: ubuntu-latest 9 | 10 | services: 11 | redis: 12 | image: redis 13 | ports: 14 | - 6379:6379 15 | 16 | steps: 17 | - name: Set up Go 18 | uses: actions/setup-go@v2 19 | with: 20 | go-version: 1.19 21 | 22 | - uses: actions/checkout@v2 23 | - name: Run Unit tests 24 | run: go test -v -coverprofile=profile.cov ./... 25 | 26 | - name: Install goveralls 27 | env: 28 | GO111MODULE: off 29 | run: go get github.com/mattn/goveralls 30 | 31 | - name: Send coverage 32 | env: 33 | COVERALLS_TOKEN: ${{ secrets.GITHUB_TOKEN }} 34 | run: goveralls -coverprofile=profile.cov -service=github 35 | 36 | semantic-release: 37 | needs: [test] 38 | runs-on: ubuntu-latest 39 | steps: 40 | 41 | - uses: actions/checkout@v2 42 | 43 | - name: Run semantic-release 44 | if: github.repository == 'casbin/redis-adapter' && github.event_name == 'push' 45 | run: | 46 | npm install --save-dev semantic-release@17.2.4 47 | npx semantic-release 48 | env: 49 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | 16 | .idea/ 17 | *.iml -------------------------------------------------------------------------------- /.releaserc.json: -------------------------------------------------------------------------------- 1 | { 2 | "debug": true, 3 | "branches": [ 4 | "+([0-9])?(.{+([0-9]),x}).x", 5 | "master", 6 | { 7 | "name": "beta", 8 | "prerelease": true 9 | } 10 | ], 11 | "plugins": [ 12 | "@semantic-release/commit-analyzer", 13 | "@semantic-release/release-notes-generator", 14 | "@semantic-release/github" 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /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 | Redis Adapter 2 | ==== 3 | 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/casbin/redis-adapter)](https://goreportcard.com/report/github.com/casbin/redis-adapter) 5 | [![Build](https://github.com/casbin/redis-adapter/actions/workflows/ci.yml/badge.svg)](https://github.com/casbin/redis-adapter/actions/workflows/ci.yml) 6 | [![Coverage Status](https://coveralls.io/repos/github/casbin/redis-adapter/badge.svg?branch=master)](https://coveralls.io/github/casbin/redis-adapter?branch=master) 7 | [![Godoc](https://godoc.org/github.com/casbin/redis-adapter?status.svg)](https://pkg.go.dev/github.com/casbin/redis-adapter/v3) 8 | [![Release](https://img.shields.io/github/release/casbin/redis-adapter.svg)](https://github.com/casbin/redis-adapter/releases/latest) 9 | [![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN) 10 | [![Sourcegraph](https://sourcegraph.com/github.com/casbin/redis-adapter/-/badge.svg)](https://sourcegraph.com/github.com/casbin/redis-adapter?badge) 11 | 12 | Redis Adapter is the [Redis](https://redis.io/) adapter for [Casbin](https://github.com/casbin/casbin). With this library, Casbin can load policy from Redis or save policy to it. 13 | 14 | ## Installation 15 | 16 | go get github.com/casbin/redis-adapter/v3 17 | 18 | ## Simple Example 19 | 20 | ```go 21 | package main 22 | 23 | import ( 24 | "github.com/casbin/casbin/v2" 25 | "github.com/casbin/redis-adapter/v3" 26 | ) 27 | 28 | func main() { 29 | // Direct Initialization: 30 | // Initialize a Redis adapter and use it in a Casbin enforcer: 31 | a, _ := redisadapter.NewAdapter("tcp", "127.0.0.1:6379") // Your Redis network and address. 32 | 33 | // Use the following if Redis has password like "123" 34 | // a, err := redisadapter.NewAdapterWithPassword("tcp", "127.0.0.1:6379", "123") 35 | 36 | // Use the following if you use Redis with a specific user 37 | // a, err := redisadapter.NewAdapterWithUser("tcp", "127.0.0.1:6379", "username", "password") 38 | 39 | // Use the following if you use Redis connections pool 40 | // pool := &redis.Pool{} 41 | // a, err := redisadapter.NewAdapterWithPool(pool) 42 | 43 | // Initialization with different user options: 44 | // Use the following if you use Redis with passowrd like "123": 45 | // a, err := redisadapter.NewAdapterWithOption(redisadapter.WithNetwork("tcp"), redisadapter.WithAddress("127.0.0.1:6379"), redisadapter.WithPassword("123")) 46 | 47 | // Use the following if you use Redis with username, password, and TLS option: 48 | // var clientTLSConfig tls.Config 49 | // ... 50 | // a, err := redisadapter.NewAdapterWithOption(redisadapter.WithNetwork("tcp"), redisadapter.WithAddress("127.0.0.1:6379"), redisadapter.WithUsername("testAccount"), redisadapter.WithPassword("123456"), redisadapter.WithTls(&clientTLSConfig)) 51 | 52 | e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) 53 | 54 | // Load the policy from DB. 55 | e.LoadPolicy() 56 | 57 | // Check the permission. 58 | e.Enforce("alice", "data1", "read") 59 | 60 | // Modify the policy. 61 | // e.AddPolicy(...) 62 | // e.RemovePolicy(...) 63 | 64 | // Save the policy back to DB. 65 | e.SavePolicy() 66 | } 67 | ``` 68 | 69 | ## Getting Help 70 | 71 | - [Casbin](https://github.com/casbin/casbin) 72 | 73 | ## License 74 | 75 | This project is under Apache 2.0 License. See the [LICENSE](LICENSE) file for the full license text. 76 | -------------------------------------------------------------------------------- /adapter.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The casbin 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 redisadapter 16 | 17 | import ( 18 | "bytes" 19 | "crypto/tls" 20 | "encoding/json" 21 | "errors" 22 | "fmt" 23 | "regexp" 24 | "runtime" 25 | "strings" 26 | 27 | "github.com/casbin/casbin/v2/model" 28 | "github.com/casbin/casbin/v2/persist" 29 | "github.com/gomodule/redigo/redis" 30 | ) 31 | 32 | // CasbinRule is used to determine which policy line to load. 33 | type CasbinRule struct { 34 | PType string 35 | V0 string 36 | V1 string 37 | V2 string 38 | V3 string 39 | V4 string 40 | V5 string 41 | } 42 | 43 | // Adapter represents the Redis adapter for policy storage. 44 | type Adapter struct { 45 | network string 46 | address string 47 | key string 48 | username string 49 | password string 50 | tlsConfig *tls.Config 51 | _conn redis.Conn 52 | _pool *redis.Pool 53 | isFiltered bool 54 | } 55 | 56 | func (a *Adapter) getConn() redis.Conn { 57 | if a._pool != nil { 58 | return a._pool.Get() 59 | } 60 | return a._conn 61 | } 62 | 63 | func (a *Adapter) release(conn redis.Conn) { 64 | if a._pool != nil { 65 | if conn != nil { 66 | conn.Close() 67 | } 68 | } 69 | } 70 | 71 | // finalizer is the destructor for Adapter. 72 | func finalizer(a *Adapter) { 73 | if a._conn != nil { 74 | a._conn.Close() 75 | } 76 | if a._pool != nil { 77 | a._pool.Close() 78 | } 79 | } 80 | 81 | func newAdapter(network string, address string, key string, 82 | username string, password string) (*Adapter, error) { 83 | a := &Adapter{} 84 | a.network = network 85 | a.address = address 86 | a.key = key 87 | a.username = username 88 | a.password = password 89 | 90 | // Open the DB, create it if not existed. 91 | err := a.open() 92 | 93 | // Call the destructor when the object is released. 94 | runtime.SetFinalizer(a, finalizer) 95 | 96 | return a, err 97 | } 98 | 99 | // NewAdapter is the constructor for Adapter. 100 | func NewAdapter(network string, address string) (*Adapter, error) { 101 | return newAdapter(network, address, "casbin_rules", "", "") 102 | } 103 | 104 | func NewAdapterWithUser(network string, address string, username string, password string) (*Adapter, error) { 105 | return newAdapter(network, address, "casbin_rules", username, password) 106 | } 107 | 108 | // NewAdapterWithPassword is the constructor for Adapter. 109 | func NewAdapterWithPassword(network string, address string, password string) (*Adapter, error) { 110 | return newAdapter(network, address, "casbin_rules", "", password) 111 | } 112 | 113 | // NewAdapterWithKey is the constructor for Adapter. 114 | func NewAdapterWithKey(network string, address string, key string) (*Adapter, error) { 115 | return newAdapter(network, address, key, "", "") 116 | } 117 | 118 | // NewAdapterWithPool is the constructor for Adapter. 119 | func NewAdapterWithPool(pool *redis.Pool) (*Adapter, error) { 120 | a := &Adapter{} 121 | a.key = "casbin_rules" 122 | 123 | conn := pool.Get() 124 | defer a.release(conn) 125 | 126 | a._conn = conn 127 | a._pool = pool 128 | 129 | // Call the destructor when the object is released. 130 | runtime.SetFinalizer(a, finalizer) 131 | 132 | return a, nil 133 | } 134 | 135 | // NewAdapterWithPoolAndOptions is the constructor for Adapter. 136 | func NewAdapterWithPoolAndOptions(pool *redis.Pool, options ...Option) (*Adapter, error) { 137 | a := &Adapter{} 138 | a.key = "casbin_rules" 139 | for _, option := range options { 140 | option(a) 141 | } 142 | 143 | conn := pool.Get() 144 | defer a.release(conn) 145 | 146 | a._conn = conn 147 | a._pool = pool 148 | 149 | // Call the destructor when the object is released. 150 | runtime.SetFinalizer(a, finalizer) 151 | 152 | return a, nil 153 | } 154 | 155 | type Option func(*Adapter) 156 | 157 | func NewAdapterWithOption(options ...Option) (*Adapter, error) { 158 | a := &Adapter{} 159 | for _, option := range options { 160 | option(a) 161 | } 162 | // Open the DB, create it if not existed. 163 | err := a.open() 164 | 165 | // Call the destructor when the object is released. 166 | runtime.SetFinalizer(a, finalizer) 167 | 168 | return a, err 169 | } 170 | 171 | func WithAddress(address string) Option { 172 | return func(a *Adapter) { 173 | a.address = address 174 | } 175 | } 176 | 177 | func WithUsername(username string) Option { 178 | return func(a *Adapter) { 179 | a.username = username 180 | } 181 | } 182 | 183 | func WithPassword(password string) Option { 184 | return func(a *Adapter) { 185 | a.password = password 186 | } 187 | } 188 | 189 | func WithNetwork(network string) Option { 190 | return func(a *Adapter) { 191 | a.network = network 192 | } 193 | } 194 | func WithKey(key string) Option { 195 | return func(a *Adapter) { 196 | a.key = key 197 | } 198 | } 199 | 200 | func WithTls(tlsConfig *tls.Config) Option { 201 | return func(a *Adapter) { 202 | a.tlsConfig = tlsConfig 203 | } 204 | } 205 | 206 | func (a *Adapter) open() error { 207 | //redis.Dial("tcp", "127.0.0.1:6379") 208 | useTls := a.tlsConfig != nil 209 | if a.username != "" { 210 | conn, err := redis.Dial(a.network, a.address, redis.DialUsername(a.username), redis.DialPassword(a.password), redis.DialTLSConfig(a.tlsConfig), redis.DialUseTLS(useTls)) 211 | if err != nil { 212 | return err 213 | } 214 | 215 | a._conn = conn 216 | } else if a.password == "" { 217 | conn, err := redis.Dial(a.network, a.address, redis.DialTLSConfig(a.tlsConfig), redis.DialUseTLS(useTls)) 218 | if err != nil { 219 | return err 220 | } 221 | 222 | a._conn = conn 223 | } else { 224 | conn, err := redis.Dial(a.network, a.address, redis.DialPassword(a.password), redis.DialTLSConfig(a.tlsConfig), redis.DialUseTLS(useTls)) 225 | if err != nil { 226 | return err 227 | } 228 | 229 | a._conn = conn 230 | } 231 | return nil 232 | } 233 | 234 | func (a *Adapter) close() { 235 | if a._conn != nil { 236 | a._conn.Close() 237 | } 238 | if a._pool != nil { 239 | a._pool.Close() 240 | } 241 | } 242 | 243 | func (a *Adapter) createTable() { 244 | } 245 | 246 | func (a *Adapter) dropTable() { 247 | conn := a.getConn() 248 | defer a.release(conn) 249 | 250 | _, _ = conn.Do("DEL", a.key) 251 | } 252 | 253 | func (c *CasbinRule) toStringPolicy() []string { 254 | policy := make([]string, 0) 255 | if c.PType != "" { 256 | policy = append(policy, c.PType) 257 | } 258 | if c.V0 != "" { 259 | policy = append(policy, c.V0) 260 | } 261 | if c.V1 != "" { 262 | policy = append(policy, c.V1) 263 | } 264 | if c.V2 != "" { 265 | policy = append(policy, c.V2) 266 | } 267 | if c.V3 != "" { 268 | policy = append(policy, c.V3) 269 | } 270 | if c.V4 != "" { 271 | policy = append(policy, c.V4) 272 | } 273 | if c.V5 != "" { 274 | policy = append(policy, c.V5) 275 | } 276 | return policy 277 | } 278 | 279 | func loadPolicyLine(line CasbinRule, model model.Model) { 280 | text := line.toStringPolicy() 281 | 282 | persist.LoadPolicyArray(text, model) 283 | } 284 | 285 | // LoadPolicy loads policy from database. 286 | func (a *Adapter) LoadPolicy(model model.Model) error { 287 | conn := a.getConn() 288 | defer a.release(conn) 289 | 290 | num, err := redis.Int(conn.Do("LLEN", a.key)) 291 | if err == redis.ErrNil { 292 | return nil 293 | } 294 | if err != nil { 295 | return err 296 | } 297 | values, err := redis.Values(conn.Do("LRANGE", a.key, 0, num)) 298 | if err != nil { 299 | return err 300 | } 301 | 302 | var line CasbinRule 303 | for _, value := range values { 304 | text, ok := value.([]byte) 305 | if !ok { 306 | // Amazon MemoryDB for Redis returns string instead of []byte 307 | if textStr, ok := value.(string); ok { 308 | text = []byte(textStr) 309 | } else { 310 | return errors.New("the type is wrong") 311 | } 312 | } 313 | err = json.Unmarshal(text, &line) 314 | if err != nil { 315 | return err 316 | } 317 | loadPolicyLine(line, model) 318 | } 319 | 320 | a.isFiltered = false 321 | return nil 322 | } 323 | 324 | func savePolicyLine(ptype string, rule []string) CasbinRule { 325 | line := CasbinRule{} 326 | 327 | line.PType = ptype 328 | if len(rule) > 0 { 329 | line.V0 = rule[0] 330 | } 331 | if len(rule) > 1 { 332 | line.V1 = rule[1] 333 | } 334 | if len(rule) > 2 { 335 | line.V2 = rule[2] 336 | } 337 | if len(rule) > 3 { 338 | line.V3 = rule[3] 339 | } 340 | if len(rule) > 4 { 341 | line.V4 = rule[4] 342 | } 343 | if len(rule) > 5 { 344 | line.V5 = rule[5] 345 | } 346 | 347 | return line 348 | } 349 | 350 | // SavePolicy saves policy to database. 351 | func (a *Adapter) SavePolicy(model model.Model) error { 352 | a.dropTable() 353 | a.createTable() 354 | 355 | var texts [][]byte 356 | 357 | for ptype, ast := range model["p"] { 358 | for _, rule := range ast.Policy { 359 | line := savePolicyLine(ptype, rule) 360 | text, err := json.Marshal(line) 361 | if err != nil { 362 | return err 363 | } 364 | texts = append(texts, text) 365 | } 366 | } 367 | 368 | for ptype, ast := range model["g"] { 369 | for _, rule := range ast.Policy { 370 | line := savePolicyLine(ptype, rule) 371 | text, err := json.Marshal(line) 372 | if err != nil { 373 | return err 374 | } 375 | texts = append(texts, text) 376 | } 377 | } 378 | 379 | conn := a.getConn() 380 | defer a.release(conn) 381 | 382 | _, err := conn.Do("RPUSH", redis.Args{}.Add(a.key).AddFlat(texts)...) 383 | return err 384 | } 385 | 386 | // AddPolicy adds a policy rule to the storage. 387 | func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error { 388 | line := savePolicyLine(ptype, rule) 389 | text, err := json.Marshal(line) 390 | if err != nil { 391 | return err 392 | } 393 | 394 | conn := a.getConn() 395 | defer a.release(conn) 396 | 397 | _, err = conn.Do("RPUSH", a.key, text) 398 | return err 399 | } 400 | 401 | // RemovePolicy removes a policy rule from the storage. 402 | func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error { 403 | line := savePolicyLine(ptype, rule) 404 | text, err := json.Marshal(line) 405 | if err != nil { 406 | return err 407 | } 408 | 409 | conn := a.getConn() 410 | defer a.release(conn) 411 | 412 | _, err = conn.Do("LREM", a.key, 1, text) 413 | return err 414 | } 415 | 416 | // AddPolicies adds policy rules to the storage. 417 | func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error { 418 | var texts [][]byte 419 | for _, rule := range rules { 420 | line := savePolicyLine(ptype, rule) 421 | text, err := json.Marshal(line) 422 | if err != nil { 423 | return err 424 | } 425 | texts = append(texts, text) 426 | } 427 | 428 | conn := a.getConn() 429 | defer a.release(conn) 430 | 431 | _, err := conn.Do("RPUSH", redis.Args{}.Add(a.key).AddFlat(texts)...) 432 | return err 433 | } 434 | 435 | // RemovePolicies removes policy rules from the storage. 436 | func (a *Adapter) RemovePolicies(sec string, ptype string, rules [][]string) error { 437 | conn := a.getConn() 438 | defer a.release(conn) 439 | 440 | for _, rule := range rules { 441 | line := savePolicyLine(ptype, rule) 442 | text, err := json.Marshal(line) 443 | if err != nil { 444 | return err 445 | } 446 | _, err = conn.Do("LREM", a.key, 1, text) 447 | if err != nil { 448 | return err 449 | } 450 | } 451 | return nil 452 | } 453 | 454 | //FilteredAdapter 455 | 456 | // IsFiltered returns true if the loaded policy has been filtered. 457 | func (a *Adapter) IsFiltered() bool { 458 | return a.isFiltered 459 | } 460 | 461 | type Filter struct { 462 | PType []string 463 | V0 []string 464 | V1 []string 465 | V2 []string 466 | V3 []string 467 | V4 []string 468 | V5 []string 469 | } 470 | 471 | func filterToRegexPattern(filter *Filter) string { 472 | // example data in redis: {"PType":"p","V0":"data2_admin","V1":"data2","V2":"write","V3":"","V4":"","V5":""} 473 | 474 | var f = [][]string{filter.PType, 475 | filter.V0, filter.V1, filter.V2, 476 | filter.V3, filter.V4, filter.V5} 477 | 478 | args := []interface{}{} 479 | for _, v := range f { 480 | if len(v) == 0 { 481 | args = append(args, ".*") 482 | } else { 483 | escapedV := make([]string, 0, len(v)) 484 | for _, s := range v { 485 | escapedV = append(escapedV, regexp.QuoteMeta(s)) 486 | } 487 | args = append(args, "(?:"+strings.Join(escapedV, "|")+")") // (?:data2_admin|data1_admin) 488 | } 489 | } 490 | 491 | // example pattern: 492 | //^\{"PType":".*","V0":"(?:data2_admin|data1_admin)","V1":".*","V2":".*","V3":".*","V4":".*","V5":".*"\}$ 493 | pattern := fmt.Sprintf( 494 | `^\{"PType":"%s","V0":"%s","V1":"%s","V2":"%s","V3":"%s","V4":"%s","V5":"%s"\}$`, args..., 495 | ) 496 | return pattern 497 | } 498 | 499 | func escapeLuaPattern(s string) string { 500 | var buf bytes.Buffer 501 | for _, char := range s { 502 | switch char { 503 | case '.', '%', '-', '+', '*', '?', '^', '$', '(', ')', '[', ']': // magic chars: . % + - * ? [ ( ) ^ $ 504 | buf.WriteRune('%') 505 | } 506 | buf.WriteRune(char) 507 | } 508 | return buf.String() 509 | } 510 | 511 | func filterFieldToLuaPattern(sec string, ptype string, fieldIndex int, fieldValues ...string) string { 512 | args := []interface{}{ptype} 513 | 514 | idx := fieldIndex + len(fieldValues) 515 | for i := 0; i < 6; i++ { // v0-v5 516 | if fieldIndex <= i && idx > i && fieldValues[i-fieldIndex] != "" { 517 | args = append(args, escapeLuaPattern(fieldValues[i-fieldIndex])) 518 | } else { 519 | args = append(args, ".*") 520 | } 521 | } 522 | 523 | // example pattern: 524 | // ^{"PType":"p","V0":"data2_admin","V1":".*","V2":".*","V3":".*","V4":".*","V5":".*"}$ 525 | pattern := fmt.Sprintf( 526 | `^{"PType":"%s","V0":"%s","V1":"%s","V2":"%s","V3":"%s","V4":"%s","V5":"%s"}$`, args..., 527 | ) 528 | return pattern 529 | } 530 | 531 | func (a *Adapter) loadFilteredPolicy(model model.Model, filter *Filter) error { 532 | conn := a.getConn() 533 | defer a.release(conn) 534 | 535 | num, err := redis.Int(conn.Do("LLEN", a.key)) 536 | if err == redis.ErrNil { 537 | return nil 538 | } 539 | if err != nil { 540 | return err 541 | } 542 | values, err := redis.Values(conn.Do("LRANGE", a.key, 0, num)) 543 | if err != nil { 544 | return err 545 | } 546 | 547 | re := regexp.MustCompile(filterToRegexPattern(filter)) 548 | 549 | var line CasbinRule 550 | for _, value := range values { 551 | text, ok := value.([]byte) 552 | if !ok { 553 | // Amazon MemoryDB for Redis returns string instead of []byte 554 | if textStr, ok := value.(string); ok { 555 | text = []byte(textStr) 556 | } else { 557 | return errors.New("the type is wrong") 558 | } 559 | } 560 | 561 | if !re.Match(text) { 562 | continue 563 | } 564 | 565 | err = json.Unmarshal(text, &line) 566 | if err != nil { 567 | return err 568 | } 569 | loadPolicyLine(line, model) 570 | } 571 | return nil 572 | } 573 | 574 | // LoadFilteredPolicy loads only policy rules that match the filter. 575 | func (a *Adapter) LoadFilteredPolicy(model model.Model, filter interface{}) error { 576 | if filter == nil { 577 | return a.LoadPolicy(model) 578 | } 579 | 580 | var err error 581 | switch f := filter.(type) { 582 | case *Filter: 583 | err = a.loadFilteredPolicy(model, f) 584 | case Filter: 585 | err = a.loadFilteredPolicy(model, &f) 586 | default: 587 | err = fmt.Errorf("invalid filter type") 588 | } 589 | 590 | if err != nil { 591 | return err 592 | } 593 | a.isFiltered = true 594 | return nil 595 | } 596 | 597 | // RemoveFilteredPolicy removes policy rules that match the filter from the storage. 598 | func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error { 599 | 600 | pattern := filterFieldToLuaPattern(sec, ptype, fieldIndex, fieldValues...) 601 | 602 | var getScript = redis.NewScript(1, ` 603 | local key = KEYS[1] 604 | local pattern = ARGV[1] 605 | 606 | local r = redis.call('lrange', key, 0, -1) 607 | for i=1, #r do 608 | if string.find(r[i], pattern) then 609 | redis.call('lset', key, i-1, '__CASBIN_DELETED__') 610 | end 611 | end 612 | redis.call('lrem', key, 0, '__CASBIN_DELETED__') 613 | return 614 | `) 615 | 616 | conn := a.getConn() 617 | defer a.release(conn) 618 | 619 | _, err := getScript.Do(conn, a.key, pattern) 620 | return err 621 | } 622 | 623 | // UpdatableAdapter 624 | 625 | // UpdatePolicy updates a new policy rule to DB. 626 | func (a *Adapter) UpdatePolicy(sec string, ptype string, oldRule, newPolicy []string) error { 627 | oldLine := savePolicyLine(ptype, oldRule) 628 | textOld, err := json.Marshal(oldLine) 629 | if err != nil { 630 | return err 631 | } 632 | newLine := savePolicyLine(ptype, newPolicy) 633 | textNew, err := json.Marshal(newLine) 634 | if err != nil { 635 | return err 636 | } 637 | 638 | var getScript = redis.NewScript(1, ` 639 | local key = KEYS[1] 640 | local old = ARGV[1] 641 | local newRule = ARGV[2] 642 | 643 | local r = redis.call('lrange', key, 0, -1) 644 | for i=1,#r do 645 | if r[i] == old then 646 | redis.call('lset', key, i-1, newRule) 647 | return true 648 | end 649 | end 650 | return false 651 | `) 652 | 653 | conn := a.getConn() 654 | defer a.release(conn) 655 | 656 | _, err = getScript.Do(conn, a.key, textOld, textNew) 657 | return err 658 | } 659 | 660 | func (a *Adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error { 661 | 662 | if len(oldRules) != len(newRules) { 663 | return errors.New("oldRules and newRules should have the same length") 664 | } 665 | 666 | oldPolicies := make([]string, 0, len(oldRules)) 667 | newPolicies := make([]string, 0, len(newRules)) 668 | for _, oldRule := range oldRules { 669 | textOld, err := json.Marshal(savePolicyLine(ptype, oldRule)) 670 | if err != nil { 671 | return err 672 | } 673 | oldPolicies = append(oldPolicies, string(textOld)) 674 | } 675 | for _, newRule := range newRules { 676 | textNew, err := json.Marshal(savePolicyLine(ptype, newRule)) 677 | if err != nil { 678 | return err 679 | } 680 | newPolicies = append(newPolicies, string(textNew)) 681 | } 682 | 683 | // Initialize a package-level variable with a script. 684 | var getScript = redis.NewScript(1, ` 685 | local key = KEYS[1] 686 | local len = #ARGV/2 687 | 688 | local map = {} 689 | for i = 1, len, 1 do 690 | map[ARGV[i]] = ARGV[i + len] -- map[oldRule] = newRule 691 | end 692 | 693 | local r = redis.call('lrange', key, 0, -1) 694 | for i=1,#r do 695 | if map[r[i]] ~= nil then 696 | redis.call('lset', key, i-1, map[r[i]]) 697 | -- return true 698 | end 699 | end 700 | 701 | return false 702 | `) 703 | args := redis.Args{}.Add(a.key).AddFlat(oldPolicies).AddFlat(newPolicies) 704 | 705 | conn := a.getConn() 706 | defer a.release(conn) 707 | 708 | _, err := getScript.Do(conn, args...) 709 | return err 710 | } 711 | 712 | func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newPolicies [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) { 713 | // UpdateFilteredPolicies deletes old rules and adds new rules. 714 | 715 | oldP := make([]string, 0) 716 | newP := make([]string, 0, len(newPolicies)) 717 | for _, newRule := range newPolicies { 718 | textNew, err := json.Marshal(savePolicyLine(ptype, newRule)) 719 | if err != nil { 720 | return nil, err 721 | } 722 | newP = append(newP, string(textNew)) 723 | } 724 | 725 | pattern := filterFieldToLuaPattern(sec, ptype, fieldIndex, fieldValues...) 726 | 727 | // Initialize a package-level variable with a script. 728 | var getScript = redis.NewScript(1, ` 729 | local key = KEYS[1] 730 | local pattern = ARGV[1] 731 | 732 | local ret = {} 733 | local r = redis.call('lrange', key, 0, -1) 734 | for i=1, #r do 735 | if string.find(r[i], pattern) then 736 | table.insert(ret, r[i]) 737 | redis.call('lset', key, i-1, '__CASBIN_DELETED__') 738 | end 739 | end 740 | redis.call('lrem', key, 0, '__CASBIN_DELETED__') 741 | 742 | local r = redis.call('lrange', key, 0, -1) 743 | for i=2,#r do 744 | redis.call('rpush', key, ARGV[i]) 745 | end 746 | 747 | return ret 748 | `) 749 | args := redis.Args{}.Add(a.key).Add(pattern).AddFlat(newP) 750 | //r, err := getScript.Do(a.conn, args...) 751 | //reply, err := redis.Values(r, err) 752 | 753 | conn := a.getConn() 754 | defer a.release(conn) 755 | 756 | reply, err := redis.Values(getScript.Do(conn, args...)) 757 | if err != nil { 758 | return nil, err 759 | } 760 | 761 | if err = redis.ScanSlice(reply, &oldP); err != nil { 762 | return nil, err 763 | } 764 | 765 | ret := make([][]string, 0, len(oldP)) 766 | for _, oldRule := range oldP { 767 | var line CasbinRule 768 | if err := json.Unmarshal([]byte(oldRule), &line); err != nil { 769 | return nil, err 770 | } 771 | 772 | ret = append(ret, line.toStringPolicy()) 773 | } 774 | 775 | return ret, nil 776 | } 777 | -------------------------------------------------------------------------------- /adapter_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The casbin 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 redisadapter 16 | 17 | import ( 18 | "log" 19 | "strings" 20 | "testing" 21 | 22 | "github.com/casbin/casbin/v2" 23 | "github.com/casbin/casbin/v2/util" 24 | "github.com/gomodule/redigo/redis" 25 | ) 26 | 27 | func testGetPolicy(t *testing.T, e *casbin.Enforcer, res [][]string) { 28 | t.Helper() 29 | myRes := e.GetPolicy() 30 | log.Print("Policy: ", myRes) 31 | 32 | m := make(map[string]bool, len(res)) 33 | for _, value := range res { 34 | key := strings.Join(value, ",") 35 | m[key] = true 36 | } 37 | 38 | for _, value := range myRes { 39 | key := strings.Join(value, ",") 40 | if !m[key] { 41 | t.Error("Policy: ", myRes, ", supposed to be ", res) 42 | break 43 | } 44 | } 45 | } 46 | 47 | func initPolicy(t *testing.T, a *Adapter) { 48 | // Because the DB is empty at first, 49 | // so we need to load the policy from the file adapter (.CSV) first. 50 | e, _ := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv") 51 | 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, a *Adapter) { 73 | // Initialize some policy in DB. 74 | initPolicy(t, a) 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 | e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) 82 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) 83 | } 84 | 85 | func testAutoSave(t *testing.T, a *Adapter) { 86 | // Initialize some policy in DB. 87 | initPolicy(t, a) 88 | // Note: you don't need to look at the above code 89 | // if you already have a working DB with policy inside. 90 | 91 | // Now the DB has policy, so we can provide a normal use case. 92 | // Create an adapter and an enforcer. 93 | // NewEnforcer() will load the policy automatically. 94 | e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) 95 | 96 | // AutoSave is enabled by default. 97 | // Now we disable it. 98 | e.EnableAutoSave(false) 99 | 100 | var err error 101 | logErr := func(action string) { 102 | if err != nil { 103 | t.Fatalf("test action[%s] failed, err: %v", action, err) 104 | } 105 | } 106 | 107 | // Because AutoSave is disabled, the policy change only affects the policy in Casbin enforcer, 108 | // it doesn't affect the policy in the storage. 109 | _, err = e.AddPolicy("alice", "data1", "write") 110 | logErr("AddPolicy") 111 | // Reload the policy from the storage to see the effect. 112 | err = e.LoadPolicy() 113 | logErr("LoadPolicy") 114 | // This is still the original policy. 115 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) 116 | 117 | // Now we enable the AutoSave. 118 | e.EnableAutoSave(true) 119 | 120 | // Because AutoSave is enabled, the policy change not only affects the policy in Casbin enforcer, 121 | // but also affects the policy in the storage. 122 | _, err = e.AddPolicy("alice", "data1", "write") 123 | logErr("AddPolicy2") 124 | // Reload the policy from the storage to see the effect. 125 | err = e.LoadPolicy() 126 | logErr("LoadPolicy2") 127 | // The policy has a new rule: {"alice", "data1", "write"}. 128 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}, {"alice", "data1", "write"}}) 129 | 130 | // Remove the added rule. 131 | _, err = e.RemovePolicy("alice", "data1", "write") 132 | logErr("RemovePolicy") 133 | err = e.LoadPolicy() 134 | logErr("LoadPolicy3") 135 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) 136 | 137 | // Remove "data2_admin" related policy rules via a filter. 138 | // Two rules: {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"} are deleted. 139 | _, err = e.RemoveFilteredPolicy(0, "data2_admin") 140 | logErr("RemoveFilteredPolicy") 141 | err = e.LoadPolicy() 142 | logErr("LoadPolicy4") 143 | 144 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}}) 145 | } 146 | 147 | func testFilteredPolicy(t *testing.T, a *Adapter) { 148 | // Initialize some policy in DB. 149 | initPolicy(t, a) 150 | // Note: you don't need to look at the above code 151 | // if you already have a working DB with policy inside. 152 | 153 | // Now the DB has policy, so we can provide a normal use case. 154 | // Create an adapter and an enforcer. 155 | // NewEnforcer() will load the policy automatically. 156 | e, _ := casbin.NewEnforcer("examples/rbac_model.conf") 157 | // Now set the adapter 158 | e.SetAdapter(a) 159 | 160 | var err error 161 | logErr := func(action string) { 162 | if err != nil { 163 | t.Fatalf("test action[%s] failed, err: %v", action, err) 164 | } 165 | } 166 | 167 | // Load only alice's policies 168 | err = e.LoadFilteredPolicy(Filter{V0: []string{"alice"}}) 169 | logErr("LoadFilteredPolicy") 170 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}}) 171 | 172 | // Load only bob's policies 173 | err = e.LoadFilteredPolicy(Filter{V0: []string{"bob"}}) 174 | logErr("LoadFilteredPolicy2") 175 | testGetPolicy(t, e, [][]string{{"bob", "data2", "write"}}) 176 | 177 | // Load policies for data2_admin 178 | err = e.LoadFilteredPolicy(Filter{V0: []string{"data2_admin"}}) 179 | logErr("LoadFilteredPolicy3") 180 | testGetPolicy(t, e, [][]string{{"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) 181 | 182 | // Load policies for alice and bob 183 | err = e.LoadFilteredPolicy(Filter{V0: []string{"alice", "bob"}}) 184 | logErr("LoadFilteredPolicy4") 185 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}}) 186 | } 187 | 188 | func testRemovePolicies(t *testing.T, a *Adapter) { 189 | // Initialize some policy in DB. 190 | initPolicy(t, a) 191 | // Note: you don't need to look at the above code 192 | // if you already have a working DB with policy inside. 193 | 194 | // Now the DB has policy, so we can provide a normal use case. 195 | // Create an adapter and an enforcer. 196 | // NewEnforcer() will load the policy automatically. 197 | e, _ := casbin.NewEnforcer("examples/rbac_model.conf") 198 | 199 | // Now set the adapter 200 | e.SetAdapter(a) 201 | 202 | var err error 203 | logErr := func(action string) { 204 | if err != nil { 205 | t.Fatalf("test action[%s] failed, err: %v", action, err) 206 | } 207 | } 208 | 209 | err = a.AddPolicies("p", "p", [][]string{{"max", "data2", "read"}, {"max", "data1", "write"}, {"max", "data1", "delete"}}) 210 | logErr("AddPolicies") 211 | 212 | // Load policies for max 213 | err = e.LoadFilteredPolicy(Filter{V0: []string{"max"}}) 214 | logErr("LoadFilteredPolicy") 215 | 216 | testGetPolicy(t, e, [][]string{{"max", "data2", "read"}, {"max", "data1", "write"}, {"max", "data1", "delete"}}) 217 | 218 | // Remove policies 219 | err = a.RemovePolicies("p", "p", [][]string{{"max", "data2", "read"}, {"max", "data1", "write"}}) 220 | logErr("RemovePolicies") 221 | 222 | // Reload policies for max 223 | err = e.LoadFilteredPolicy(Filter{V0: []string{"max"}}) 224 | logErr("LoadFilteredPolicy2") 225 | 226 | testGetPolicy(t, e, [][]string{{"max", "data1", "delete"}}) 227 | } 228 | 229 | func testAddPolicies(t *testing.T, a *Adapter) { 230 | // Initialize some policy in DB. 231 | initPolicy(t, a) 232 | // Note: you don't need to look at the above code 233 | // if you already have a working DB with policy inside. 234 | 235 | // Now the DB has policy, so we can provide a normal use case. 236 | // Create an adapter and an enforcer. 237 | // NewEnforcer() will load the policy automatically. 238 | e, _ := casbin.NewEnforcer("examples/rbac_model.conf") 239 | 240 | // Now set the adapter 241 | e.SetAdapter(a) 242 | 243 | var err error 244 | logErr := func(action string) { 245 | if err != nil { 246 | t.Fatalf("test action[%s] failed, err: %v", action, err) 247 | } 248 | } 249 | 250 | err = a.AddPolicies("p", "p", [][]string{{"max", "data2", "read"}, {"max", "data1", "write"}}) 251 | logErr("AddPolicies") 252 | 253 | // Load policies for max 254 | err = e.LoadFilteredPolicy(Filter{V0: []string{"max"}}) 255 | logErr("LoadFilteredPolicy") 256 | 257 | testGetPolicy(t, e, [][]string{{"max", "data2", "read"}, {"max", "data1", "write"}}) 258 | } 259 | 260 | func testUpdatePolicies(t *testing.T, a *Adapter) { 261 | // Initialize some policy in DB. 262 | initPolicy(t, a) 263 | // Note: you don't need to look at the above code 264 | // if you already have a working DB with policy inside. 265 | 266 | // Now the DB has policy, so we can provide a normal use case. 267 | // Create an adapter and an enforcer. 268 | // NewEnforcer() will load the policy automatically. 269 | e, _ := casbin.NewEnforcer("examples/rbac_model.conf") 270 | 271 | // Now set the adapter 272 | e.SetAdapter(a) 273 | 274 | var err error 275 | logErr := func(action string) { 276 | if err != nil { 277 | t.Fatalf("test action[%s] failed, err: %v", action, err) 278 | } 279 | } 280 | 281 | err = a.UpdatePolicy("p", "p", []string{"bob", "data2", "write"}, []string{"alice", "data2", "write"}) 282 | logErr("UpdatePolicy") 283 | 284 | testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"alice", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) 285 | 286 | err = a.UpdatePolicies("p", "p", [][]string{{"alice", "data1", "read"}, {"alice", "data2", "write"}}, [][]string{{"bob", "data1", "read"}, {"bob", "data2", "write"}}) 287 | logErr("UpdatePolicies") 288 | 289 | testGetPolicy(t, e, [][]string{{"bob", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}}) 290 | } 291 | 292 | func testUpdateFilteredPolicies(t *testing.T, a *Adapter) { 293 | // Initialize some policy in DB. 294 | initPolicy(t, a) 295 | // Note: you don't need to look at the above code 296 | // if you already have a working DB with policy inside. 297 | 298 | // Now the DB has policy, so we can provide a normal use case. 299 | // Create an adapter and an enforcer. 300 | // NewEnforcer() will load the policy automatically. 301 | e, _ := casbin.NewEnforcer("examples/rbac_model.conf") 302 | 303 | // Now set the adapter 304 | e.SetAdapter(a) 305 | 306 | e.UpdateFilteredPolicies([][]string{{"alice", "data1", "write"}}, 0, "alice", "data1", "read") 307 | e.UpdateFilteredPolicies([][]string{{"bob", "data2", "read"}}, 0, "bob", "data2", "write") 308 | e.LoadPolicy() 309 | testGetPolicyWithoutOrder(t, e, [][]string{{"alice", "data1", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}, {"bob", "data2", "read"}}) 310 | } 311 | 312 | func testGetPolicyWithoutOrder(t *testing.T, e *casbin.Enforcer, res [][]string) { 313 | myRes := e.GetPolicy() 314 | log.Print("Policy: ", myRes) 315 | 316 | if !arrayEqualsWithoutOrder(myRes, res) { 317 | t.Error("Policy: ", myRes, ", supposed to be ", res) 318 | } 319 | } 320 | 321 | func arrayEqualsWithoutOrder(a [][]string, b [][]string) bool { 322 | if len(a) != len(b) { 323 | return false 324 | } 325 | 326 | mapA := make(map[int]string) 327 | mapB := make(map[int]string) 328 | order := make(map[int]struct{}) 329 | l := len(a) 330 | 331 | for i := 0; i < l; i++ { 332 | mapA[i] = util.ArrayToString(a[i]) 333 | mapB[i] = util.ArrayToString(b[i]) 334 | } 335 | 336 | for i := 0; i < l; i++ { 337 | for j := 0; j < l; j++ { 338 | if _, ok := order[j]; ok { 339 | if j == l-1 { 340 | return false 341 | } else { 342 | continue 343 | } 344 | } 345 | if mapA[i] == mapB[j] { 346 | order[j] = struct{}{} 347 | break 348 | } else if j == l-1 { 349 | return false 350 | } 351 | } 352 | } 353 | return true 354 | } 355 | 356 | func TestAdapters(t *testing.T) { 357 | a, _ := NewAdapter("tcp", "127.0.0.1:6379") 358 | 359 | // Use the following if Redis has password like "123" 360 | // a, err := NewAdapterWithPassword("tcp", "127.0.0.1:6379", "123") 361 | 362 | // Use the following if you use Redis with a account 363 | // a, err := NewAdapterWithUser("tcp", "127.0.0.1:6379", "testaccount", "userpass") 364 | testSaveLoad(t, a) 365 | testAutoSave(t, a) 366 | testFilteredPolicy(t, a) 367 | testAddPolicies(t, a) 368 | testRemovePolicies(t, a) 369 | testUpdatePolicies(t, a) 370 | testUpdateFilteredPolicies(t, a) 371 | } 372 | 373 | func TestAdapterWithOption(t *testing.T) { 374 | a, _ := NewAdapterWithOption(WithNetwork("tcp"), WithAddress("127.0.0.1:6379")) 375 | // User the following if use TLS to connect to redis 376 | // var clientTLSConfig tls.Config 377 | // a, err := NewAdapterWithOption(WithTls(&clientTLSConfig)) 378 | 379 | testSaveLoad(t, a) 380 | testAutoSave(t, a) 381 | testFilteredPolicy(t, a) 382 | testAddPolicies(t, a) 383 | testRemovePolicies(t, a) 384 | testUpdatePolicies(t, a) 385 | testUpdateFilteredPolicies(t, a) 386 | } 387 | 388 | func TestPoolAdapters(t *testing.T) { 389 | a, err := NewAdapterWithPool(&redis.Pool{ 390 | Dial: func() (redis.Conn, error) { 391 | return redis.Dial("tcp", "127.0.0.1:6379") 392 | }, 393 | }) 394 | if err != nil { 395 | t.Fatal(err) 396 | } 397 | 398 | testSaveLoad(t, a) 399 | testAutoSave(t, a) 400 | testFilteredPolicy(t, a) 401 | testAddPolicies(t, a) 402 | testRemovePolicies(t, a) 403 | testUpdatePolicies(t, a) 404 | testUpdateFilteredPolicies(t, a) 405 | } 406 | 407 | func TestPoolAndOptionsAdapters(t *testing.T) { 408 | a, err := NewAdapterWithPoolAndOptions(&redis.Pool{ 409 | Dial: func() (redis.Conn, error) { 410 | return redis.Dial("tcp", "127.0.0.1:6379") 411 | }, 412 | }, WithKey("casbin:policy:test")) 413 | if err != nil { 414 | t.Fatal(err) 415 | } 416 | 417 | testSaveLoad(t, a) 418 | testAutoSave(t, a) 419 | testFilteredPolicy(t, a) 420 | testAddPolicies(t, a) 421 | testRemovePolicies(t, a) 422 | testUpdatePolicies(t, a) 423 | testUpdateFilteredPolicies(t, a) 424 | } 425 | -------------------------------------------------------------------------------- /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/casbin/redis-adapter/v3 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/casbin/casbin/v2 v2.60.0 7 | github.com/gomodule/redigo v1.8.9 8 | ) 9 | -------------------------------------------------------------------------------- /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.60.0 h1:ZmC0/t4wolfEsDpDxTEsu2z6dfbMNpc11F52ceLs2Eo= 4 | github.com/casbin/casbin/v2 v2.60.0/go.mod h1:vByNa/Fchek0KZUgG5wEsl7iFsiviAYKRtgrQfcJqHg= 5 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 6 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 7 | github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= 8 | github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= 9 | github.com/gomodule/redigo v1.8.9 h1:Sl3u+2BI/kk+VEatbj0scLdrFhjPmbxOc1myhDP41ws= 10 | github.com/gomodule/redigo v1.8.9/go.mod h1:7ArFNvsTjH8GMMzB4uy1snslv2BwmginuMs06a1uzZE= 11 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 12 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 13 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 14 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 15 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 16 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 17 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 18 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 19 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 20 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 21 | golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= 22 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 23 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 24 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 25 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 26 | --------------------------------------------------------------------------------