Skip to content

Commit

Permalink
Merge pull request #25 from closetool/master
Browse files Browse the repository at this point in the history
feat: add updateFilteredPolicies
  • Loading branch information
hsluoyz authored Apr 17, 2021
2 parents 91d507a + d872751 commit 83dd5d7
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
26 changes: 26 additions & 0 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,32 @@ func (a *Adapter) UpdatePolicies(sec string, ptype string, oldRules, newRules []
return a.updatePolicies(oldLines, newLines)
}

func (a *Adapter) UpdateFilteredPolicies(sec string, ptype string, oldRules, newRules [][]string) error {
var oldLines []*CasbinRule
for _, rule := range oldRules {
line := savePolicyLine(ptype, rule)
oldLines = append(oldLines, line)
}

var newLines []*CasbinRule
for _, rule := range newRules {
line := savePolicyLine(ptype, rule)
newLines = append(newLines, line)
}

err := a.db.RunInTransaction(func(tx *pg.Tx) error {
_, err := tx.Model(&oldLines).Delete()
if err != nil {
return err
}
_, err = tx.Model(&newLines).
OnConflict("DO NOTHING").
Insert()
return err
})
return err
}

func (a *Adapter) updatePolicies(oldLines, newLines []*CasbinRule) error {
tx, err := a.db.Begin()
if err != nil {
Expand Down
19 changes: 19 additions & 0 deletions adapter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,25 @@ func (s *AdapterTestSuite) TestUpdatePolicyWithLoadFilteredPolicy() {
s.assertPolicy(s.e.GetPolicy(), [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"bob", "data2", "read"}, {"alice", "data2", "write"}})
}

func (s *AdapterTestSuite) TestUpdateFilteredPolicies() {

var err error
s.e, err = casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv")
s.Require().NoError(err)

s.e.SetAdapter(s.a)

err = s.e.SavePolicy()
s.Require().NoError(err)

err = s.a.UpdateFilteredPolicies("p", "p", [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}}, [][]string{{"alice", "data2", "write"}, {"bob", "data1", "read"}})
s.Require().NoError(err)

err = s.e.LoadPolicy()
s.Require().NoError(err)

s.assertPolicy(s.e.GetPolicy(), [][]string{{"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}, {"alice", "data2", "write"}, {"bob", "data1", "read"}})
}
func TestAdapterTestSuite(t *testing.T) {
suite.Run(t, new(AdapterTestSuite))
}

0 comments on commit 83dd5d7

Please sign in to comment.