main.go 1.3 KB
Newer Older
1 2 3
package main

import (
khoipham's avatar
khoipham committed
4
	pgadapter "github.com/casbin/casbin-pg-adapter"
khoipham's avatar
khoipham committed
5
	"github.com/casbin/casbin/v2"
6 7 8 9 10 11
)

func main() {
	// Initialize a Go-pg adapter and use it in a Casbin enforcer:
	// The adapter will use the Postgres database named "casbin".
	// If it doesn't exist, the adapter will create it automatically.
khoipham's avatar
khoipham committed
12
	a, _ := pgadapter.NewAdapter("postgresql://postgres:password@postgres:5432/postgres?sslmode=disable") // Your driver and data source.
khoipham's avatar
khoipham committed
13 14 15 16 17 18
	// Alternatively, you can construct an adapter instance with *pg.Options:
	// a, _ := pgadapter.NewAdapter(&pg.Options{
	//     Database: "...",
	//     User: "...",
	//     Password: "...",
	// })
19 20 21 22 23

	// Or you can use an existing DB "abc" like this:
	// The adapter will use the table named "casbin_rule".
	// If it doesn't exist, the adapter will create it automatically.

khoipham's avatar
khoipham committed
24
	e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a)
25 26 27 28

	// Load the policy from DB.
	e.LoadPolicy()

khoipham's avatar
khoipham committed
29 30 31 32 33 34
	// Alternatively load a subset of policy as demonstrated at https://casbin.org/docs/en/policy-subset-loading
	// e.LoadFilteredPolicy(&pgadapter.Filter{
	// 	P: []string{"", "data1"},
	// 	G: []string{"alice"},
	// })

35 36 37 38 39 40 41 42 43 44
	// Check the permission.
	e.Enforce("alice", "data1", "read")

	// Modify the policy.
	// e.AddPolicy(...)
	// e.RemovePolicy(...)

	// Save the policy back to DB.
	e.SavePolicy()
}