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.

103 lines
2.5 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. type CasbinInfo struct {
  19. Path string `json:"path"`
  20. Method string `json:"method"`
  21. }
  22. // 供入参使用
  23. type CasbinInReceive struct {
  24. AuthorityId string `json:"authorityId"`
  25. CasbinInfos []CasbinInfo `json:"casbinInfos"`
  26. }
  27. // 更新权限
  28. func (c *CasbinModel) CasbinPUpdata(AuthorityId string, casbinInfos []CasbinInfo) error {
  29. c.clearCasbin(0, AuthorityId)
  30. for _, v := range casbinInfos {
  31. cm := CasbinModel{
  32. ID: 0,
  33. Ptype: "p",
  34. AuthorityId: AuthorityId,
  35. Path: v.Path,
  36. Method: v.Method,
  37. }
  38. addflag := c.AddCasbin(cm)
  39. if addflag == false {
  40. return errors.New("存在相同api,添加失败,请联系管理员")
  41. }
  42. }
  43. return nil
  44. }
  45. // API更新随动
  46. func (c *CasbinModel) CasbinApiUpdata(oldPath string, newPath string) error {
  47. var cs []CasbinModel
  48. err := qmsql.DEFAULTDB.Table("casbin_rule").Where("v1 = ?", oldPath).Find(&cs).Update("v1", newPath).Error
  49. return err
  50. }
  51. //添加权限
  52. func (c *CasbinModel) AddCasbin(cm CasbinModel) bool {
  53. e := Casbin()
  54. return e.AddPolicy(cm.AuthorityId, cm.Path, cm.Method)
  55. }
  56. //获取权限列表
  57. func (c *CasbinModel) GetPolicyPathByAuthorityId(AuthorityId string) []string {
  58. e := Casbin()
  59. var pathList []string
  60. list := e.GetFilteredPolicy(0, AuthorityId)
  61. for _, v := range list {
  62. pathList = append(pathList, v[1])
  63. }
  64. return pathList
  65. }
  66. //清除匹配的权限
  67. func (c *CasbinModel) clearCasbin(v int, p string) bool {
  68. e := Casbin()
  69. return e.RemoveFilteredPolicy(v, p)
  70. }
  71. // 自定义规则函数
  72. func ParamsMatch(key1 string, key2 string) bool {
  73. k1arr := strings.Split(key1, "?")
  74. return k1arr[0] == key2
  75. }
  76. // 自定义规则函数
  77. func ParamsMatchFunc(args ...interface{}) (interface{}, error) {
  78. name1 := args[0].(string)
  79. name2 := args[1].(string)
  80. return (bool)(ParamsMatch(name1, name2)), nil
  81. }
  82. //持久化到数据库 引入自定义规则
  83. func Casbin() *casbin.Enforcer {
  84. a := gormadapter.NewAdapterByDB(qmsql.DEFAULTDB)
  85. e := casbin.NewEnforcer(config.GinVueAdminconfig.CasbinConfig.ModelPath, a)
  86. e.AddFunction("ParamsMatch", ParamsMatchFunc)
  87. e.LoadPolicy()
  88. return e
  89. }