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.

92 lines
2.2 KiB

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