casbin / gorm-adapter

GORM adapter for Casbin, see extended version of GORM Adapter Ex at: https://github.com/casbin/gorm-adapter-ex
https://github.com/casbin/casbin
Apache License 2.0
678 stars 206 forks source link

How to setup a casbin watcher along with the the Gorm adapter #215

Closed umairrsyedd closed 1 year ago

casbin-bot commented 1 year ago

@tangyang9464 @JalinWang @imp2002

hsluoyz commented 1 year ago

@PokIsemaine

umairrsyedd commented 1 year ago

Any updates on this @PokIsemaine ?

PokIsemaine commented 1 year ago

@umairrsyedd

package main

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

type SampleWatcher struct {
    callback func(string)
}

func myCallBack(s string) {
    fmt.Println(s)
}
func (w *SampleWatcher) Close() {
}

func (w *SampleWatcher) SetUpdateCallback(callback func(string)) error {
    w.callback = callback
    return nil
}

func (w *SampleWatcher) Update() error {
    if w.callback != nil {
        fmt.Println("watcher Update")
        w.callback("myCallBack")
    }
    return nil
}

func main() {
    a, _ := gormadapter.NewAdapter("mysql", "root:root@tcp(127.0.0.1:3307)/") // Your driver and data source.
    e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a)

    //e, _ := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv")

    sampleWatcher := &SampleWatcher{}
    _ = e.SetWatcher(sampleWatcher)
    _ = sampleWatcher.SetUpdateCallback(myCallBack)
    e.EnableAutoNotifyWatcher(true)

    _ = e.SavePolicy() //calls watcher.Update()
}