snapshot of https://github.com/casbin/casbin.git (master, 2026-09-15; blobs > 131072B omitted)
This commit is contained in:
116
persist/adapter.go
Normal file
116
persist/adapter.go
Normal file
@@ -0,0 +1,116 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
)
|
||||
|
||||
// LoadPolicyLine loads a text line as a policy rule to model.
|
||||
func LoadPolicyLine(line string, m model.Model) error {
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
return nil
|
||||
}
|
||||
|
||||
r := csv.NewReader(strings.NewReader(line))
|
||||
r.Comma = ','
|
||||
r.Comment = '#'
|
||||
r.TrimLeadingSpace = true
|
||||
|
||||
tokens, err := r.Read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return LoadPolicyArray(tokens, m)
|
||||
}
|
||||
|
||||
// PolicyLineToCsv serializes a policy type and its rule fields into a CSV-safe line.
|
||||
// Fields are separated by ", " to match the conventional layout of Casbin policy
|
||||
// files, which LoadPolicyLine accepts because its reader trims leading spaces.
|
||||
// Fields containing commas are properly quoted so the line can be round-tripped
|
||||
// through LoadPolicyLine without corruption.
|
||||
func PolicyLineToCsv(ptype string, rule []string) (string, error) {
|
||||
record := append([]string{ptype}, rule...)
|
||||
|
||||
// Each field is written as its own single-field record so that the standard
|
||||
// library decides on quoting, then the fields are joined with ", ".
|
||||
var buf bytes.Buffer
|
||||
w := csv.NewWriter(&buf)
|
||||
fields := make([]string, 0, len(record))
|
||||
for _, field := range record {
|
||||
buf.Reset()
|
||||
if err := w.Write([]string{field}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
w.Flush()
|
||||
if err := w.Error(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
fields = append(fields, strings.TrimRight(buf.String(), "\r\n"))
|
||||
}
|
||||
|
||||
return strings.Join(fields, ", "), nil
|
||||
}
|
||||
|
||||
// LoadPolicyArray loads a policy rule to model.
|
||||
func LoadPolicyArray(rule []string, m model.Model) error {
|
||||
if len(rule) == 0 || rule[0] == "" {
|
||||
return errors.New("invalid policy rule: missing policy type")
|
||||
}
|
||||
|
||||
key := rule[0]
|
||||
sec := key[:1]
|
||||
ok, err := m.HasPolicyEx(sec, key, rule[1:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
return nil // skip duplicated policy
|
||||
}
|
||||
|
||||
err = m.AddPolicy(sec, key, rule[1:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Adapter is the interface for Casbin adapters.
|
||||
type Adapter interface {
|
||||
// LoadPolicy loads all policy rules from the storage.
|
||||
LoadPolicy(model model.Model) error
|
||||
// SavePolicy saves all policy rules to the storage.
|
||||
SavePolicy(model model.Model) error
|
||||
|
||||
// AddPolicy adds a policy rule to the storage.
|
||||
// This is part of the Auto-Save feature.
|
||||
AddPolicy(sec string, ptype string, rule []string) error
|
||||
// RemovePolicy removes a policy rule from the storage.
|
||||
// This is part of the Auto-Save feature.
|
||||
RemovePolicy(sec string, ptype string, rule []string) error
|
||||
// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
|
||||
// This is part of the Auto-Save feature.
|
||||
RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error
|
||||
}
|
||||
42
persist/adapter_context.go
Normal file
42
persist/adapter_context.go
Normal file
@@ -0,0 +1,42 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
)
|
||||
|
||||
// ContextAdapter provides a context-aware interface for Casbin adapters.
|
||||
type ContextAdapter interface {
|
||||
// LoadPolicyCtx loads all policy rules from the storage with context.
|
||||
LoadPolicyCtx(ctx context.Context, model model.Model) error
|
||||
// SavePolicyCtx saves all policy rules to the storage with context.
|
||||
SavePolicyCtx(ctx context.Context, model model.Model) error
|
||||
|
||||
// AddPolicyCtx adds a policy rule to the storage with context.
|
||||
// This is part of the Auto-Save feature.
|
||||
AddPolicyCtx(ctx context.Context, sec string, ptype string, rule []string) error
|
||||
// RemovePolicyCtx removes a policy rule from the storage with context.
|
||||
// This is part of the Auto-Save feature.
|
||||
RemovePolicyCtx(ctx context.Context, sec string, ptype string, rule []string) error
|
||||
// RemoveFilteredPolicyCtx removes policy rules that match the filter from the storage with context.
|
||||
// This is part of the Auto-Save feature.
|
||||
RemoveFilteredPolicyCtx(ctx context.Context, sec string, ptype string, fieldIndex int, fieldValues ...string) error
|
||||
}
|
||||
32
persist/adapter_filtered.go
Normal file
32
persist/adapter_filtered.go
Normal file
@@ -0,0 +1,32 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
import (
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
)
|
||||
|
||||
// FilteredAdapter is the interface for Casbin adapters supporting filtered policies.
|
||||
type FilteredAdapter interface {
|
||||
Adapter
|
||||
|
||||
// LoadFilteredPolicy loads only policy rules that match the filter.
|
||||
LoadFilteredPolicy(model model.Model, filter interface{}) error
|
||||
// IsFiltered returns true if the loaded policy has been filtered.
|
||||
IsFiltered() bool
|
||||
}
|
||||
34
persist/adapter_filtered_context.go
Normal file
34
persist/adapter_filtered_context.go
Normal file
@@ -0,0 +1,34 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
)
|
||||
|
||||
// ContextFilteredAdapter is the context-aware interface for Casbin adapters supporting filtered policies.
|
||||
type ContextFilteredAdapter interface {
|
||||
ContextAdapter
|
||||
|
||||
// LoadFilteredPolicyCtx loads only policy rules that match the filter.
|
||||
LoadFilteredPolicyCtx(ctx context.Context, model model.Model, filter interface{}) error
|
||||
// IsFilteredCtx returns true if the loaded policy has been filtered.
|
||||
IsFilteredCtx(ctx context.Context) bool
|
||||
}
|
||||
29
persist/batch_adapter.go
Normal file
29
persist/batch_adapter.go
Normal file
@@ -0,0 +1,29 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
// BatchAdapter is the interface for Casbin adapters with multiple add and remove policy functions.
|
||||
type BatchAdapter interface {
|
||||
Adapter
|
||||
// AddPolicies adds policy rules to the storage.
|
||||
// This is part of the Auto-Save feature.
|
||||
AddPolicies(sec string, ptype string, rules [][]string) error
|
||||
// RemovePolicies removes policy rules from the storage.
|
||||
// This is part of the Auto-Save feature.
|
||||
RemovePolicies(sec string, ptype string, rules [][]string) error
|
||||
}
|
||||
32
persist/batch_adapter_context.go
Normal file
32
persist/batch_adapter_context.go
Normal file
@@ -0,0 +1,32 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
import "context"
|
||||
|
||||
// ContextBatchAdapter is the context-aware interface for Casbin adapters with multiple add and remove policy functions.
|
||||
type ContextBatchAdapter interface {
|
||||
ContextAdapter
|
||||
|
||||
// AddPoliciesCtx adds policy rules to the storage.
|
||||
// This is part of the Auto-Save feature.
|
||||
AddPoliciesCtx(ctx context.Context, sec string, ptype string, rules [][]string) error
|
||||
// RemovePoliciesCtx removes policy rules from the storage.
|
||||
// This is part of the Auto-Save feature.
|
||||
RemovePoliciesCtx(ctx context.Context, sec string, ptype string, rules [][]string) error
|
||||
}
|
||||
42
persist/cache/cache.go
vendored
Normal file
42
persist/cache/cache.go
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package cache
|
||||
|
||||
import "errors"
|
||||
|
||||
var ErrNoSuchKey = errors.New("there's no such key existing in cache")
|
||||
|
||||
type Cache interface {
|
||||
// Set puts key and value into cache.
|
||||
// First parameter for extra should be time.Time object denoting expected survival time.
|
||||
// If survival time equals 0 or less, the key will always be survival.
|
||||
Set(key string, value bool, extra ...interface{}) error
|
||||
|
||||
// Get returns result for key,
|
||||
// If there's no such key existing in cache,
|
||||
// ErrNoSuchKey will be returned.
|
||||
Get(key string) (bool, error)
|
||||
|
||||
// Delete will remove the specific key in cache.
|
||||
// If there's no such key existing in cache,
|
||||
// ErrNoSuchKey will be returned.
|
||||
Delete(key string) error
|
||||
|
||||
// Clear deletes all the items stored in cache.
|
||||
Clear() error
|
||||
}
|
||||
89
persist/cache/cache_sync.go
vendored
Normal file
89
persist/cache/cache_sync.go
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package cache
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SyncCache struct {
|
||||
cache DefaultCache
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (c *SyncCache) Set(key string, value bool, extra ...interface{}) error {
|
||||
ttl := time.Duration(-1)
|
||||
if len(extra) > 0 {
|
||||
ttl = extra[0].(time.Duration)
|
||||
}
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
c.cache[key] = cacheItem{
|
||||
value: value,
|
||||
expiresAt: time.Now().Add(ttl),
|
||||
ttl: ttl,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *SyncCache) Get(key string) (bool, error) {
|
||||
c.RLock()
|
||||
res, ok := c.cache[key]
|
||||
c.RUnlock()
|
||||
if !ok {
|
||||
return false, ErrNoSuchKey
|
||||
} else {
|
||||
if res.ttl > 0 && time.Now().After(res.expiresAt) {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
delete(c.cache, key)
|
||||
return false, ErrNoSuchKey
|
||||
}
|
||||
return res.value, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SyncCache) Delete(key string) error {
|
||||
c.RLock()
|
||||
_, ok := c.cache[key]
|
||||
c.RUnlock()
|
||||
if !ok {
|
||||
return ErrNoSuchKey
|
||||
} else {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
delete(c.cache, key)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SyncCache) Clear() error {
|
||||
c.Lock()
|
||||
c.cache = make(DefaultCache)
|
||||
c.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewSyncCache() (Cache, error) {
|
||||
cache := SyncCache{
|
||||
make(DefaultCache),
|
||||
sync.RWMutex{},
|
||||
}
|
||||
return &cache, nil
|
||||
}
|
||||
72
persist/cache/default-cache.go
vendored
Normal file
72
persist/cache/default-cache.go
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package cache
|
||||
|
||||
import "time"
|
||||
|
||||
type cacheItem struct {
|
||||
value bool
|
||||
expiresAt time.Time
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
type DefaultCache map[string]cacheItem
|
||||
|
||||
func (c *DefaultCache) Set(key string, value bool, extra ...interface{}) error {
|
||||
ttl := time.Duration(-1)
|
||||
if len(extra) > 0 {
|
||||
ttl = extra[0].(time.Duration)
|
||||
}
|
||||
(*c)[key] = cacheItem{
|
||||
value: value,
|
||||
expiresAt: time.Now().Add(ttl),
|
||||
ttl: ttl,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *DefaultCache) Get(key string) (bool, error) {
|
||||
if res, ok := (*c)[key]; !ok {
|
||||
return false, ErrNoSuchKey
|
||||
} else {
|
||||
if res.ttl > 0 && time.Now().After(res.expiresAt) {
|
||||
delete(*c, key)
|
||||
return false, ErrNoSuchKey
|
||||
}
|
||||
return res.value, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *DefaultCache) Delete(key string) error {
|
||||
if _, ok := (*c)[key]; !ok {
|
||||
return ErrNoSuchKey
|
||||
} else {
|
||||
delete(*c, key)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *DefaultCache) Clear() error {
|
||||
*c = make(DefaultCache)
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewDefaultCache() (Cache, error) {
|
||||
cache := make(DefaultCache)
|
||||
return &cache, nil
|
||||
}
|
||||
36
persist/dispatcher.go
Normal file
36
persist/dispatcher.go
Normal file
@@ -0,0 +1,36 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
// Dispatcher is the interface for Casbin dispatcher.
|
||||
type Dispatcher interface {
|
||||
// AddPolicies adds policies rule to all instance.
|
||||
AddPolicies(sec string, ptype string, rules [][]string) error
|
||||
// RemovePolicies removes policies rule from all instance.
|
||||
RemovePolicies(sec string, ptype string, rules [][]string) error
|
||||
// RemoveFilteredPolicy removes policy rules that match the filter from all instance.
|
||||
RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error
|
||||
// ClearPolicy clears all current policy in all instances
|
||||
ClearPolicy() error
|
||||
// UpdatePolicy updates policy rule from all instance.
|
||||
UpdatePolicy(sec string, ptype string, oldRule, newRule []string) error
|
||||
// UpdatePolicies updates some policy rules from all instance
|
||||
UpdatePolicies(sec string, ptype string, oldrules, newRules [][]string) error
|
||||
// UpdateFilteredPolicies deletes old rules and adds new rules.
|
||||
UpdateFilteredPolicies(sec string, ptype string, oldRules [][]string, newRules [][]string) error
|
||||
}
|
||||
157
persist/file-adapter/adapter.go
Normal file
157
persist/file-adapter/adapter.go
Normal file
@@ -0,0 +1,157 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package fileadapter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
"github.com/casbin/casbin/v3/persist"
|
||||
)
|
||||
|
||||
// Adapter is the file adapter for Casbin.
|
||||
// It can load policy from file or save policy to file.
|
||||
type Adapter struct {
|
||||
filePath string
|
||||
}
|
||||
|
||||
func (a *Adapter) UpdatePolicy(sec string, ptype string, oldRule, newRule []string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (a *Adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) {
|
||||
return nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
// NewAdapter is the constructor for Adapter.
|
||||
func NewAdapter(filePath string) *Adapter {
|
||||
return &Adapter{filePath: filePath}
|
||||
}
|
||||
|
||||
// LoadPolicy loads all policy rules from the storage.
|
||||
func (a *Adapter) LoadPolicy(model model.Model) error {
|
||||
if a.filePath == "" {
|
||||
return errors.New("invalid file path, file path cannot be empty")
|
||||
}
|
||||
|
||||
return a.loadPolicyFile(model, persist.LoadPolicyLine)
|
||||
}
|
||||
|
||||
// SavePolicy saves all policy rules to the storage.
|
||||
func (a *Adapter) SavePolicy(model model.Model) error {
|
||||
if a.filePath == "" {
|
||||
return errors.New("invalid file path, file path cannot be empty")
|
||||
}
|
||||
|
||||
var tmp bytes.Buffer
|
||||
|
||||
for ptype, ast := range model["p"] {
|
||||
for _, rule := range ast.Policy {
|
||||
line, err := persist.PolicyLineToCsv(ptype, rule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp.WriteString(line)
|
||||
tmp.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
for ptype, ast := range model["g"] {
|
||||
for _, rule := range ast.Policy {
|
||||
line, err := persist.PolicyLineToCsv(ptype, rule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp.WriteString(line)
|
||||
tmp.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
return a.savePolicyFile(strings.TrimRight(tmp.String(), "\n"))
|
||||
}
|
||||
|
||||
func (a *Adapter) loadPolicyFile(model model.Model, handler func(string, model.Model) error) error {
|
||||
f, err := os.Open(a.filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
err = handler(line, model)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return scanner.Err()
|
||||
}
|
||||
|
||||
func (a *Adapter) savePolicyFile(text string) error {
|
||||
f, err := os.Create(a.filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := bufio.NewWriter(f)
|
||||
|
||||
_, err = w.WriteString(text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = w.Flush()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return f.Close()
|
||||
}
|
||||
|
||||
// AddPolicy adds a policy rule to the storage.
|
||||
func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
// AddPolicies adds policy rules to the storage.
|
||||
func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
// RemovePolicy removes a policy rule from the storage.
|
||||
func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
// RemovePolicies removes policy rules from the storage.
|
||||
func (a *Adapter) RemovePolicies(sec string, ptype string, rules [][]string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
|
||||
func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
120
persist/file-adapter/adapter_context.go
Normal file
120
persist/file-adapter/adapter_context.go
Normal file
@@ -0,0 +1,120 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package fileadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
)
|
||||
|
||||
func (a *Adapter) UpdatePolicyCtx(ctx context.Context, sec string, ptype string, oldRule, newRule []string) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.UpdatePolicy(sec, ptype, oldRule, newRule)
|
||||
}
|
||||
|
||||
func (a *Adapter) UpdatePoliciesCtx(ctx context.Context, sec string, ptype string, oldRules, newRules [][]string) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.UpdatePolicies(sec, ptype, oldRules, newRules)
|
||||
}
|
||||
|
||||
func (a *Adapter) UpdateFilteredPoliciesCtx(ctx context.Context, sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) ([][]string, error) {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return a.UpdateFilteredPolicies(sec, ptype, newRules, fieldIndex, fieldValues...)
|
||||
}
|
||||
|
||||
// LoadPolicyCtx loads all policy rules from the storage with context.
|
||||
func (a *Adapter) LoadPolicyCtx(ctx context.Context, model model.Model) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.LoadPolicy(model)
|
||||
}
|
||||
|
||||
// SavePolicyCtx saves all policy rules to the storage with context.
|
||||
func (a *Adapter) SavePolicyCtx(ctx context.Context, model model.Model) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.SavePolicy(model)
|
||||
}
|
||||
|
||||
// AddPolicyCtx adds a policy rule to the storage with context.
|
||||
func (a *Adapter) AddPolicyCtx(ctx context.Context, sec string, ptype string, rule []string) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.AddPolicy(sec, ptype, rule)
|
||||
}
|
||||
|
||||
// AddPoliciesCtx adds policy rules to the storage with context.
|
||||
func (a *Adapter) AddPoliciesCtx(ctx context.Context, sec string, ptype string, rules [][]string) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.AddPolicies(sec, ptype, rules)
|
||||
}
|
||||
|
||||
// RemovePolicyCtx removes a policy rule from the storage with context.
|
||||
func (a *Adapter) RemovePolicyCtx(ctx context.Context, sec string, ptype string, rule []string) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.RemovePolicy(sec, ptype, rule)
|
||||
}
|
||||
|
||||
// RemovePoliciesCtx removes policy rules from the storage with context.
|
||||
func (a *Adapter) RemovePoliciesCtx(ctx context.Context, sec string, ptype string, rules [][]string) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.RemovePolicies(sec, ptype, rules)
|
||||
}
|
||||
|
||||
// RemoveFilteredPolicyCtx removes policy rules that match the filter from the storage with context.
|
||||
func (a *Adapter) RemoveFilteredPolicyCtx(ctx context.Context, sec string, ptype string, fieldIndex int, fieldValues ...string) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues...)
|
||||
}
|
||||
|
||||
func checkCtx(ctx context.Context) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
159
persist/file-adapter/adapter_filtered.go
Normal file
159
persist/file-adapter/adapter_filtered.go
Normal file
@@ -0,0 +1,159 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package fileadapter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
"github.com/casbin/casbin/v3/persist"
|
||||
)
|
||||
|
||||
// FilteredAdapter is the filtered file adapter for Casbin. It can load policy
|
||||
// from file or save policy to file and supports loading of filtered policies.
|
||||
type FilteredAdapter struct {
|
||||
*Adapter
|
||||
filtered bool
|
||||
}
|
||||
|
||||
// Filter defines the filtering rules for a FilteredAdapter's policy. Empty values
|
||||
// are ignored, but all others must match the filter.
|
||||
type Filter struct {
|
||||
P []string
|
||||
G []string
|
||||
G1 []string
|
||||
G2 []string
|
||||
G3 []string
|
||||
G4 []string
|
||||
G5 []string
|
||||
}
|
||||
|
||||
// NewFilteredAdapter is the constructor for FilteredAdapter.
|
||||
func NewFilteredAdapter(filePath string) *FilteredAdapter {
|
||||
a := FilteredAdapter{}
|
||||
a.filtered = true
|
||||
a.Adapter = NewAdapter(filePath)
|
||||
return &a
|
||||
}
|
||||
|
||||
// LoadPolicy loads all policy rules from the storage.
|
||||
func (a *FilteredAdapter) LoadPolicy(model model.Model) error {
|
||||
a.filtered = false
|
||||
return a.Adapter.LoadPolicy(model)
|
||||
}
|
||||
|
||||
// LoadFilteredPolicy loads only policy rules that match the filter.
|
||||
func (a *FilteredAdapter) LoadFilteredPolicy(model model.Model, filter interface{}) error {
|
||||
if filter == nil {
|
||||
return a.LoadPolicy(model)
|
||||
}
|
||||
if a.filePath == "" {
|
||||
return errors.New("invalid file path, file path cannot be empty")
|
||||
}
|
||||
|
||||
filterValue, ok := filter.(*Filter)
|
||||
if !ok {
|
||||
return errors.New("invalid filter type")
|
||||
}
|
||||
err := a.loadFilteredPolicyFile(model, filterValue, persist.LoadPolicyLine)
|
||||
if err == nil {
|
||||
a.filtered = true
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *FilteredAdapter) loadFilteredPolicyFile(model model.Model, filter *Filter, handler func(string, model.Model) error) error {
|
||||
f, err := os.Open(a.filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
|
||||
if filterLine(line, filter) {
|
||||
continue
|
||||
}
|
||||
|
||||
err = handler(line, model)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return scanner.Err()
|
||||
}
|
||||
|
||||
// IsFiltered returns true if the loaded policy has been filtered.
|
||||
func (a *FilteredAdapter) IsFiltered() bool {
|
||||
return a.filtered
|
||||
}
|
||||
|
||||
// SavePolicy saves all policy rules to the storage.
|
||||
func (a *FilteredAdapter) SavePolicy(model model.Model) error {
|
||||
if a.filtered {
|
||||
return errors.New("cannot save a filtered policy")
|
||||
}
|
||||
return a.Adapter.SavePolicy(model)
|
||||
}
|
||||
|
||||
func filterLine(line string, filter *Filter) bool {
|
||||
if filter == nil {
|
||||
return false
|
||||
}
|
||||
p := strings.Split(line, ",")
|
||||
if len(p) == 0 {
|
||||
return true
|
||||
}
|
||||
var filterSlice []string
|
||||
switch strings.TrimSpace(p[0]) {
|
||||
case "p":
|
||||
filterSlice = filter.P
|
||||
case "g":
|
||||
filterSlice = filter.G
|
||||
case "g1":
|
||||
filterSlice = filter.G1
|
||||
case "g2":
|
||||
filterSlice = filter.G2
|
||||
case "g3":
|
||||
filterSlice = filter.G3
|
||||
case "g4":
|
||||
filterSlice = filter.G4
|
||||
case "g5":
|
||||
filterSlice = filter.G5
|
||||
}
|
||||
return filterWords(p, filterSlice)
|
||||
}
|
||||
|
||||
func filterWords(line []string, filter []string) bool {
|
||||
if len(line) < len(filter)+1 {
|
||||
return true
|
||||
}
|
||||
var skipLine bool
|
||||
for i, v := range filter {
|
||||
if len(v) > 0 && strings.TrimSpace(v) != strings.TrimSpace(line[i+1]) {
|
||||
skipLine = true
|
||||
break
|
||||
}
|
||||
}
|
||||
return skipLine
|
||||
}
|
||||
60
persist/file-adapter/adapter_filtered_context.go
Normal file
60
persist/file-adapter/adapter_filtered_context.go
Normal file
@@ -0,0 +1,60 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package fileadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
)
|
||||
|
||||
// LoadPolicyCtx loads all policy rules from the storage with context.
|
||||
func (a *FilteredAdapter) LoadPolicyCtx(ctx context.Context, model model.Model) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.LoadPolicy(model)
|
||||
}
|
||||
|
||||
// LoadFilteredPolicyCtx loads only policy rules that match the filter with context.
|
||||
func (a *FilteredAdapter) LoadFilteredPolicyCtx(ctx context.Context, model model.Model, filter interface{}) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.LoadFilteredPolicy(model, filter)
|
||||
}
|
||||
|
||||
// SavePolicyCtx saves all policy rules to the storage with context.
|
||||
func (a *FilteredAdapter) SavePolicyCtx(ctx context.Context, model model.Model) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.SavePolicy(model)
|
||||
}
|
||||
|
||||
// IsFilteredCtx returns true if the loaded policy has been filtered with context.
|
||||
func (a *FilteredAdapter) IsFilteredCtx(ctx context.Context) bool {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return a.IsFiltered()
|
||||
}
|
||||
125
persist/file-adapter/adapter_mock.go
Normal file
125
persist/file-adapter/adapter_mock.go
Normal file
@@ -0,0 +1,125 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package fileadapter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
"github.com/casbin/casbin/v3/persist"
|
||||
)
|
||||
|
||||
// AdapterMock is the file adapter for Casbin.
|
||||
// It can load policy from file or save policy to file.
|
||||
type AdapterMock struct {
|
||||
filePath string
|
||||
errorValue string
|
||||
}
|
||||
|
||||
// NewAdapterMock is the constructor for AdapterMock.
|
||||
func NewAdapterMock(filePath string) *AdapterMock {
|
||||
a := AdapterMock{}
|
||||
a.filePath = filePath
|
||||
return &a
|
||||
}
|
||||
|
||||
// LoadPolicy loads all policy rules from the storage.
|
||||
func (a *AdapterMock) LoadPolicy(model model.Model) error {
|
||||
err := a.loadPolicyFile(model, persist.LoadPolicyLine)
|
||||
return err
|
||||
}
|
||||
|
||||
// SavePolicy saves all policy rules to the storage.
|
||||
func (a *AdapterMock) SavePolicy(model model.Model) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *AdapterMock) loadPolicyFile(model model.Model, handler func(string, model.Model) error) error {
|
||||
f, err := os.Open(a.filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
buf := bufio.NewReader(f)
|
||||
for {
|
||||
line, err := buf.ReadString('\n')
|
||||
line = strings.TrimSpace(line)
|
||||
if err2 := handler(line, model); err2 != nil {
|
||||
return err2
|
||||
}
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SetMockErr sets string to be returned by of the mock during testing.
|
||||
func (a *AdapterMock) SetMockErr(errorToSet string) {
|
||||
a.errorValue = errorToSet
|
||||
}
|
||||
|
||||
// GetMockErr returns a mock error or nil.
|
||||
func (a *AdapterMock) GetMockErr() error {
|
||||
var returnError error
|
||||
if a.errorValue != "" {
|
||||
returnError = errors.New(a.errorValue)
|
||||
}
|
||||
return returnError
|
||||
}
|
||||
|
||||
// AddPolicy adds a policy rule to the storage.
|
||||
func (a *AdapterMock) AddPolicy(sec string, ptype string, rule []string) error {
|
||||
return a.GetMockErr()
|
||||
}
|
||||
|
||||
// AddPolicies removes policy rules from the storage.
|
||||
func (a *AdapterMock) AddPolicies(sec string, ptype string, rules [][]string) error {
|
||||
return a.GetMockErr()
|
||||
}
|
||||
|
||||
// RemovePolicy removes a policy rule from the storage.
|
||||
func (a *AdapterMock) RemovePolicy(sec string, ptype string, rule []string) error {
|
||||
return a.GetMockErr()
|
||||
}
|
||||
|
||||
// RemovePolicies removes policy rules from the storage.
|
||||
func (a *AdapterMock) RemovePolicies(sec string, ptype string, rules [][]string) error {
|
||||
return a.GetMockErr()
|
||||
}
|
||||
|
||||
// UpdatePolicy removes a policy rule from the storage.
|
||||
func (a *AdapterMock) UpdatePolicy(sec string, ptype string, oldRule, newPolicy []string) error {
|
||||
return a.GetMockErr()
|
||||
}
|
||||
|
||||
func (a *AdapterMock) UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error {
|
||||
return a.GetMockErr()
|
||||
}
|
||||
|
||||
// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
|
||||
func (a *AdapterMock) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error {
|
||||
return a.GetMockErr()
|
||||
}
|
||||
154
persist/persist_test.go
Normal file
154
persist/persist_test.go
Normal file
@@ -0,0 +1,154 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/casbin/casbin/v3"
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
"github.com/casbin/casbin/v3/persist"
|
||||
)
|
||||
|
||||
func TestPersist(t *testing.T) {
|
||||
// No tests yet
|
||||
}
|
||||
|
||||
func testRuleCount(t *testing.T, model model.Model, expected int, sec string, ptype string, tag string) {
|
||||
t.Helper()
|
||||
|
||||
ruleCount := len(model[sec][ptype].Policy)
|
||||
if ruleCount != expected {
|
||||
t.Errorf("[%s] rule count: %d, expected %d", tag, ruleCount, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateRuleInAdapter(t *testing.T) {
|
||||
e, _ := casbin.NewEnforcer("../examples/basic_model.conf")
|
||||
|
||||
_, _ = e.AddPolicy("alice", "data1", "read")
|
||||
_, _ = e.AddPolicy("alice", "data1", "read")
|
||||
|
||||
testRuleCount(t, e.GetModel(), 1, "p", "p", "AddPolicy")
|
||||
|
||||
e.ClearPolicy()
|
||||
|
||||
// simulate adapter.LoadPolicy with duplicate rules
|
||||
_ = persist.LoadPolicyArray([]string{"p", "alice", "data1", "read"}, e.GetModel())
|
||||
_ = persist.LoadPolicyArray([]string{"p", "alice", "data1", "read"}, e.GetModel())
|
||||
|
||||
testRuleCount(t, e.GetModel(), 1, "p", "p", "LoadPolicyArray")
|
||||
}
|
||||
|
||||
func TestPolicyLineToCsv(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ptype string
|
||||
rule []string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
// Fields are separated by ", ", the layout used by the policy files
|
||||
// under examples/, so that SavePolicy does not reformat them.
|
||||
name: "plain fields keep the space after the comma",
|
||||
ptype: "p",
|
||||
rule: []string{"alice", "data1", "read"},
|
||||
expected: "p, alice, data1, read",
|
||||
},
|
||||
{
|
||||
name: "field containing a comma is quoted",
|
||||
ptype: "p",
|
||||
rule: []string{"alice", "data1", "read", "r.attrs in ('val1','val2')"},
|
||||
expected: `p, alice, data1, read, "r.attrs in ('val1','val2')"`,
|
||||
},
|
||||
{
|
||||
name: "field containing a quote is escaped",
|
||||
ptype: "p",
|
||||
rule: []string{"alice", `say "hi"`, "read"},
|
||||
expected: `p, alice, "say ""hi""", read`,
|
||||
},
|
||||
{
|
||||
// A leading space must stay quoted: LoadPolicyLine trims leading
|
||||
// spaces on unquoted fields.
|
||||
name: "field with a leading space is quoted",
|
||||
ptype: "g",
|
||||
rule: []string{" alice", "admin"},
|
||||
expected: `g, " alice", admin`,
|
||||
},
|
||||
{
|
||||
name: "empty field",
|
||||
ptype: "p",
|
||||
rule: []string{"alice", "", "read"},
|
||||
expected: "p, alice, , read",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
line, err := persist.PolicyLineToCsv(tt.ptype, tt.rule)
|
||||
if err != nil {
|
||||
t.Fatalf("PolicyLineToCsv: %v", err)
|
||||
}
|
||||
if line != tt.expected {
|
||||
t.Errorf("line: %q, expected %q", line, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyLineToCsvRoundTrip(t *testing.T) {
|
||||
conf := `
|
||||
[request_definition]
|
||||
r = sub, obj, act, cond
|
||||
|
||||
[policy_definition]
|
||||
p = sub, obj, act, cond
|
||||
|
||||
[policy_effect]
|
||||
e = some(where (p.eft == allow))
|
||||
|
||||
[matchers]
|
||||
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
|
||||
`
|
||||
rule := []string{" alice", `say "hi"`, "read", "r.attrs in ('val1','val2')"}
|
||||
|
||||
line, err := persist.PolicyLineToCsv("p", rule)
|
||||
if err != nil {
|
||||
t.Fatalf("PolicyLineToCsv: %v", err)
|
||||
}
|
||||
|
||||
m := model.NewModel()
|
||||
if err = m.LoadModelFromText(conf); err != nil {
|
||||
t.Fatalf("load model: %v", err)
|
||||
}
|
||||
if err = persist.LoadPolicyLine(line, m); err != nil {
|
||||
t.Fatalf("LoadPolicyLine on %q: %v", line, err)
|
||||
}
|
||||
|
||||
rules, err := m.GetPolicy("p", "p")
|
||||
if err != nil {
|
||||
t.Fatalf("GetPolicy: %v", err)
|
||||
}
|
||||
if len(rules) != 1 {
|
||||
t.Fatalf("rule count: %d, expected 1 (line: %q)", len(rules), line)
|
||||
}
|
||||
if !reflect.DeepEqual(rules[0], rule) {
|
||||
t.Errorf("rule after round-trip: %q, expected %q (line: %q)", rules[0], rule, line)
|
||||
}
|
||||
}
|
||||
103
persist/string-adapter/adapter.go
Normal file
103
persist/string-adapter/adapter.go
Normal file
@@ -0,0 +1,103 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package stringadapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
"github.com/casbin/casbin/v3/persist"
|
||||
)
|
||||
|
||||
// Adapter is the string adapter for Casbin.
|
||||
// It can load policy from string or save policy to string.
|
||||
type Adapter struct {
|
||||
Line string
|
||||
}
|
||||
|
||||
// NewAdapter is the constructor for Adapter.
|
||||
func NewAdapter(line string) *Adapter {
|
||||
return &Adapter{
|
||||
Line: line,
|
||||
}
|
||||
}
|
||||
|
||||
// LoadPolicy loads all policy rules from the storage.
|
||||
func (a *Adapter) LoadPolicy(model model.Model) error {
|
||||
if a.Line == "" {
|
||||
return errors.New("invalid line, line cannot be empty")
|
||||
}
|
||||
strs := strings.Split(a.Line, "\n")
|
||||
for _, str := range strs {
|
||||
str = strings.TrimSpace(str)
|
||||
if str == "" {
|
||||
continue
|
||||
}
|
||||
if err := persist.LoadPolicyLine(str, model); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SavePolicy saves all policy rules to the storage.
|
||||
func (a *Adapter) SavePolicy(model model.Model) error {
|
||||
var tmp bytes.Buffer
|
||||
for ptype, ast := range model["p"] {
|
||||
for _, rule := range ast.Policy {
|
||||
line, err := persist.PolicyLineToCsv(ptype, rule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp.WriteString(line)
|
||||
tmp.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
for ptype, ast := range model["g"] {
|
||||
for _, rule := range ast.Policy {
|
||||
line, err := persist.PolicyLineToCsv(ptype, rule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp.WriteString(line)
|
||||
tmp.WriteString("\n")
|
||||
}
|
||||
}
|
||||
a.Line = strings.TrimRight(tmp.String(), "\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddPolicy adds a policy rule to the storage.
|
||||
func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
// RemovePolicy removes a policy rule from the storage.
|
||||
func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error {
|
||||
a.Line = ""
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
|
||||
func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
78
persist/string-adapter/adapter_context.go
Normal file
78
persist/string-adapter/adapter_context.go
Normal file
@@ -0,0 +1,78 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package stringadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
)
|
||||
|
||||
// LoadPolicyCtx loads all policy rules from the storage with context.
|
||||
func (a *Adapter) LoadPolicyCtx(ctx context.Context, model model.Model) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.LoadPolicy(model)
|
||||
}
|
||||
|
||||
// SavePolicyCtx saves all policy rules to the storage with context.
|
||||
func (a *Adapter) SavePolicyCtx(ctx context.Context, model model.Model) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.SavePolicy(model)
|
||||
}
|
||||
|
||||
// AddPolicyCtx adds a policy rule to the storage with context.
|
||||
func (a *Adapter) AddPolicyCtx(ctx context.Context, sec string, ptype string, rule []string) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.AddPolicy(sec, ptype, rule)
|
||||
}
|
||||
|
||||
// RemovePolicyCtx removes a policy rule from the storage with context.
|
||||
func (a *Adapter) RemovePolicyCtx(ctx context.Context, sec string, ptype string, rule []string) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.RemovePolicy(sec, ptype, rule)
|
||||
}
|
||||
|
||||
// RemoveFilteredPolicyCtx removes policy rules that match the filter from the storage with context.
|
||||
func (a *Adapter) RemoveFilteredPolicyCtx(ctx context.Context, sec string, ptype string, fieldIndex int, fieldValues ...string) error {
|
||||
if err := checkCtx(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.RemoveFilteredPolicy(sec, ptype, fieldIndex, fieldValues...)
|
||||
}
|
||||
|
||||
func checkCtx(ctx context.Context) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
173
persist/string-adapter/adapter_test.go
Normal file
173
persist/string-adapter/adapter_test.go
Normal file
@@ -0,0 +1,173 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package stringadapter
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/casbin/casbin/v3"
|
||||
"github.com/casbin/casbin/v3/model"
|
||||
"github.com/casbin/casbin/v3/persist"
|
||||
)
|
||||
|
||||
func Test_KeyMatchRbac(t *testing.T) {
|
||||
conf := `
|
||||
[request_definition]
|
||||
r = sub, obj, act
|
||||
|
||||
[policy_definition]
|
||||
p = sub, obj, act
|
||||
|
||||
[role_definition]
|
||||
g = _ , _
|
||||
|
||||
[policy_effect]
|
||||
e = some(where (p.eft == allow))
|
||||
|
||||
[matchers]
|
||||
m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act)
|
||||
`
|
||||
line := `
|
||||
p, alice, /alice_data/*, (GET)|(POST)
|
||||
p, alice, /alice_data/resource1, POST
|
||||
p, data_group_admin, /admin/*, POST
|
||||
p, data_group_admin, /bob_data/*, POST
|
||||
g, alice, data_group_admin
|
||||
`
|
||||
a := NewAdapter(line)
|
||||
m := model.NewModel()
|
||||
err := m.LoadModelFromText(conf)
|
||||
if err != nil {
|
||||
t.Errorf("load model from text failed: %v", err.Error())
|
||||
return
|
||||
}
|
||||
e, _ := casbin.NewEnforcer(m, a)
|
||||
sub := "alice"
|
||||
obj := "/alice_data/login"
|
||||
act := "POST"
|
||||
if res, _ := e.Enforce(sub, obj, act); !res {
|
||||
t.Error("unexpected enforce result")
|
||||
}
|
||||
}
|
||||
|
||||
// Test_SavePolicyRoundTripWithCommas verifies that a policy rule whose fields contain
|
||||
// commas (e.g. ABAC condition expressions) survives a SavePolicy → LoadPolicy round trip
|
||||
// without corruption. See https://github.com/apache/casbin/issues/1733.
|
||||
func Test_SavePolicyRoundTripWithCommas(t *testing.T) {
|
||||
conf := `
|
||||
[request_definition]
|
||||
r = sub, obj, act, cond
|
||||
|
||||
[policy_definition]
|
||||
p = sub, obj, act, cond
|
||||
|
||||
[policy_effect]
|
||||
e = some(where (p.eft == allow))
|
||||
|
||||
[matchers]
|
||||
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
|
||||
`
|
||||
// cond field intentionally contains commas (as in ABAC expressions).
|
||||
condWithComma := `r.attrs in ('val1','val2')`
|
||||
line := "p, alice, data1, read, " + `"` + condWithComma + `"`
|
||||
|
||||
a := NewAdapter(line)
|
||||
m := model.NewModel()
|
||||
if err := m.LoadModelFromText(conf); err != nil {
|
||||
t.Fatalf("load model: %v", err)
|
||||
}
|
||||
e, err := casbin.NewEnforcer(m, a)
|
||||
if err != nil {
|
||||
t.Fatalf("new enforcer: %v", err)
|
||||
}
|
||||
|
||||
// SavePolicy serialises in-memory rules back to the adapter string.
|
||||
err = e.SavePolicy()
|
||||
if err != nil {
|
||||
t.Fatalf("SavePolicy: %v", err)
|
||||
}
|
||||
|
||||
// The saved line must be a properly quoted CSV so that re-loading produces
|
||||
// exactly one rule with the comma-containing cond field intact.
|
||||
saved := a.Line
|
||||
reloaded := model.NewModel()
|
||||
err = reloaded.LoadModelFromText(conf)
|
||||
if err != nil {
|
||||
t.Fatalf("reload model: %v", err)
|
||||
}
|
||||
for _, l := range strings.Split(saved, "\n") {
|
||||
if l == "" {
|
||||
continue
|
||||
}
|
||||
err = persist.LoadPolicyLine(l, reloaded)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadPolicyLine on saved line %q: %v", l, err)
|
||||
}
|
||||
}
|
||||
|
||||
rules, err := reloaded.GetPolicy("p", "p")
|
||||
if err != nil {
|
||||
t.Fatalf("GetPolicy: %v", err)
|
||||
}
|
||||
if len(rules) != 1 {
|
||||
t.Fatalf("expected 1 rule after round-trip, got %d (saved: %q)", len(rules), saved)
|
||||
}
|
||||
if rules[0][3] != condWithComma {
|
||||
t.Errorf("cond field corrupted after round-trip: got %q, want %q", rules[0][3], condWithComma)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_StringRbac(t *testing.T) {
|
||||
conf := `
|
||||
[request_definition]
|
||||
r = sub, obj, act
|
||||
|
||||
[policy_definition]
|
||||
p = sub, obj, act
|
||||
|
||||
[role_definition]
|
||||
g = _ , _
|
||||
|
||||
[policy_effect]
|
||||
e = some(where (p.eft == allow))
|
||||
|
||||
[matchers]
|
||||
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
|
||||
`
|
||||
line := `
|
||||
p, alice, data1, read
|
||||
p, data_group_admin, data3, read
|
||||
p, data_group_admin, data3, write
|
||||
g, alice, data_group_admin
|
||||
`
|
||||
a := NewAdapter(line)
|
||||
m := model.NewModel()
|
||||
err := m.LoadModelFromText(conf)
|
||||
if err != nil {
|
||||
t.Errorf("load model from text failed: %v", err.Error())
|
||||
return
|
||||
}
|
||||
e, _ := casbin.NewEnforcer(m, a)
|
||||
sub := "alice" // the user that wants to access a resource.
|
||||
obj := "data1" // the resource that is going to be accessed.
|
||||
act := "read" // the operation that the user performs on the resource.
|
||||
if res, _ := e.Enforce(sub, obj, act); !res {
|
||||
t.Error("unexpected enforce result")
|
||||
}
|
||||
}
|
||||
61
persist/transaction.go
Normal file
61
persist/transaction.go
Normal file
@@ -0,0 +1,61 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
import "context"
|
||||
|
||||
// TransactionalAdapter defines the interface for adapters that support transactions.
|
||||
// Adapters implementing this interface can participate in Casbin transactions.
|
||||
type TransactionalAdapter interface {
|
||||
Adapter
|
||||
// BeginTransaction starts a new transaction and returns a transaction context.
|
||||
BeginTransaction(ctx context.Context) (TransactionContext, error)
|
||||
}
|
||||
|
||||
// TransactionContext represents a database transaction context.
|
||||
// It provides methods to commit or rollback the transaction and get an adapter
|
||||
// that operates within this transaction.
|
||||
type TransactionContext interface {
|
||||
// Commit commits the transaction.
|
||||
Commit() error
|
||||
// Rollback rolls back the transaction.
|
||||
Rollback() error
|
||||
// GetAdapter returns an adapter that operates within this transaction.
|
||||
GetAdapter() Adapter
|
||||
}
|
||||
|
||||
// PolicyOperation represents a policy operation that can be buffered in a transaction.
|
||||
type PolicyOperation struct {
|
||||
Type OperationType // The type of operation (add, remove, update)
|
||||
Section string // The section of the policy (p, g)
|
||||
PolicyType string // The policy type (p, p2, g, g2, etc.)
|
||||
Rules [][]string // The policy rules to operate on
|
||||
OldRules [][]string // For update operations, the old rules to replace
|
||||
}
|
||||
|
||||
// OperationType represents the type of policy operation.
|
||||
type OperationType int
|
||||
|
||||
const (
|
||||
// OperationAdd represents adding policy rules.
|
||||
OperationAdd OperationType = iota
|
||||
// OperationRemove represents removing policy rules.
|
||||
OperationRemove
|
||||
// OperationUpdate represents updating policy rules.
|
||||
OperationUpdate
|
||||
)
|
||||
30
persist/update_adapter.go
Normal file
30
persist/update_adapter.go
Normal file
@@ -0,0 +1,30 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
// UpdatableAdapter is the interface for Casbin adapters with add update policy function.
|
||||
type UpdatableAdapter interface {
|
||||
Adapter
|
||||
// UpdatePolicy updates a policy rule from storage.
|
||||
// This is part of the Auto-Save feature.
|
||||
UpdatePolicy(sec string, ptype string, oldRule, newRule []string) error
|
||||
// UpdatePolicies updates some policy rules to storage, like db, redis.
|
||||
UpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error
|
||||
// UpdateFilteredPolicies deletes old rules and adds new rules.
|
||||
UpdateFilteredPolicies(sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) ([][]string, error)
|
||||
}
|
||||
33
persist/update_adapter_context.go
Normal file
33
persist/update_adapter_context.go
Normal file
@@ -0,0 +1,33 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
import "context"
|
||||
|
||||
// ContextUpdatableAdapter is the context-aware interface for Casbin adapters with add update policy function.
|
||||
type ContextUpdatableAdapter interface {
|
||||
ContextAdapter
|
||||
|
||||
// UpdatePolicyCtx updates a policy rule from storage.
|
||||
// This is part of the Auto-Save feature.
|
||||
UpdatePolicyCtx(ctx context.Context, sec string, ptype string, oldRule, newRule []string) error
|
||||
// UpdatePoliciesCtx updates some policy rules to storage, like db, redis.
|
||||
UpdatePoliciesCtx(ctx context.Context, sec string, ptype string, oldRules, newRules [][]string) error
|
||||
// UpdateFilteredPoliciesCtx deletes old rules and adds new rules.
|
||||
UpdateFilteredPoliciesCtx(ctx context.Context, sec string, ptype string, newRules [][]string, fieldIndex int, fieldValues ...string) ([][]string, error)
|
||||
}
|
||||
32
persist/watcher.go
Normal file
32
persist/watcher.go
Normal file
@@ -0,0 +1,32 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
// Watcher is the interface for Casbin watchers.
|
||||
type Watcher interface {
|
||||
// SetUpdateCallback sets the callback function that the watcher will call
|
||||
// when the policy in DB has been changed by other instances.
|
||||
// A classic callback is Enforcer.LoadPolicy().
|
||||
SetUpdateCallback(func(string)) error
|
||||
// Update calls the update callback of other instances to synchronize their policy.
|
||||
// It is usually called after changing the policy in DB, like Enforcer.SavePolicy(),
|
||||
// Enforcer.AddPolicy(), Enforcer.RemovePolicy(), etc.
|
||||
Update() error
|
||||
// Close stops and releases the watcher, the callback function will not be called any more.
|
||||
Close()
|
||||
}
|
||||
43
persist/watcher_ex.go
Normal file
43
persist/watcher_ex.go
Normal file
@@ -0,0 +1,43 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
import "github.com/casbin/casbin/v3/model"
|
||||
|
||||
// WatcherEx is the strengthened Casbin watchers.
|
||||
type WatcherEx interface {
|
||||
Watcher
|
||||
// UpdateForAddPolicy calls the update callback of other instances to synchronize their policy.
|
||||
// It is called after Enforcer.AddPolicy()
|
||||
UpdateForAddPolicy(sec, ptype string, params ...string) error
|
||||
// UpdateForRemovePolicy calls the update callback of other instances to synchronize their policy.
|
||||
// It is called after Enforcer.RemovePolicy()
|
||||
UpdateForRemovePolicy(sec, ptype string, params ...string) error
|
||||
// UpdateForRemoveFilteredPolicy calls the update callback of other instances to synchronize their policy.
|
||||
// It is called after Enforcer.RemoveFilteredNamedGroupingPolicy()
|
||||
UpdateForRemoveFilteredPolicy(sec, ptype string, fieldIndex int, fieldValues ...string) error
|
||||
// UpdateForSavePolicy calls the update callback of other instances to synchronize their policy.
|
||||
// It is called after Enforcer.RemoveFilteredNamedGroupingPolicy()
|
||||
UpdateForSavePolicy(model model.Model) error
|
||||
// UpdateForAddPolicies calls the update callback of other instances to synchronize their policy.
|
||||
// It is called after Enforcer.AddPolicies()
|
||||
UpdateForAddPolicies(sec string, ptype string, rules ...[]string) error
|
||||
// UpdateForRemovePolicies calls the update callback of other instances to synchronize their policy.
|
||||
// It is called after Enforcer.RemovePolicies()
|
||||
UpdateForRemovePolicies(sec string, ptype string, rules ...[]string) error
|
||||
}
|
||||
29
persist/watcher_update.go
Normal file
29
persist/watcher_update.go
Normal file
@@ -0,0 +1,29 @@
|
||||
// Licensed to the Apache Software Foundation (ASF) under one
|
||||
// or more contributor license agreements. See the NOTICE file
|
||||
// distributed with this work for additional information
|
||||
// regarding copyright ownership. The ASF licenses this file
|
||||
// to you under the Apache License, Version 2.0 (the
|
||||
// "License"); you may not use this file except in compliance
|
||||
// with the License. You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing,
|
||||
// software distributed under the License is distributed on an
|
||||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
// KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package persist
|
||||
|
||||
// UpdatableWatcher is strengthened for Casbin watchers.
|
||||
type UpdatableWatcher interface {
|
||||
Watcher
|
||||
// UpdateForUpdatePolicy calls the update callback of other instances to synchronize their policy.
|
||||
// It is called after Enforcer.UpdatePolicy()
|
||||
UpdateForUpdatePolicy(sec string, ptype string, oldRule, newRule []string) error
|
||||
// UpdateForUpdatePolicies calls the update callback of other instances to synchronize their policy.
|
||||
// It is called after Enforcer.UpdatePolicies()
|
||||
UpdateForUpdatePolicies(sec string, ptype string, oldRules, newRules [][]string) error
|
||||
}
|
||||
Reference in New Issue
Block a user