auth.go 985 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/samber/lo"
  6. "go_server/base/core"
  7. "go_server/model/common/response"
  8. "go_server/model/system"
  9. "net/http"
  10. "strings"
  11. )
  12. func Auth() gin.HandlerFunc {
  13. return func(c *gin.Context) {
  14. path := c.Request.URL.Path
  15. // /proxy/*path
  16. // /api/app/login/check
  17. // /api/sys/user/find
  18. api, err := system.NewApis().FindOrCreateAuth(core.MainDb(), path, c.Request.Method)
  19. if err == nil {
  20. // 必须存在用户ID 角色ID
  21. roleId := c.GetInt64("roleId")
  22. var role *system.Role
  23. core.MainDb().Model(&system.Role{}).Where("id", roleId).First(&role)
  24. if role.Apis != "*" {
  25. authsList := strings.Split(role.Apis, ",") // 通过缓存获取角色配置的权限
  26. if !lo.Contains(authsList, fmt.Sprintf("%d", api.ID)) {
  27. c.AbortWithStatusJSON(http.StatusUnauthorized, response.ErrorObjByCode(response.ResponseCodeInsufficientAuthority))
  28. return
  29. }
  30. }
  31. }
  32. // 继续执行
  33. c.Next()
  34. }
  35. }