checkAuth.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package middleware
  2. import (
  3. "bytes"
  4. "github.com/gin-gonic/gin"
  5. "iot_manager_service/util/common"
  6. "net/http"
  7. "strings"
  8. )
  9. type CustomResponseWriter struct {
  10. gin.ResponseWriter
  11. body *bytes.Buffer
  12. Host string
  13. }
  14. func (w CustomResponseWriter) Write(b []byte) (int, error) {
  15. w.body.Write(b)
  16. if strings.Contains(w.Host, "cloud.long-chi.com") {
  17. old := string(b)
  18. //为兼容https,此处需要修改下
  19. new := strings.ReplaceAll(old, "http://110.40.223.170:9000/", "https://cloud.long-chi.com/")
  20. new = strings.ReplaceAll(new, "http://106.52.134.22:9099/", "https://cloud.long-chi.com/")
  21. b = []byte(new)
  22. }
  23. return w.ResponseWriter.Write(b)
  24. }
  25. func (w CustomResponseWriter) WriteString(s string) (int, error) {
  26. w.body.WriteString(s)
  27. return w.ResponseWriter.WriteString(s)
  28. }
  29. func CheckAuth() gin.HandlerFunc {
  30. return func(ctx *gin.Context) {
  31. //该路由下不校验token
  32. if strings.Contains(ctx.Request.RequestURI, "/login") ||
  33. strings.Contains(ctx.Request.RequestURI, "/captcha") ||
  34. strings.Contains(ctx.Request.RequestURI, "/tenant/info") ||
  35. strings.Contains(ctx.Request.RequestURI, "/token") {
  36. ctx.Next()
  37. return
  38. }
  39. authorization := ctx.GetHeader(Authorization)
  40. if authorization != "" {
  41. token := ParseAccessToken(authorization)
  42. if token != nil {
  43. ctx.Set(Authorization, token)
  44. blw := &CustomResponseWriter{body: bytes.NewBufferString(""), ResponseWriter: ctx.Writer, Host: ctx.Request.Host}
  45. ctx.Writer = blw
  46. ctx.Next()
  47. return
  48. }
  49. }
  50. ctx.JSON(http.StatusUnauthorized, common.NormalResponse(http.StatusUnauthorized, "token is invalid", nil))
  51. ctx.Abort()
  52. }
  53. }