Commit 7fe62e47 authored by nafisfaysal's avatar nafisfaysal

Implement casbin adapter for go-pg/pg

parent 3f155b65
# casbin-pg-adapter Go-pg Adapter
A go-pg adapter for casbin ====
Go-pg Adapter is the [Go-pg](https://github.com/go-pg/pg) adapter for [Casbin](https://github.com/casbin/casbin). With this library, Casbin can load policy from PostgreSQL or save policy to it.
## Installation
go get github.com/MonedaCacao/casbin-pg-adapter
## Env Variables
Populate .env with necessary environment variable values:
$ nano .env
```
DATABASE_ADDRESSES=
DATABASE_USER_NAME=
DATABSE_USER_PASSORD=
```
## Simple Postgres Example
```go
package main
import (
pgadapter "github.com/MonedaCacao/casbin-pg-adapter"
"github.com/casbin/casbin"
)
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.
a, _ := pgadapter.NewAdapter() // Your driver and data source.
// 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.
e := casbin.NewEnforcer("examples/rbac_model.conf", a)
// Load the policy from DB.
e.LoadPolicy()
// Check the permission.
e.Enforce("alice", "data1", "read")
// Modify the policy.
// e.AddPolicy(...)
// e.RemovePolicy(...)
// Save the policy back to DB.
e.SavePolicy()
}
```
## Getting Help
- [Casbin](https://github.com/casbin/casbin)
## License
This project is under Apache 2.0 License. See the [LICENSE](LICENSE) file for the full license text.
package pgadapter
import (
"github.com/MonedaCacao/casbin-pg-adapter/config"
"github.com/casbin/casbin/model"
"github.com/casbin/casbin/persist"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
"log"
"strings"
)
const (
tableExistsErrorCode = "ERROR #42P07"
)
// CasbinRule represents a rule in Casbin.
type CasbinRule struct {
Id int
PType string
V0 string
V1 string
V2 string
V3 string
V4 string
V5 string
}
// Adapter represents the github.com/go-pg/pg adapter for policy storage.
type Adapter struct {
db *pg.DB
}
// finalizer is the destructor for Adapter.
func finalizer(a *Adapter) {}
// NewAdapter is the constructor for Adapter.
// The adapter will automatically create a DB named "casbin"
func NewAdapter() (*Adapter, error) {
a := Adapter{}
// Open the DB, create it if not existed.
err := a.open()
if err != nil {
return nil, err
}
return &a, nil
}
func (a *Adapter) createDatabase() error {
var err error
var db *pg.DB
env := config.GetEnvVariables()
cfg := config.GetConfig(*env)
db = pg.Connect(&pg.Options{
Addr: cfg.DatabaseAddresses,
User: cfg.DatabaseUsername,
Password: cfg.DatabseUserPassord,
})
defer db.Close()
_, err = db.Exec("CREATE DATABASE casbin")
if err != nil {
log.Println("can't create database", err)
return err
}
return nil
}
func (a *Adapter) open() error {
var err error
var db *pg.DB
env := config.GetEnvVariables()
cfg := config.GetConfig(*env)
err = a.createDatabase()
if err != nil {
panic(err)
}
db = pg.Connect(&pg.Options{
Addr: cfg.DatabaseAddresses,
User: cfg.DatabaseUsername,
Password: cfg.DatabseUserPassord,
Database: "casbin",
})
a.db = db
return a.createTable()
}
func (a *Adapter) close() error {
err := a.db.Close()
if err != nil {
return err
}
a.db = nil
return nil
}
func (a *Adapter) createTable() error {
err := a.db.CreateTable(&CasbinRule{}, &orm.CreateTableOptions{
Temp: false,
})
if err != nil {
errorCode := err.Error()[0:12]
if errorCode != tableExistsErrorCode {
return err
}
}
return nil
}
func (a *Adapter) dropTable() error {
err := a.db.DropTable(&CasbinRule{}, &orm.DropTableOptions{})
if err != nil {
return err
}
return nil
}
func loadPolicyLine(line *CasbinRule, model model.Model) {
const prefixLine = ", "
var sb strings.Builder
sb.WriteString(line.PType)
if len(line.V0) > 0 {
sb.WriteString(prefixLine)
sb.WriteString(line.V0)
}
if len(line.V1) > 0 {
sb.WriteString(prefixLine)
sb.WriteString(line.V1)
}
if len(line.V2) > 0 {
sb.WriteString(prefixLine)
sb.WriteString(line.V2)
}
if len(line.V3) > 0 {
sb.WriteString(prefixLine)
sb.WriteString(line.V3)
}
if len(line.V4) > 0 {
sb.WriteString(prefixLine)
sb.WriteString(line.V4)
}
if len(line.V5) > 0 {
sb.WriteString(prefixLine)
sb.WriteString(line.V5)
}
persist.LoadPolicyLine(sb.String(), model)
}
// LoadPolicy loads policy from database.
func (a *Adapter) LoadPolicy(model model.Model) error {
var lines []*CasbinRule
if _, err := a.db.Query(&lines, `SELECT * FROM casbin_rules`); err != nil {
return err
}
for _, line := range lines {
loadPolicyLine(line, model)
}
return nil
}
func savePolicyLine(ptype string, rule []string) *CasbinRule {
line := &CasbinRule{PType: ptype}
l := len(rule)
if l > 0 {
line.V0 = rule[0]
}
if l > 1 {
line.V1 = rule[1]
}
if l > 2 {
line.V2 = rule[2]
}
if l > 3 {
line.V3 = rule[3]
}
if l > 4 {
line.V4 = rule[4]
}
if l > 5 {
line.V5 = rule[5]
}
return line
}
// SavePolicy saves policy to database.
func (a *Adapter) SavePolicy(model model.Model) error {
err := a.dropTable()
if err != nil {
return err
}
err = a.createTable()
if err != nil {
return err
}
var lines []*CasbinRule
for ptype, ast := range model["p"] {
for _, rule := range ast.Policy {
line := savePolicyLine(ptype, rule)
lines = append(lines, line)
}
}
for ptype, ast := range model["g"] {
for _, rule := range ast.Policy {
line := savePolicyLine(ptype, rule)
lines = append(lines, line)
}
}
err = a.db.Insert(&lines)
return err
}
// AddPolicy adds a policy rule to the storage.
func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error {
line := savePolicyLine(ptype, rule)
err := a.db.Insert(line)
return err
}
// RemovePolicy removes a policy rule from the storage.
func (a *Adapter) RemovePolicy(sec string, ptype string, rule []string) error {
line := savePolicyLine(ptype, rule)
err := a.db.Delete(line)
return err
}
// RemoveFilteredPolicy removes policy rules that match the filter from the storage.
func (a *Adapter) RemoveFilteredPolicy(sec string, ptype string, fieldIndex int, fieldValues ...string) error {
line := &CasbinRule{PType: ptype}
idx := fieldIndex + len(fieldValues)
if fieldIndex <= 0 && idx > 0 {
line.V0 = fieldValues[0-fieldIndex]
}
if fieldIndex <= 1 && idx > 1 {
line.V1 = fieldValues[1-fieldIndex]
}
if fieldIndex <= 2 && idx > 2 {
line.V2 = fieldValues[2-fieldIndex]
}
if fieldIndex <= 3 && idx > 3 {
line.V3 = fieldValues[3-fieldIndex]
}
if fieldIndex <= 4 && idx > 4 {
line.V4 = fieldValues[4-fieldIndex]
}
if fieldIndex <= 5 && idx > 5 {
line.V5 = fieldValues[5-fieldIndex]
}
err := a.db.Delete(line)
return err
}
package pgadapter
import (
"github.com/casbin/casbin"
"github.com/casbin/casbin/util"
"log"
"testing"
)
func testGetPolicy(t *testing.T, e *casbin.Enforcer, res [][]string) {
t.Helper()
myRes := e.GetPolicy()
log.Print("Policy Got: ", myRes)
if !util.Array2DEquals(res, myRes) {
t.Error("Policy Got: ", myRes, ", supposed to be ", res)
}
}
func initPolicy(t *testing.T) {
// Because the DB is empty at first,
// so we need to load the policy from the file adapter (.CSV) first.
e := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv")
a, err := NewAdapter()
if err != nil {
panic(err)
}
// This is a trick to save the current policy to the DB.
// We can't call e.SavePolicy() because the adapter in the enforcer is still the file adapter.
// The current policy means the policy in the Casbin enforcer (aka in memory).
err = a.SavePolicy(e.GetModel())
if err != nil {
panic(err)
}
// Clear the current policy.
e.ClearPolicy()
testGetPolicy(t, e, [][]string{})
// Load the policy from DB.
err = a.LoadPolicy(e.GetModel())
if err != nil {
panic(err)
}
testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}})
}
func testSaveLoad(t *testing.T) {
// Initialize some policy in DB.
initPolicy(t)
// Note: you don't need to look at the above code
// if you already have a working DB with policy inside.
// Now the DB has policy, so we can provide a normal use case.
// Create an adapter and an enforcer.
// NewEnforcer() will load the policy automatically.
a, _ := NewAdapter()
e := casbin.NewEnforcer("examples/rbac_model.conf", a)
testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}})
}
func testAutoSave(t *testing.T) {
// Initialize some policy in DB.
initPolicy(t)
// Note: you don't need to look at the above code
// if you already have a working DB with policy inside.
// Now the DB has policy, so we can provide a normal use case.
// Create an adapter and an enforcer.
// NewEnforcer() will load the policy automatically.
a, _ := NewAdapter()
e := casbin.NewEnforcer("examples/rbac_model.conf", a)
// AutoSave is enabled by default.
// Now we disable it.
e.EnableAutoSave(false)
// Because AutoSave is disabled, the policy change only affects the policy in Casbin enforcer,
// it doesn't affect the policy in the storage.
e.AddPolicy("alice", "data1", "write")
// Reload the policy from the storage to see the effect.
e.LoadPolicy()
// This is still the original policy.
testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}})
// Now we enable the AutoSave.
e.EnableAutoSave(true)
// Because AutoSave is enabled, the policy change not only affects the policy in Casbin enforcer,
// but also affects the policy in the storage.
e.AddPolicy("alice", "data1", "write")
// Reload the policy from the storage to see the effect.
e.LoadPolicy()
// The policy has a new rule: {"alice", "data1", "write"}.
testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}, {"alice", "data1", "write"}})
testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}, {"alice", "data1", "write"}})
}
func TestAdapters(t *testing.T) {
// You can also use the following way to use an existing DB "abc":
testSaveLoad(t)
testAutoSave(t)
}
package config
import (
"os"
"path/filepath"
log "github.com/inconshreveable/log15"
"github.com/spf13/viper"
)
// Config contains the config.yml settings
type Config struct {
DatabaseAddresses string
DatabaseUsername string
DatabseUserPassord string
Database string
}
// Env contains the environment variables
type Env struct {
Environment string
DatabasePassword string
ProjectRootPath string
}
// GetEnvVariables gets the environment variables and returns a new env struct
func GetEnvVariables() *Env {
viper.AutomaticEnv()
viper.SetDefault("go_env", "development")
viper.SetDefault("database_password", "")
// Get the current environment
environment := viper.GetString("go_env")
log.Info("Initializing", "ENVIROMENT", environment)
// Get the enviroment variables
log.Info("Obtaining env variables")
databasePassword := viper.GetString("database_password")
env := &Env{
Environment: environment,
DatabasePassword: databasePassword,
// Secret: secret,
}
return env
}
// GetConfig reads the configuration file and returns a new config
func GetConfig(env Env) *Config {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AddConfigPath(env.ProjectRootPath)
log.Info("Reading config file")
err := viper.ReadInConfig()
if err != nil {
log.Error("Missing configuration file.", "Error:", err)
os.Exit(1)
}
var config Config
err = viper.UnmarshalKey(env.Environment, &config)
if err != nil {
panic("Unable to unmarshal config")
}
return &config
}
// GetTestingEnvVariables returns env variables for testing
func GetTestingEnvVariables() *Env {
wd, err := os.Getwd()
if err != nil {
panic(err)
}
// Since we are loading configuration files from the root dir, when running from main package
// this is fine but for testing we need to find the root dir
dir := filepath.Dir(wd)
for dir[len(dir)-24:] != "gopg-casbin-adapter" {
dir = filepath.Dir(dir)
}
return &Env{Environment: "test", ProjectRootPath: dir}
}
DATABASE_ADDRESSES=
DATABASE_USER_NAME=
DATABSE_USER_PASSORD=
\ No newline at end of file
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
g2 = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
\ No newline at end of file
p, alice, data1, read
p, bob, data2, write
p, data2_admin, data2, read
p, data2_admin, data2, write
g, alice, data2_admin
\ No newline at end of file
module github.com/MonedaCacao/casbin-pg-adapter
go 1.12
require (
github.com/casbin/casbin v1.9.1
github.com/go-pg/pg v8.0.5+incompatible
github.com/inconshreveable/log15 v0.0.0-20180818164646-67afb5ed74ec
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/mattn/go-colorable v0.1.2 // indirect
github.com/onsi/ginkgo v1.8.0 // indirect
github.com/onsi/gomega v1.5.0 // indirect
github.com/spf13/viper v1.4.0
mellium.im/sasl v0.2.1 // indirect
)
This diff is collapsed.
package main
import (
pgadapter "github.com/MonedaCacao/casbin-pg-adapter"
"github.com/casbin/casbin"
)
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.
a, _ := pgadapter.NewAdapter() // Your driver and data source.
// 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.
e := casbin.NewEnforcer("examples/rbac_model.conf", a)
// Load the policy from DB.
e.LoadPolicy()
// Check the permission.
e.Enforce("alice", "data1", "read")
// Modify the policy.
// e.AddPolicy(...)
// e.RemovePolicy(...)
// Save the policy back to DB.
e.SavePolicy()
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment