Initial commit

This commit is contained in:
yan.y
2024-03-27 23:25:08 +08:00
commit 0884384e91
127 changed files with 9353 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
package casbin
import (
"fmt"
"path/filepath"
"pet-house.com/core/g"
"pet-house.com/core/helper/dir"
)
// Remove del config file
func Remove() error {
casbinPath := getCasbinPath()
if dir.IsExist(casbinPath) && dir.IsFile(casbinPath) {
return dir.Remove(casbinPath)
}
return nil
}
func getCasbinPath() string {
return filepath.Join(dir.GetCurrentAbPath(), g.CasbinFileName)
}
// init initialize config file
// - initialize casbin's config file as rbac_model.conf name
func init() {
casbinPath := getCasbinPath()
fmt.Printf("casbin rbac_model.conf's path: %s\n\n", casbinPath)
if !dir.IsExist(casbinPath) { // casbin rbac_model.conf file
var rbacModelConf = []byte(`[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch2(r.obj, p.obj) && (r.act == p.act || p.act == "*")`)
_, err := dir.WriteBytes(casbinPath, rbacModelConf)
if err != nil {
panic(fmt.Errorf("initialize casbin rbac_model.conf file return error: %w ", err))
}
}
}
+29
View File
@@ -0,0 +1,29 @@
package casbin
import (
"testing"
"pet-house.com/core/helper/dir"
)
func TestRemove(t *testing.T) {
t.Run("Test casbin instance", func(t *testing.T) {
casbin := Instance()
if casbin == nil {
t.Error("casbin instance is nil")
}
})
casbinPath := getCasbinPath()
if !dir.IsExist(casbinPath) || !dir.IsFile(casbinPath) {
t.Error("casbin file is not exist")
}
t.Run("Test casbin config remove", func(t *testing.T) {
err := Remove()
if err != nil {
t.Error(err)
}
})
if dir.IsExist(casbinPath) && dir.IsFile(casbinPath) {
t.Error("casbin file is delete fail")
}
}
+75
View File
@@ -0,0 +1,75 @@
package casbin
import (
"path/filepath"
"strconv"
"sync"
"github.com/casbin/casbin/v2"
gormadapter "github.com/casbin/gorm-adapter/v3"
"pet-house.com/core/g"
"pet-house.com/core/helper/dir"
"pet-house.com/core/server/database"
"pet-house.com/core/server/zap_server"
)
var (
once sync.Once
enforcer *casbin.Enforcer
)
// Instance casbin instance
func Instance() *casbin.Enforcer {
once.Do(func() {
enforcer = getEnforcer()
})
return enforcer
}
// getEnforcer get casbin.Enforcer
func getEnforcer() *casbin.Enforcer {
if database.Instance() == nil {
zap_server.ZAPLOG.Error(database.ErrDatabaseInit.Error())
return nil
}
c, err := gormadapter.NewAdapterByDBUseTableName(database.Instance(), "", "casbin_rule") // Your driver and data source.
if err != nil {
return nil
}
enforcer, err := casbin.NewEnforcer(filepath.Join(dir.GetCurrentAbPath(), g.CasbinFileName), c)
if err != nil {
return nil
}
if enforcer == nil {
zap_server.ZAPLOG.Error("Casbin init")
return nil
}
err = enforcer.LoadPolicy()
if err != nil {
return nil
}
return enforcer
}
// GetRolesForUser get user's roles
func GetRolesForUser(uid uint) []string {
uids, err := Instance().GetRolesForUser(strconv.FormatUint(uint64(uid), 10))
if err != nil {
return []string{}
}
return uids
}
// ClearCasbin clean rules
func ClearCasbin(v int, p ...string) error {
_, err := Instance().RemoveFilteredPolicy(v, p...)
if err != nil {
return err
}
return nil
}
+37
View File
@@ -0,0 +1,37 @@
package casbin
import (
"strconv"
"testing"
)
func TestInstance(t *testing.T) {
t.Run("test casbin instance", func(t *testing.T) {
casbin := Instance()
if casbin == nil {
t.Error("casbin instance is nil")
}
})
}
func TestGetRolesForUser(t *testing.T) {
userId := "888"
roleId := "2"
_, err := Instance().AddRoleForUser(userId, roleId)
if err != nil {
t.Errorf("add role for user get %v", err.Error())
}
userUid, err := strconv.ParseUint(userId, 10, 64)
if err != nil {
t.Errorf("parse uint err %v", err.Error())
}
t.Run("test casbin get enforcer", func(t *testing.T) {
uids := GetRolesForUser(uint(userUid))
if len(uids) != 1 {
t.Errorf("get role for user want %+v but get %+v", userId, uids)
}
if uids[0] != roleId {
t.Errorf("get role for user want %s but get %s", roleId, uids[0])
}
})
}
+41
View File
@@ -0,0 +1,41 @@
package casbin
import (
_ "embed"
"os"
"testing"
"github.com/bwmarrin/snowflake"
"pet-house.com/core/g"
"pet-house.com/core/helper/str"
"pet-house.com/core/server/database"
"pet-house.com/core/server/zap_server"
)
func TestMain(m *testing.M) {
node, _ := snowflake.NewNode(1)
uuid := str.Join("casbin", "_", node.Generate().String())
database.CONFIG.DbName = uuid
database.CONFIG.Path = g.TestMysqlAddr
database.CONFIG.Password = g.TestMysqlPwd
Instance()
code := m.Run()
err := database.DorpDB(database.CONFIG.BaseDsn(), "mysql", uuid)
if err != nil {
zap_server.ZAPLOG.Error(err.Error())
}
db, _ := database.Instance().DB()
if db != nil {
db.Close()
}
Remove()
zap_server.Remove()
database.Remove()
os.Exit(code)
}