Skip to content

Latest commit

 

History

95 Commits

Folders and files

Repository files navigation

Xorm Adapter

Build Coverage Status Go Reference Release License Discord

Xorm Adapter is the Xorm adapter for Apache Casbin. It lets Casbin load policy from, and save policy to, any database that Xorm supports.

Supported databases

Any database with an Xorm driver works. Import the driver you need next to the adapter:

Database Driver name Driver package
MySQL, MariaDB, TiDB mysql github.com/go-sql-driver/mysql
MySQL (MyMySQL) mymysql github.com/ziutek/mymysql/godrv
PostgreSQL postgres github.com/lib/pq
SQLite sqlite3 github.com/mattn/go-sqlite3
SQL Server mssql github.com/denisenkom/go-mssqldb
Oracle (experimental) oci8 github.com/mattn/go-oci8

Installation

go get github.com/apache/casbin-xorm-adapter/v3

Quick start

MySQL

package main

import (
	"log"

	xormadapter "github.com/apache/casbin-xorm-adapter/v3"
	"github.com/casbin/casbin/v3"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	// Without a database name in the DSN, the adapter creates and uses a database named "casbin".
	a, err := xormadapter.NewAdapter("mysql", "username:password@tcp(127.0.0.1:3306)/")
	if err != nil {
		log.Fatal(err)
	}

	// To use an existing database instead, put it in the DSN and pass true:
	// a, err := xormadapter.NewAdapter("mysql", "username:password@tcp(127.0.0.1:3306)/abc", true)

	// NewEnforcer loads the policy from the database.
	e, err := casbin.NewEnforcer("examples/rbac_model.conf", a)
	if err != nil {
		log.Fatal(err)
	}

	// Check a permission.
	ok, err := e.Enforce("alice", "data1", "read")
	if err != nil {
		log.Fatal(err)
	}
	log.Println(ok)

	// AddPolicy, RemovePolicy and the other management APIs write to the database right away.
	if _, err = e.AddPolicy("bob", "data2", "read"); err != nil {
		log.Fatal(err)
	}

	// Reload the policy from the database.
	if err = e.LoadPolicy(); err != nil {
		log.Fatal(err)
	}
}

PostgreSQL

package main

import (
	"log"

	xormadapter "github.com/apache/casbin-xorm-adapter/v3"
	"github.com/casbin/casbin/v3"
	_ "github.com/lib/pq"
)

func main() {
	// Without dbname in the DSN, the adapter creates and uses a database named "casbin".
	a, err := xormadapter.NewAdapter("postgres", "user=username password=password host=127.0.0.1 port=5432 sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}

	// To use an existing database instead, put it in the DSN and pass true:
	// a, err := xormadapter.NewAdapter("postgres", "dbname=abc user=username password=password host=127.0.0.1 port=5432 sslmode=disable", true)

	e, err := casbin.NewEnforcer("examples/rbac_model.conf", a)
	if err != nil {
		log.Fatal(err)
	}

	ok, _ := e.Enforce("alice", "data1", "read")
	log.Println(ok)
}

To keep the table in a schema other than public, set search_path in the DSN, for example dbname=abc search_path=myschema. The adapter looks for and creates the table in the schema that search_path resolves to.

Other databases

Automatic database creation covers MySQL-style and PostgreSQL DSNs. For SQLite, SQL Server, Oracle and anything else, give a DSN that already points at a database and pass true:

a, err := xormadapter.NewAdapter("sqlite3", "file:casbin.db?cache=shared", true)

Creating an adapter

Constructor Use it when
NewAdapter(driverName, dataSourceName, dbSpecified...) The adapter opens its own connection and uses the default table casbin_rule.
NewAdapterWithTableName(driverName, dataSourceName, tableName, tablePrefix, dbSpecified...) Same, with your own table name and optional prefix (the table becomes tablePrefix + tableName).
NewAdapterByEngine(engine) Your application already has an *xorm.Engine and the adapter should share it.
NewAdapterByEngineWithTableName(engine, tableName, tablePrefix) Same, with your own table name and prefix.

dbSpecified defaults to false, which makes the adapter create a database named casbin and connect to it. Pass true when the DSN already names the database you want.

engine, err := xorm.NewEngine("mysql", "username:password@tcp(127.0.0.1:3306)/abc")
if err != nil {
	log.Fatal(err)
}

a, err := xormadapter.NewAdapterByEngineWithTableName(engine, "rule", "casbin_")

Table schema

The adapter creates the table when it starts, if it does not exist yet. Every policy line is one row:

Column Type Content
ptype varchar(100) Policy type, such as p or g
v0 to v5 varchar(100) Policy fields, in order

Each column has its own index. If you create the table yourself, keep the same column names.

Filtered policy loading

On large policy sets, load only the rules you need with xormadapter.Filter. Every field takes a list of accepted values, and an empty field matches everything:

err := e.LoadFilteredPolicy(xormadapter.Filter{
	Ptype: []string{"p"},
	V0:    []string{"alice", "bob"},
})

After a filtered load, e.SavePolicy() is refused so that a partial policy cannot overwrite the full one in the database.

Batch and update operations

The adapter implements Casbin's batch and update interfaces, so the matching enforcer APIs write straight to the database:

  • AddPolicies and RemovePolicies run in a single transaction.
  • UpdatePolicy, UpdatePolicies and UpdateFilteredPolicies change rows in place.

SavePolicy drops and recreates the table, then writes the whole policy from memory. Use it to replace the stored policy, not for routine changes.

Context support

Each storage method has a Ctx version that takes a context.Context, for timeouts and cancellation: LoadPolicyCtx, SavePolicyCtx, AddPolicyCtx, RemovePolicyCtx and RemoveFilteredPolicyCtx.

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

if err := a.AddPolicyCtx(ctx, "p", "p", []string{"alice", "data1", "read"}); err != nil {
	log.Fatal(err)
}

Getting help

License

This project is licensed under the Apache 2.0 License.

Releases

Packages

Used by

Contributors

Languages