You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.3 KiB

  1. package sysModel
  2. import (
  3. "errors"
  4. "gin-vue-admin/config"
  5. "gin-vue-admin/init/qmsql"
  6. "github.com/casbin/casbin"
  7. gormadapter "github.com/casbin/gorm-adapter"
  8. "strings"
  9. )
  10. type CasbinModel struct {
  11. ID uint `json:"id" gorm:"column:_id"`
  12. Ptype string `json:"ptype" gorm:"column:ptype"`
  13. AuthorityId string `json:"rolename" gorm:"column:v0"`
  14. Path string `json:"path" gorm:"column:v1"`
  15. Method string `json:"method" gorm:"column:v2"`
  16. }
  17. // 更新权限
  18. func (c *CasbinModel) CasbinPUpdata(AuthorityId string, Paths []string) error {
  19. c.clearCasbin(0, AuthorityId)
  20. for _, v := range Paths {
  21. cm := CasbinModel{
  22. ID: 0,
  23. Ptype: "p",
  24. AuthorityId: AuthorityId,
  25. Path: v,
  26. Method: "POST",
  27. }
  28. addflag := c.AddCasbin(cm)
  29. if addflag == false {
  30. return errors.New("存在相同api,添加失败,请联系管理员")
  31. }
  32. }
  33. return nil
  34. }
  35. // API更新随动
  36. func (c *CasbinModel) CasbinApiUpdata(oldPath string, newPath string) error {
  37. var cs []CasbinModel
  38. err := qmsql.DEFAULTDB.Table("casbin_rule").Where("v1 = ?", oldPath).Find(&cs).Update("v1", newPath).Error
  39. return err
  40. }
  41. //添加权限
  42. func (c *CasbinModel) AddCasbin(cm CasbinModel) bool {
  43. e := Casbin()
  44. return e.AddPolicy(cm.AuthorityId, cm.Path, cm.Method)
  45. }
  46. //获取权限列表
  47. func (c *CasbinModel) GetPolicyPathByAuthorityId(AuthorityId string) []string {
  48. e := Casbin()
  49. var pathList []string
  50. list := e.GetFilteredPolicy(0, AuthorityId)
  51. for _, v := range list {
  52. pathList = append(pathList, v[1])
  53. }
  54. return pathList
  55. }
  56. //清除匹配的权限
  57. func (c *CasbinModel) clearCasbin(v int, p string) bool {
  58. e := Casbin()
  59. return e.RemoveFilteredPolicy(v, p)
  60. }
  61. // 自定义规则函数
  62. func ParamsMatch(key1 string, key2 string) bool {
  63. k1arr := strings.Split(key1, "?")
  64. return k1arr[0] == key2
  65. }
  66. // 自定义规则函数
  67. func ParamsMatchFunc(args ...interface{}) (interface{}, error) {
  68. name1 := args[0].(string)
  69. name2 := args[1].(string)
  70. return (bool)(ParamsMatch(name1, name2)), nil
  71. }
  72. //持久化到数据库 引入自定义规则
  73. func Casbin() *casbin.Enforcer {
  74. a := gormadapter.NewAdapterByDB(qmsql.DEFAULTDB)
  75. e := casbin.NewEnforcer(config.GinVueAdminconfig.CasbinConfig.ModelPath, a)
  76. e.AddFunction("ParamsMatch", ParamsMatchFunc)
  77. e.LoadPolicy()
  78. return e
  79. }