Coder Social home page Coder Social logo

casbin / gorm-adapter Goto Github PK

View Code? Open in Web Editor NEW
653.0 6.0 201.0 173 KB

GORM adapter for Casbin, see extended version of GORM Adapter Ex at: https://github.com/casbin/gorm-adapter-ex

Home Page: https://github.com/casbin/casbin

License: Apache License 2.0

Go 100.00%
casbin adapter storage-driver gorm orm access-control authorization acl rbac abac

gorm-adapter's Introduction

Gorm Adapter

In v3.0.3, method NewAdapterByDB creates table named casbin_rules,
we fix it to casbin_rule after that.
If you used v3.0.3 and less, and you want to update it,
you might need to migrate data manually. Find out more at: #78

Go Report Card Go Coverage Status Godoc Release Discord Sourcegraph

Gorm Adapter is the Gorm adapter for Casbin. With this library, Casbin can load policy from Gorm supported database or save policy to it.

Based on Officially Supported Databases, The current supported databases are:

  • MySQL
  • PostgreSQL
  • SQL Server
  • Sqlite3

gorm-adapter use github.com/glebarez/sqlite instead of gorm official sqlite driver gorm.io/driver/sqlite because the latter needs cgo support. But there is almost no difference between the two driver. If there is a difference in use, please submit an issue.

  • other 3rd-party supported DBs in Gorm website or other places.

Installation

go get github.com/casbin/gorm-adapter/v3

Simple Example

package main

import (
	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	// Initialize a Gorm adapter and use it in a Casbin enforcer:
	// The adapter will use the MySQL database named "casbin".
	// If it doesn't exist, the adapter will create it automatically.
	// You can also use an already existing gorm instance with gormadapter.NewAdapterByDB(gormInstance)
	a, _ := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/") // Your driver and data source.
	e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a)
	
	// 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.
	// a := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/abc", true)

	// 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()
}

Turn off AutoMigrate

New an adapter will use AutoMigrate by default for create table, if you want to turn it off, please use API TurnOffAutoMigrate(db *gorm.DB) *gorm.DB. See example:

db, err := gorm.Open(mysql.Open("root:@tcp(127.0.0.1:3306)/casbin"), &gorm.Config{})
TurnOffAutoMigrate(db)
// a,_ := NewAdapterByDB(...)
// a,_ := NewAdapterByDBUseTableName(...)
a,_ := NewAdapterByDBWithCustomTable(...)

Find out more details at gorm-adapter#162

Customize table columns example

You can change the gorm struct tags, but the table structure must stay the same.

package main

import (
	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"gorm.io/gorm"
)

func main() {
	// Increase the column size to 512.
	type CasbinRule struct {
		ID    uint   `gorm:"primaryKey;autoIncrement"`
		Ptype string `gorm:"size:512;uniqueIndex:unique_index"`
		V0    string `gorm:"size:512;uniqueIndex:unique_index"`
		V1    string `gorm:"size:512;uniqueIndex:unique_index"`
		V2    string `gorm:"size:512;uniqueIndex:unique_index"`
		V3    string `gorm:"size:512;uniqueIndex:unique_index"`
		V4    string `gorm:"size:512;uniqueIndex:unique_index"`
		V5    string `gorm:"size:512;uniqueIndex:unique_index"`
	}

	db, _ := gorm.Open(...)

	// Initialize a Gorm adapter and use it in a Casbin enforcer:
	// The adapter will use an existing gorm.DB instnace.
	a, _ := gormadapter.NewAdapterByDBWithCustomTable(db, &CasbinRule{}) 
	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()
}

Transaction

You can modify policies within a transaction.See example:

package main

func main() {
	a, err := NewAdapterByDB(db)
	e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a)
	err = e.GetAdapter().(*Adapter).Transaction(e, func(e casbin.IEnforcer) error {
		_, err := e.AddPolicy("jack", "data1", "write")
		if err != nil {
			return err
		}
		_, err = e.AddPolicy("jack", "data2", "write")
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		// handle if transaction failed
		return
	}
}

ConditionsToGormQuery

ConditionsToGormQuery() is a function that converts multiple query conditions into a GORM query statement You can use the GetAllowedObjectConditions() API of Casbin to get conditions, and choose the way of combining conditions through combineType.

ConditionsToGormQuery() allows Casbin to be combined with SQL, and you can use it to implement many functions.

Example: GetAllowedRecordsForUser

DataBase example:

id title author publisher publish_data price category_id
1 book1 author1 publisher1 2023-04-09 16:23:42 10 1
2 book2 author1 publisher1 2023-04-09 16:23:44 20 2
3 book3 author2 publisher1 2023-04-09 16:23:44 30 1
4 book4 author2 publisher2 2023-04-09 16:23:45 10 3
5 book5 author3 publisher2 2023-04-09 16:23:45 50 1
6 book6 author3 publisher2 2023-04-09 16:23:46 60 2
type Book struct {
    ID          int
    Title       string
    Author      string
    Publisher   string
    PublishDate time.Time
    Price       float64
    CategoryID  int
}

func TestGetAllowedRecordsForUser(t *testing.T) {
	e, _ := casbin.NewEnforcer("examples/object_conditions_model.conf", "examples/object_conditions_policy.csv")

	conditions, err := e.GetAllowedObjectConditions("alice", "read", "r.obj.")
	if err != nil {
		panic(err)
	}
	fmt.Println(conditions)

	dsn := "root:root@tcp(127.0.0.1:3307)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	fmt.Println("CombineTypeOr")
	rows, err := ConditionsToGormQuery(db, conditions, CombineTypeOr).Model(&Book{}).Rows()
	defer rows.Close()
	var b Book
	for rows.Next() {
		err := db.ScanRows(rows, &b)
		if err != nil {
			panic(err)
		}
		log.Println(b)
	}

	fmt.Println("CombineTypeAnd")
	rows, err = ConditionsToGormQuery(db, conditions, CombineTypeAnd).Model(&Book{}).Rows()
	defer rows.Close()
	for rows.Next() {
		err := db.ScanRows(rows, &b)
		if err != nil {
			panic(err)
		}
		log.Println(b)
	}
}

Context Adapter

gormadapter supports adapter with context, the following is a timeout control implemented using context

a, _ := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/") // Your driver and data source.
// Limited time 300s
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Microsecond)
defer cancel()
err := a.AddPolicyCtx(ctx, "p", "p", []string{"alice", "data1", "read"})
if err != nil {
    panic(err)
}

Getting Help

License

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

gorm-adapter's People

Contributors

00lt00 avatar abingcbc avatar dallen42 avatar despire avatar dirablue avatar dsuket avatar hanshengzhao avatar helloshaohua avatar hiteshsethi avatar hsluoyz avatar huangkuan123 avatar jleeh avatar kilosonc avatar l1ghtman2k avatar maocaicai avatar miaolz123 avatar muzhou233 avatar nodece avatar nonchan7720 avatar pokisemaine avatar selflocking avatar snyh avatar sylarxu avatar tangyang9464 avatar uran0sh avatar vanelord67 avatar warnerwu avatar weloe avatar wuzhican avatar xiao-niu-ren avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

gorm-adapter's Issues

User should define database

In the gorm-adapter, the following lines have hard-coded "magic" values which should be defined by the user in the config file rather than set here:

gorm-adapter's DefaultTableNameHandler

When I use gorm-adapter's DefaultTableNameHandler to add a prefix name to each table, casbin's default table "casbin_rule" cannot be used to remove a policy.
That's because casbin_rule has no primary key, and policy's remove action is different from add action . I tried to init gorm-adapter in front of DefaultTableNameHandler, it still not woked.
Finially, I change casbin's default table name "casbin_rule" to "$prefix_casbin_rule", and make a judgement in DefaultTableNameHandler : if table name is equal to "$prefix_casbin_rule", prefix name will not be added .
If you any better solution , welcome to reply to me~

Avoid the automatic use of LoadPolicy() loading the policy

In order to avoid the automatic use of LoadPolicy loading strategy, I think the setting of isFiltered should be added in Adapter.

a, _ := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/") 
e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a)
// It automatically loaded all policies

postgres - won't detect whether database exists

Repeated database creation:

It will still trying create the database, even I have specified dbname=casbin in gorm dsn:

github.com/casbin/gorm-adapter/[email protected]/adapter.go:237 ERROR: database "casbin" already exists (SQLSTATE 42P04)

Better create only if not exists yet, I guess.

BTW, the 2nd issue about timezone is moved to: #96

Can't call func LoadPolicy by using tablePrefix

first i init an enforcer by using tablePrefix

cas, _ := casbin.NewEnforcer(modelPath)

adapter, err := gormadapter.NewAdapterByDBUsePrefix(db, "test_")
if err != nil {
	panic(err)
}

cas.SetAdapter(adapter)

then i call func cas.LoadPolicy(), that won't found any policy cuz it search db.casbin_rule
not db.test_casbin_rule

here is the code

// LoadPolicy loads policy from database.
func (a *Adapter) LoadPolicy(model model.Model) error {
	var lines []CasbinRule   // this line 
	if err := a.db.Find(&lines).Error; err != nil {
		return err
	}

	for _, line := range lines {
		loadPolicyLine(line, model)
	}

	return nil
}

open postgresql failed

func (a *Adapter) open() error {
	var err error
	var db *gorm.DB

	if a.dbSpecified {
		db, err = openDBConnection(a.driverName, a.dataSourceName)
		if err != nil {
			return err
		}
	} else {
		if err = a.createDatabase(); err != nil {
			return err
		}
		if a.driverName == "postgres" {
			**db, err = openDBConnection(a.driverName, a.dataSourceName+" dbname="+a.databaseName)**
		} else if a.driverName == "sqlite3" {
			db, err = openDBConnection(a.driverName, a.dataSourceName)
		} else {
			db, err = openDBConnection(a.driverName, a.dataSourceName+a.databaseName)
		}
		if err != nil {
			return err
		}
	}
	a.db = db.Scopes(CasbinTableName(&CasbinRule{TableName:a.tableName,TablePrefix:a.tablePrefix})).
		Session(&gorm.Session{WithConditions: true})
	return a.createTable()
}

change it to:

if a.driverName == "postgres" {
			**db, err = openDBConnection(a.driverName, a.dataSourceName)**
		} 

For the sake of god, please fix the "casbin_rule" table name bug

We already see tons of complaints from the users for such a boring problem, see:

I'm so tired of it. Such bugs are harming our software quality.

What I want to achieve is:

  1. Not a single bug report about the "casbin_rule" or "casbin_rules" table name any more.
  2. For a new user, we always use the new table name "casbin_rule".
  3. We take care of the DB migration. If the user is using old DB table name "casbin_rules", we will create the new table "casbin_rule" and migrate the data from old table to new table. If the user is using a custom DB table name like "abc", we do nothing.
  4. If there's any bugs for newer version of Gorm, then don't update Gorm' version. Don't use a Gorm version with bugs.
  5. Fix any existing bugs with a PR. Then make a release.

Behaviour of NewAdapterByDB() has a breaking change

Hi,

Just a heads up for other users:
I've updated from gorm-adapter 3.0.3 to 3.2.0 today and found that NewAdapterByDB() is now using "casbin_rule" as table name vs. "casbin_rules" in 3.0.3.

Therefore the user group memberships where missing in the new "casbin_rule" table.

The reason is probably (didn't verify) the use of the Gorm Migrator in 3.0.3:
return a.db.Migrator().CreateTable(a.getTableInstance())
In Gorm "CasbinRule" will result in a table name "casbin_rules".

This fixed if for me:
insert into casbin_rule(ptype,v0,v1) select p_type,v0,v1 from casbin_rules where p_type = 'g';

Application build failed

version:
github.com/casbin/gorm-adapter/v3 v3.0.1

log :

exec: "gcc": executable file not found in %PATH%

The build fails under Windows because I have not installed gcc and cannot build qlite3

Rely on explanation go mod why github.com/mattn/go-sqlite3

# github.com/mattn/go-sqlite3
myApp/internal/cas
github.com/casbin/gorm-adapter/v3
gorm.io/driver/sqlite
github.com/mattn/go-sqlite3

NewAdapterByDB failed due to different gorm type

tried to use exsit gorm instance which is "github.com/jinzhu/gorm", failed due to below error:

Cannot use 'component.DB' (type *"github.com/jinzhu/gorm".DB) as type *"gorm.io/gorm".DB

//code sample

adapter, err := gormadapter.NewAdapterByDB(component.DB)

Waiting for new release

Would it be possible to bump the version and perform a new release?
sorry for urging you , i'm really like this pkg
alse really need it

why CasbinRule struct dosen't have Id field?

type CasbinRule struct {
	PType string `gorm:"size:100"`
	V0    string `gorm:"size:100"`
	V1    string `gorm:"size:100"`
	V2    string `gorm:"size:100"`
	V3    string `gorm:"size:100"`
	V4    string `gorm:"size:100"`
	V5    string `gorm:"size:100"`
}

Panic when trying to connect

Hi, I'm receiving this error when I try to call NewAdapter using correct (url encoded) credentials.

panic: mssql: Incorrect syntax near 'casbin'.

I don't think this is an issue with my connection string, but what do you think? This is how I'm calling it.

a := gormadapter.NewAdapter("mssql", "sqlserver://"+username+":"+pass+"@remote_url:1433?database=dbname")

support customize table name

Our app use multi permission models. I'll init multi Enforce instance while app startup, each Enforce load different model.
I use mysql to persist policy through gorm-adapter. I wanna to save policy to different table so each Enforce can load policy precisely.
How can I do that? Thanks

postgres - can't set timezone


Can't set timezone:

If I specify TimeZone=Asia/Shanghai in gorm dsn, then will get error:

2021/04/22 19:06:44 /home/eric/go/pkg/mod/github.com/casbin/gorm-adapter/[email protected]/adapter.go:214
[error] failed to initialize database, got error failed to connect to host=localhost user=postgres database=casbin: server error (FATAL: invalid value for parameter "TimeZone": "Asia/Shanghai dbname=casbin" (SQLSTATE 22023))
model conf: /home/eric/go/src/gitlab.com/kuchaguangjie/go-learn/casbin/adapter/gorm/conf/rbac_model.conf
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x60 pc=0x8ca865]

goroutine 1 [running]:
github.com/casbin/gorm-adapter/v3.(*Adapter).IsFiltered(0x0, 0x7fce8af15340)
/home/eric/go/pkg/mod/github.com/casbin/gorm-adapter/[email protected]/adapter.go:396 +0x5
github.com/casbin/casbin/v2.(*Enforcer).InitWithModelAndAdapter(0xc00042e100, 0xc00021b770, 0x7fce8af15340, 0x0, 0x0, 0x7fce8af15340)
/home/eric/go/pkg/mod/github.com/casbin/casbin/[email protected]/enforcer.go:168 +0x142
github.com/casbin/casbin/v2.(*Enforcer).InitWithAdapter(0xc00042e100, 0xc00010e660, 0x5c, 0x7fce8af15340, 0x0, 0x7fce8aeff700, 0x8)
/home/eric/go/pkg/mod/github.com/casbin/casbin/[email protected]/enforcer.go:146 +0x7b
github.com/casbin/casbin/v2.NewEnforcer(0xc00017df58, 0x2, 0x2, 0x99e79c, 0x4, 0x9a1072)
/home/eric/go/pkg/mod/github.com/casbin/casbin/[email protected]/enforcer.go:95 +0x36b

But according to gorm postgres doc, it's valid dsn syntax.

BTW, since this issue is migrated from another, it already got some useful comment:
#95 (comment)

[QUESTION] - How Would I make queries for different scenarios

I've been using this adapter on Postgres. Curently I'm stuck on getting some information from Casbin. Please help me understand how could I query to get those information.

I'm trying to look for

  1. If the domain is *, get all users associated to all domains with their respective roles
  2. get all users associated to a domain with their respective roles

So I have basically added three roles: admin, account-admin, and user
admin => with all powers
account-admin => with all powers for account (domain)
user => normal users

And Admin would see all users irrespective of domains, Account Admin would see all users associated with the domain.

Currently I needed to make custom queries to fetch such information. Any help would be highly appreciated.

In SavePolicy, what happens if saving table is unsuccessful after dropping?

It has never happened to me but I'm asking just in case.

func (a *Adapter) SavePolicy(model model.Model) error {
	err := a.dropTable()
	if err != nil {
		return err
	}
	err = a.createTable()
	if err != nil {
		return err
	}

	for ptype, ast := range model["p"] {
		for _, rule := range ast.Policy {
			line := a.savePolicyLine(ptype, rule)
			err := a.db.Create(&line).Error
			if err != nil {
				return err
			}
		}
	}

	for ptype, ast := range model["g"] {
		for _, rule := range ast.Policy {
			line := a.savePolicyLine(ptype, rule)
			err := a.db.Create(&line).Error
			if err != nil {
				return err
			}
		}
	}

	return nil
}

Environment Variables for DB creation

Following issue #40, there should be the out-of-the-box possibility for the user to define environment variables which should be used for DB creation.

For example, in the CaaS project, I manually added a string parser to substitute keywords starting with $ in the config file with the corresponding environment variables.

I'm not sure whether that's something that should be implemented here or directly in CaaS, but definitely necessary for production-grade deployment.

sqlite3 can run well in windows,but not in linux

I use V3.02
for sqlite I edit adapter
detail

import "gorm.io/driver/sqlite"

func openDBConnection(driverName, dataSourceName string) (*gorm.DB, error) {
	var err error
	var db *gorm.DB
	if driverName == "postgres" {
		db, err = gorm.Open(postgres.Open(dataSourceName+" dbname=postgres"), &gorm.Config{})
	} else if driverName == "mysql" {
		db, err = gorm.Open(mysql.Open(dataSourceName), &gorm.Config{})
	} else if driverName == "sqlite3" {
		db, err = gorm.Open(sqlite.Open(dataSourceName), &gorm.Config{})
	} else if driverName == "sqlserver" {
		db, err = gorm.Open(sqlserver.Open(dataSourceName), &gorm.Config{})
	} else {
		return nil, errors.New("database dialect is not supported")
	}
	if err != nil {
		return nil, err
	}
	return db, err
}

func Casbin() *casbin.Enforcer {
 	a, _ := gormadapter.NewAdapter("sqlite3", "db.db", true)
 	e, _ := casbin.NewEnforcer("rbac_model.conf", a)

	e.AddFunction("ParamsMatch", ParamsMatchFunc)
	_ = e.LoadPolicy()
	return e
}

Error:

NewEnforcer: err := e.InitWithAdapter(p0, p1.(persist.Adapter))
/home/zbl/server/service/sys_casbin.go:97 (0xea6a84)
	Casbin: e, _ := casbin.NewEnforcer("./rbac_model.conf", a)
/home/zbl/server/middleware/casbin_rbac.go:22 (0xeb2624)
	CasbinHandler.func1: e := service.Casbin()

unknown field 'WithConditions' in struct literal of type gorm.Session

Hi,

I'm attempting to import your adaptor into my project, however I am getting the following message:

/home/tim/go/pkg/mod/github.com/casbin/gorm-adapter/[email protected]/adapter.go:247:25: unknown field 'WithConditions' in struct literal of type gorm.Session

Do you know what the issue might be?

Edit: You may notice I closed, then reopened, I immediately thought that it was related to the wrong version of gorm installed. However upon further testing it still occurs as the gorm.Session does not appear to have WithConditions, wondering if they may have been a recent update in gorm?

Using casbin in SQL-Query

Is there a way to use casbin policy checking in a WHERE part of SQL-query? For example, when selecting a list of entries.

Column size

Hi, I'm migrating to new gormadapter, And it seems that the column size was lowered to 40 from the original 100. I was wondering if it would be possible to bump up the size back to 100?

(As I have problems now when I'm migrating it 'cause of the size differences.)

custom column size support

Hi, I was wondering if there are any plans to support custom column sizes? I've reached a use-case where the 100 column size limit is not sufficient.

I noticed there was an Issue opened about this #56, however, the solution wouldn't work for me, as I'm using cockroach and get this error

ALTER TABLE "casbin_rule" ALTER COLUMN "v0" TYPE varchar(100);
ERROR: unimplemented: type conversion not yet implemented
SQLSTATE: 0A000
HINT: You have attempted to use a feature that is not yet implemented.
See: https://github.com/cockroachdb/cockroach/issues/9851

One solution (somewhat hacky though) that could work is, that we could pass a custom CasbinRule table in the DB context and used that instead of the default CasbinRule, example, and when creating the table we could just use the custom one

What do you think about this ?

Compatible with sqlite3

I create new adapter.

gormadapter.NewAdapter("sqlite3", "assets/database.db")

After i get panic near "DATABASE": syntax error. I think it's happened because connection string connect to database and not server.
I change

} else {

to if a.driverName != "sqlite3" and all is worked.

[Question] Customizing casbin_rule table name

What's your scenario? What do you want to achieve?
We are working on a cloud based offering and planning to use casbin.
In that we would like to segregate tenant's data and for that we would like to create separate casbin_rules tables for each tenant.
I know that we have the provision for seperate databases and that we can pass in the connection string
But we don't want to have that many databases.

So our requirement is that instead of the default table name casbin_rule how can we have that table name customized to something like tenant1_casbin_rule, tenant1_casbin_rule... tenantn_casbin_rule

mysql 创建的数据库的表名是casbin_rules

使用github.com/casbin/gorm-adapter/v3 v3.0.3 的时候 ,

if !db.Migrator().HasTable("casbin_rule") { err = db.Migrator().CreateTable(&gormadapter.CasbinRule{}) }
mysql 创建的数据库的表名是casbin_rules ,应该是 casbin_rule 才能正常使用

I got an err when I Save Policy

(Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CHARSET=utf8' at line 1) 
[2019-03-29 21:53:15]  
panic: Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CHARSET=utf8' at line 1

goroutine 1 [running]:
TongXingChuangYe/Spiders/vendor/github.com/casbin/gorm-adapter.(*Adapter).dropTable(...)
	/Users/c/go/src/TongXingChuangYe/Spiders/vendor/github.com/casbin/gorm-adapter/adapter.go:165
TongXingChuangYe/Spiders/vendor/github.com/casbin/gorm-adapter.(*Adapter).SavePolicy(0xc0002ae990, 0xc0002ae570, 0xc0002ae990, 0x0)
	/Users/c/go/src/TongXingChuangYe/Spiders/vendor/github.com/casbin/gorm-adapter/adapter.go:236 +0x756
TongXingChuangYe/Spiders/vendor/github.com/casbin/casbin.(*Enforcer).SavePolicy(0xc0003661c0, 0x4586d03, 0x1)

How to set custom column size?

Hello,

First of all, thank you for this project, it's very useful.

I'm using casbin with a RESTful model, i.e. the list of permissions for a given roles are strored in 1 record in the dabatase (vs 1 record per permissions/role as usualy) :

Instead of this :
p, data2_admin, data2, read p, data2_admin, data2, write

I'm using this :
p, data2_admin, data2, (read)|(write)

The problem is that my casbin gorm adapter defines the column size without any option to adapt it as per end user needs :

V0    string `gorm:"size:40;uniqueIndex:unique_index"`
V1    string `gorm:"size:40;uniqueIndex:unique_index"`
V2    string `gorm:"size:40;uniqueIndex:unique_index"`
V3    string `gorm:"size:40;uniqueIndex:unique_index"`
V4    string `gorm:"size:40;uniqueIndex:unique_index"`
V5    string `gorm:"size:40;uniqueIndex:unique_index"`

Is there something that drives this decision or can we imagine to change that?

Thanks

looking for newer release of gorm-adapter

Would it be possible to bump the version and perform a new release? I'd like to use NewAdapterByDBUsePrefix() but this isn't present in the current v2 release.

If I can help somehow please let me know.

[Question] Logging all SQL Queries

We are using casbin-gorm-adapter for our policies storage to DB
I would like to log all the queries that are fired to the DB.
How can I do that?

Previously when using the pg-adapter I was suggested to use the go-pg query hook for this purpose at casbin/casbin-pg-adapter#20 (comment)

I am looking for something similar in gorm-adapter

Note : We are using AWS EDS, so configuring Postgres to log statements to stdout isn't an option

[BUG] Error while creating enforcer if "gorm.io/gorm v1.21.3" present in go.mod

If the dependencies contain "gorm.io/gorm v1.21.3" then the following program gives error as follows

package main

import (
	"fmt"
	"github.com/casbin/casbin/v2"
	pgAdapter "github.com/casbin/gorm-adapter/v3"
)

const DBHost = "SomeHost"
const DBUser = "SomeUser"
const DBName = "SomeDB"
const DBPassword = "SomePw"

func main() {

	dsn := fmt.Sprintf("host=%v port=5432 user=%v dbname=%v password=%v sslmode=allow", DBHost, DBUser, DBName, DBPassword)
	adapter1, _ := pgAdapter.NewFilteredAdapter("postgres", dsn, DBName, "casbin_rule_snowe", true)

	enforcer, _ := casbin.NewEnforcer()
	enforcer.InitWithAdapter("model.conf", adapter1)
}

Error is as follows

2021/04/23 09:22:11 C:/Users/sinarn/go/pkg/mod/github.com/casbin/gorm-adapter/[email protected]/adapter.go:321 ERROR: relation "idx_casbin_rule_snowe" already exists (SQLSTATE 42P07)
[249.612ms] [rows:0] CREATE UNIQUE INDEX idx_casbin_rule_snowe ON casbin_rule_snowe (ptype,v0,v1,v2,v3,v4,v5)
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x60 pc=0xe66285]

goroutine 1 [running]:
github.com/casbin/gorm-adapter/v3.(*Adapter).IsFiltered(0x0, 0xfe2960)
        C:/Users/sinarn/go/pkg/mod/github.com/casbin/gorm-adapter/[email protected]/adapter.go:396 +0x5
github.com/casbin/casbin/v2.(*Enforcer).InitWithModelAndAdapter(0xc000416580, 0xc000415080, 0xfe2960, 0x0, 0x0, 0xc000408948)
        C:/Users/sinarn/go/pkg/mod/github.com/casbin/casbin/[email protected]/enforcer.go:168 +0x144
github.com/casbin/casbin/v2.(*Enforcer).InitWithAdapter(0xc000416580, 0xf40b7d, 0xa, 0xfe2960, 0x0, 0x0, 0x3)
        C:/Users/sinarn/go/pkg/mod/github.com/casbin/casbin/[email protected]/enforcer.go:146 +0x85
main.main()
        C:/TNG/_GO/mkt-infra-iam/Source/main_jdbc_query_filtered_TEMP_gorm.go:20 +0x1eb
exit status 2

The moment "gorm.io/gorm v1.21.3" is removed from go.mod it starts working fine.
We need "gorm.io/gorm v1.21.3" for other modules in the system, so removing that is not an option for us

gorm-adapter/v3与casbin/v2不兼容吗?

测试代码如下:

import (
	"log"
	"os"
        "testing"
	"time"

	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

func TestC() {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      false,       // 禁用彩色打印
		},
	)
	db, err := gorm.Open(mysql.Open("root:root@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local"),
		&gorm.Config{
			Logger: newLogger,
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true, // 表名单数
				TablePrefix:   "",   // 表前缀
			},
		})
	if err != nil {
		println("数据库连接失败!")
	}
	// con1()
	con2(db)
	db.Debug()
	println("hello")
}
// 使用已有DB连接
func con2(db *gorm.DB) {
	a, err := gormadapter.NewAdapterByDB(db)
	if err != nil {
		println(err)
	}
	e, err := casbin.NewEnforcer("./rbac_model.toml", a)
	if err != nil {
		println(err)
	}
	e.LoadPolicy()
	// e.AddRoleForUser("tom", "admin")
	println(e.GetAdapter())

}

运行时,报e, err := casbin.NewEnforcer("./rbac_model.toml", a)这行错误:

invalid memory address or nil pointer dereference

debug发现:
ennforcer.go文件85行err := e.InitWithAdapter(p0, p1.(persist.Adapter))

interface conversion: interface {} is *github.com/casbin/gorm-adapter/v3.Adapter, not github.com/casbin/casbin/v2/persist.Adapter


学这个时候,gorm升级了v2,casbin也有v2了,人都整傻了

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.