Skip to content

Commit 87b7d8c

Browse files
committed
feat: add UpdatePolicy(#36)
Signed-off-by: closetool <[email protected]>
1 parent 5c98582 commit 87b7d8c

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

adapter.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,3 +455,10 @@ func (a *Adapter) filterQuery(session *xorm.Session, filter Filter) *xorm.Sessio
455455

456456
return session
457457
}
458+
459+
// UpdatePolicy update oldRule to newPolicy permanently
460+
func (a *Adapter) UpdatePolicy(sec string, ptype string, oldRule, newPolicy []string) error {
461+
oRule := a.genPolicyLine(ptype, oldRule)
462+
_, err := a.engine.Update(a.genPolicyLine(ptype, newPolicy), oRule)
463+
return err
464+
}

adapter_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,34 @@ func testAddPolicies(t *testing.T, driverName string, dataSourceName string, dbS
267267
testGetPolicy(t, e, [][]string{{"max", "data2", "read"}, {"max", "data1", "write"}})
268268
}
269269

270+
func testUpdatePolicies(t *testing.T, driverName string, dataSourceName string, dbSpecified ...bool) {
271+
// Initialize some policy in DB.
272+
initPolicy(t, driverName, dataSourceName, dbSpecified...)
273+
// Note: you don't need to look at the above code
274+
// if you already have a working DB with policy inside.
275+
276+
// Now the DB has policy, so we can provide a normal use case.
277+
// Create an adapter and an enforcer.
278+
// NewEnforcer() will load the policy automatically.
279+
a, _ := NewAdapter(driverName, dataSourceName, dbSpecified...)
280+
e, _ := casbin.NewEnforcer("examples/rbac_model.conf")
281+
282+
// Now set the adapter
283+
e.SetAdapter(a)
284+
285+
var err error
286+
logErr := func(action string) {
287+
if err != nil {
288+
t.Fatalf("test action[%s] failed, err: %v", action, err)
289+
}
290+
}
291+
292+
err = a.UpdatePolicy("p", "p", []string{"bob", "data2", "write"}, []string{"alice", "data2", "write"})
293+
logErr("UpdatePolicy")
294+
295+
testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"alice", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}})
296+
}
297+
270298
func TestAdapters(t *testing.T) {
271299
// You can also use the following way to use an existing DB "abc":
272300
// testSaveLoad(t, "mysql", "root:@tcp(127.0.0.1:3306)/abc", true)
@@ -284,4 +312,7 @@ func TestAdapters(t *testing.T) {
284312

285313
testRemovePolicies(t, "mysql", "root:@tcp(127.0.0.1:3306)/")
286314
testRemovePolicies(t, "postgres", "user=postgres host=127.0.0.1 port=5432 sslmode=disable")
315+
316+
testUpdatePolicies(t, "mysql", "root:@tcp(127.0.0.1:3306)/")
317+
testUpdatePolicies(t, "postgres", "user=postgres host=127.0.0.1 port=5432 sslmode=disable")
287318
}

0 commit comments

Comments
 (0)