123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- package service
- import (
- "errors"
- "gin-vue-admin/global"
- "gin-vue-admin/model"
- "gin-vue-admin/model/request"
- "github.com/casbin/casbin"
- "github.com/casbin/casbin/util"
- gormadapter "github.com/casbin/gorm-adapter"
- "strings"
- )
- func UpdateCasbin(authorityId string, casbinInfos []request.CasbinInfo) error {
- ClearCasbin(0, authorityId)
- for _, v := range casbinInfos {
- cm := model.CasbinModel{
- ID: 0,
- Ptype: "p",
- AuthorityId: authorityId,
- Path: v.Path,
- Method: v.Method,
- }
- addflag := AddCasbin(cm)
- if addflag == false {
- return errors.New("存在相同api,添加失败,请联系管理员")
- }
- }
- return nil
- }
- func AddCasbin(cm model.CasbinModel) bool {
- e := Casbin()
- return e.AddPolicy(cm.AuthorityId, cm.Path, cm.Method)
- }
- func UpdateCasbinApi(oldPath string, newPath string, oldMethod string, newMethod string) error {
- var cs []model.CasbinModel
- err := global.GVA_DB.Table("casbin_rule").Where("v1 = ? AND v2 = ?", oldPath, oldMethod).Find(&cs).Updates(map[string]string{
- "v1": newPath,
- "v2": newMethod,
- }).Error
- return err
- }
- func GetPolicyPathByAuthorityId(authorityId string) (pathMaps []request.CasbinInfo) {
- e := Casbin()
- list := e.GetFilteredPolicy(0, authorityId)
- for _, v := range list {
- pathMaps = append(pathMaps, request.CasbinInfo{
- Path: v[1],
- Method: v[2],
- })
- }
- return pathMaps
- }
- func ClearCasbin(v int, p ...string) bool {
- e := Casbin()
- return e.RemoveFilteredPolicy(v, p...)
- }
- func Casbin() *casbin.Enforcer {
- a := gormadapter.NewAdapterByDB(global.GVA_DB)
- e := casbin.NewEnforcer(global.GVA_CONFIG.Casbin.ModelPath, a)
- e.AddFunction("ParamsMatch", ParamsMatchFunc)
- _ = e.LoadPolicy()
- return e
- }
- func ParamsMatch(fullNameKey1 string, key2 string) bool {
- key1 := strings.Split(fullNameKey1, "?")[0]
-
- return util.KeyMatch2(key1, key2)
- }
- func ParamsMatchFunc(args ...interface{}) (interface{}, error) {
- name1 := args[0].(string)
- name2 := args[1].(string)
- return ParamsMatch(name1, name2), nil
- }
|