/sql-adapter

database/sql Adapter for Casbin V2

Primary LanguageGoApache License 2.0Apache-2.0

sql-adapter

Go Report Card Build Status Coverage Status PkgGoDev Release Sourcegraph License


The sql-adapter is a database/sql adapter for Casbin v2.

With this library, Casbin can load policy lines or save policy lines from supported databases.

Tested Databases

master branch

oracle branch

Installation

go get github.com/Blank-Xu/sql-adapter

Examples

Simple example for MySQL

package main

import (
    "database/sql"
    "log"
    "runtime"
    "time"

    sqladapter "github.com/Blank-Xu/sql-adapter"
    "github.com/casbin/casbin/v2"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    // connect to the database first.
    db, err := sql.Open("mysql", "YourUserName:YourPassword@tcp(127.0.0.1:3306)/YourDBName?charset=utf8")
    if err != nil {
        panic(err)
    }
    if err = db.Ping();err!=nil{
        panic(err)
    }
    defer db.Close()

    db.SetMaxOpenConns(20)
    db.SetMaxIdleConns(10)
    db.SetConnMaxLifetime(time.Minute * 10)

    // Initialize an adapter and use it in a Casbin enforcer:
    // The adapter will use the MySQL table name "casbin_rule_test",
    // the default table name is "casbin_rule" if it is not given.
    // If it doesn't exist, the adapter will create it automatically.
    a, err := sqladapter.NewAdapter(db, "mysql", "casbin_rule_test")
    if err != nil {
        panic(err)
    }

    e, err := casbin.NewEnforcer("test/testdata/rbac_model.conf", a)
    if err != nil {
        panic(err)
    }

    // Load the policies from DB.
    if err = e.LoadPolicy(); err != nil {
        log.Println("LoadPolicy failed, err: ", err)
    }

    // Check the permission.
    has, err := e.Enforce("alice", "data1", "read")
    if err != nil {
        log.Println("Enforce failed, err: ", err)
    }
    if !has {
        log.Println("do not have permission")
    }

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

    // Save the policy back to DB.
    if err = e.SavePolicy(); err != nil {
        log.Println("SavePolicy failed, err: ", err)
    }
}

Getting Help

License

This project is under Apache 2.0 License. See the LICENSE file for the full license text.