perm.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package perm
  2. import (
  3. "exam_system/dao"
  4. "exam_system/entity"
  5. result "exam_system/result"
  6. "exam_system/vo"
  7. "net/http"
  8. "regexp"
  9. "strings"
  10. "github.com/gin-gonic/gin"
  11. )
  12. func Perm() gin.HandlerFunc {
  13. return func(c *gin.Context) {
  14. if strings.HasPrefix(c.Request.RequestURI, "/auth") {
  15. c.Next()
  16. return
  17. }
  18. id := c.GetInt("id")
  19. if id == 0 {
  20. c.JSON(http.StatusForbidden, result.NO_PERMISSION)
  21. c.Abort()
  22. return
  23. }
  24. // 查user
  25. res := dao.FindUserbyId(id)
  26. if res.Data == nil {
  27. c.JSON(http.StatusForbidden, result.USER_IS_NOT_EXISTED)
  28. c.Abort()
  29. return
  30. }
  31. userVo := res.Data.(vo.UserVo)
  32. // TODO 后续role和perm可以保存到redis里面
  33. // 查role列表
  34. roles := dao.FindRoleByUserId(userVo.ID)
  35. roleIds := make([]int, len(roles))
  36. for i, v := range roles {
  37. roleIds[i] = v.Id
  38. }
  39. // 查perm列表
  40. res = dao.FindPermByRoles(roleIds)
  41. if res.Code != result.SUCCESS.Code {
  42. c.JSON(http.StatusForbidden, res)
  43. c.Abort()
  44. return
  45. }
  46. permissions := res.Data.([]*entity.Perm)
  47. for _, permission := range permissions {
  48. match, _ := regexp.MatchString(permission.Path, c.Request.RequestURI)
  49. if match && strings.ToUpper(permission.Method) == c.Request.Method {
  50. c.Next()
  51. return
  52. }
  53. }
  54. c.JSON(http.StatusForbidden, result.NO_PERMISSION)
  55. c.Abort()
  56. return
  57. }
  58. }