Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

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

License

NotificationsYou must be signed in to change notification settings

casbin/gorm-adapter

Repository files navigation

In v3.0.3, methodNewAdapterByDB creates table namedcasbin_rules,
we fix it tocasbin_rule after that.
If you used v3.0.3 and less, and you want to update it,
you might need tomigrate data manually.Find out more at:#78

Go Report CardGoCoverage StatusGodocReleaseDiscordSourcegraph

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

Based onOfficially Supported Databases, The current supported databases are:

  • MySQL
  • PostgreSQL
  • SQL Server
  • Sqlite3

gorm-adapter usegithub.com/glebarez/sqlite instead of gorm official sqlite drivergorm.io/driver/sqlite because the latter needscgo 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 mainimport ("github.com/casbin/casbin/v2"gormadapter"github.com/casbin/gorm-adapter/v3"_"github.com/go-sql-driver/mysql")funcmain() {// 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 useAutoMigrate by default for create table, if you want to turn it off, please use APITurnOffAutoMigrate(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 atgorm-adapter#162

Customize table columns example

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

package mainimport ("github.com/casbin/casbin/v2"gormadapter"github.com/casbin/gorm-adapter/v3""gorm.io/gorm")funcmain() {// Increase the column size to 512.typeCasbinRulestruct {IDuint`gorm:"primaryKey;autoIncrement"`Ptypestring`gorm:"size:512;uniqueIndex:unique_index"`V0string`gorm:"size:512;uniqueIndex:unique_index"`V1string`gorm:"size:512;uniqueIndex:unique_index"`V2string`gorm:"size:512;uniqueIndex:unique_index"`V3string`gorm:"size:512;uniqueIndex:unique_index"`V4string`gorm:"size:512;uniqueIndex:unique_index"`V5string`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 mainfuncmain() {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")iferr!=nil {returnerr}_,err=e.AddPolicy("jack","data2","write")iferr!=nil {returnerr}returnnil})iferr!=nil {// handle if transaction failedreturn}}

ConditionsToGormQuery

ConditionsToGormQuery() is a function that converts multiple query conditions into a GORM query statementYou can use theGetAllowedObjectConditions() API of Casbin to get conditions,and choose the way of combining conditions throughcombineType.

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

Example: GetAllowedRecordsForUser

DataBase example:

idtitleauthorpublisherpublish_datapricecategory_id
1book1author1publisher12023-04-09 16:23:42101
2book2author1publisher12023-04-09 16:23:44202
3book3author2publisher12023-04-09 16:23:44301
4book4author2publisher22023-04-09 16:23:45103
5book5author3publisher22023-04-09 16:23:45501
6book6author3publisher22023-04-09 16:23:46602
typeBookstruct {IDintTitlestringAuthorstringPublisherstringPublishDate time.TimePricefloat64CategoryIDint}funcTestGetAllowedRecordsForUser(t*testing.T) {e,_:=casbin.NewEnforcer("examples/object_conditions_model.conf","examples/object_conditions_policy.csv")conditions,err:=e.GetAllowedObjectConditions("alice","read","r.obj.")iferr!=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{})iferr!=nil {panic(err)}fmt.Println("CombineTypeOr")rows,err:=ConditionsToGormQuery(db,conditions,CombineTypeOr).Model(&Book{}).Rows()deferrows.Close()varbBookforrows.Next() {err:=db.ScanRows(rows,&b)iferr!=nil {panic(err)}log.Println(b)}fmt.Println("CombineTypeAnd")rows,err=ConditionsToGormQuery(db,conditions,CombineTypeAnd).Model(&Book{}).Rows()deferrows.Close()forrows.Next() {err:=db.ScanRows(rows,&b)iferr!=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 300sctx,cancel:=context.WithTimeout(context.Background(),300*time.Microsecond)defercancel()err:=a.AddPolicyCtx(ctx,"p","p", []string{"alice","data1","read"})iferr!=nil {panic(err)}

Getting Help

License

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


[8]ページ先頭

©2009-2025 Movatter.jp