authz.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package rbac
  2. import (
  3. "fmt"
  4. "git.bvbej.com/bvbej/base-golang/pkg/rbac/model"
  5. "github.com/casbin/casbin/v2"
  6. casbinModel "github.com/casbin/casbin/v2/model"
  7. gormAdapter "github.com/casbin/gorm-adapter/v3"
  8. "github.com/gin-gonic/gin"
  9. "go.uber.org/zap"
  10. "gorm.io/gorm"
  11. "net/http"
  12. )
  13. var _ Auth = (*auth)(nil)
  14. type Auth interface {
  15. AddRole(role, describe string) error
  16. DeleteRole(role string) (bool, error)
  17. AddRoleForUser(user, role string) (bool, error)
  18. UpdateRoleForUser(user, role string) (bool, error)
  19. UpdateRolePermission(role string, permissionIDs []uint64) (bool, error)
  20. CreatePermission(info gin.RoutesInfo)
  21. UpdatePermission(id uint64, url, description string) error
  22. CheckPermission(user string, r *http.Request) bool
  23. }
  24. type auth struct {
  25. db *gorm.DB
  26. enforcer *casbin.Enforcer
  27. logger *zap.Logger
  28. }
  29. func NewRBAC(db *gorm.DB, logger *zap.Logger) (Auth, error) {
  30. rule := new(model.RbacRules)
  31. gormAdapter.TurnOffAutoMigrate(db)
  32. t, err := gormAdapter.NewAdapterByDBWithCustomTable(db, rule, rule.TableName())
  33. if err != nil {
  34. return nil, err
  35. }
  36. m, err := casbinModel.NewModelFromString(`
  37. [request_definition]
  38. r = sub, obj, act
  39. [policy_definition]
  40. p = sub, obj, act
  41. [role_definition]
  42. g = _, _
  43. [policy_effect]
  44. e = some(where (p.eft == allow))
  45. [matchers]
  46. m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*") || r.sub == "admin"
  47. `)
  48. if err != nil {
  49. return nil, err
  50. }
  51. enforcer, err := casbin.NewEnforcer(m, t)
  52. if err != nil {
  53. return nil, err
  54. }
  55. return &auth{
  56. db: db,
  57. enforcer: enforcer,
  58. logger: logger,
  59. }, nil
  60. }
  61. func (a *auth) AddRole(role, describe string) error {
  62. if a.db.Where("name = ?", role).First(&model.RbacRoles{}).RowsAffected > 0 {
  63. return fmt.Errorf("角色已存在")
  64. }
  65. return a.db.Create(&model.RbacRoles{
  66. Name: role,
  67. Describe: describe,
  68. }).Error
  69. }
  70. func (a *auth) DeleteRole(role string) (bool, error) {
  71. err := a.db.Where("name = ?", role).Delete(&model.RbacRoles{}).Error
  72. if err != nil {
  73. return false, err
  74. }
  75. return a.enforcer.DeleteRole(role)
  76. }
  77. func (a *auth) AddRoleForUser(user, role string) (bool, error) {
  78. return a.enforcer.AddRoleForUser(user, role)
  79. }
  80. func (a *auth) UpdateRoleForUser(user, role string) (bool, error) {
  81. oldRole, err := a.enforcer.GetRolesForUser(user)
  82. if err != nil && len(oldRole) > 0 {
  83. return false, err
  84. }
  85. oldRule := []string{user, oldRole[0]}
  86. newRule := []string{user, role}
  87. return a.enforcer.UpdateGroupingPolicy(oldRule, newRule)
  88. }
  89. func (a *auth) UpdateRolePermission(role string, permissionIDs []uint64) (bool, error) {
  90. ok, err := a.enforcer.DeletePermissionsForUser(role)
  91. if err != nil {
  92. return ok, err
  93. }
  94. var rbacPermissions []model.RbacPermissions
  95. a.db.Where("id IN ?", permissionIDs).Find(&rbacPermissions)
  96. if len(rbacPermissions) > 0 {
  97. var permissions [][]string
  98. for _, permission := range rbacPermissions {
  99. permissions = append(permissions, []string{permission.Path, permission.Method})
  100. }
  101. return a.enforcer.AddPermissionsForUser(role, permissions...)
  102. }
  103. return false, fmt.Errorf("未找到需要添加的权限")
  104. }
  105. func (a *auth) CreatePermission(info gin.RoutesInfo) {
  106. for _, routeInfo := range info {
  107. a.db.Where("method = ? AND path = ?", routeInfo.Method, routeInfo.Path).
  108. FirstOrCreate(&model.RbacPermissions{
  109. Method: routeInfo.Method,
  110. Path: routeInfo.Path,
  111. })
  112. }
  113. }
  114. func (a *auth) UpdatePermission(id uint64, url, description string) error {
  115. return a.db.Where("id = ?", id).Updates(map[string]any{
  116. "url": url,
  117. "description": description,
  118. }).Error
  119. }
  120. func (a *auth) CheckPermission(user string, r *http.Request) bool {
  121. path := r.URL.Path
  122. method := r.Method
  123. allowed, err := a.enforcer.Enforce(user, path, method)
  124. if err != nil {
  125. a.logger.Sugar().Errorf("Enforce err [%s]", err)
  126. return false
  127. }
  128. return allowed
  129. }