middlewareAuth.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package utils
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. "net/http"
  7. "github.com/gogf/gf/v2/errors/gcode"
  8. "github.com/gogf/gf/v2/errors/gerror"
  9. )
  10. // DefaultHandlerResponse is the default implementation of HandlerResponse.
  11. type DefaultHandlerResponse struct {
  12. Code int `json:"code" dc:"Error code"`
  13. Message string `json:"message" dc:"Error message"`
  14. Data interface{} `json:"data" dc:"Result data for certain request according API definition"`
  15. }
  16. func MiddlewareAuth(r *ghttp.Request) {
  17. auth, er := g.Cfg().Get(context.Background(), "chain.auth")
  18. if er != nil {
  19. r.Response.WriteStatus(http.StatusForbidden)
  20. }
  21. apiKey := r.GetHeader("apiKey")
  22. if g.IsEmpty(apiKey) {
  23. r.Response.WriteStatus(http.StatusUnauthorized)
  24. }
  25. if auth.String() == apiKey {
  26. r.Middleware.Next()
  27. } else {
  28. r.Response.WriteJson(DefaultHandlerResponse{
  29. Code: http.StatusUnauthorized,
  30. Message: "the apiKey is wrong",
  31. Data: nil,
  32. })
  33. }
  34. // There's custom buffer content, it then exits current handler.
  35. if r.Response.BufferLength() > 0 {
  36. return
  37. }
  38. var (
  39. msg string
  40. err = r.GetError()
  41. res = r.GetHandlerResponse()
  42. code = gerror.Code(err)
  43. )
  44. if err != nil {
  45. if code == gcode.CodeNil {
  46. code = gcode.CodeInternalError
  47. }
  48. msg = err.Error()
  49. } else if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
  50. msg = http.StatusText(r.Response.Status)
  51. switch r.Response.Status {
  52. case http.StatusNotFound:
  53. code = gcode.CodeNotFound
  54. case http.StatusForbidden:
  55. code = gcode.CodeNotAuthorized
  56. default:
  57. code = gcode.CodeUnknown
  58. }
  59. } else {
  60. code = gcode.CodeOK
  61. }
  62. r.Response.WriteJson(DefaultHandlerResponse{
  63. Code: code.Code(),
  64. Message: msg,
  65. Data: res,
  66. })
  67. }