middleware.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package router
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "net/http"
  6. "runtime/debug"
  7. "strings"
  8. "time"
  9. )
  10. import (
  11. "github.com/gin-gonic/gin"
  12. )
  13. import (
  14. "resource-server/common"
  15. "resource-server/logger"
  16. )
  17. func InitMiddleware(r *gin.Engine) {
  18. // NoCache is a middleware function that appends headers
  19. r.Use(NoCache)
  20. // 跨域处理
  21. r.Use(Options)
  22. // Secure is a middleware function that appends security
  23. r.Use(Secure)
  24. // Use Slog Logger
  25. r.Use(GinLogger(logger.WithGroup("gin")))
  26. // Global Recover
  27. r.Use(GinRecovery(logger.WithGroup("ginRecovery")))
  28. // check header
  29. r.Use(CheckLanguage)
  30. r.Use(CheckSource)
  31. r.Use(CheckProduct)
  32. // check token
  33. r.Use(CheckAuth)
  34. }
  35. // NoCache is a middleware function that appends headers
  36. // to prevent the client from caching the HTTP response.
  37. func NoCache(c *gin.Context) {
  38. c.Header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate, value")
  39. c.Header("Expires", "Thu, 01 Jan 1970 00:00:00 GMT")
  40. c.Header("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
  41. c.Next()
  42. }
  43. // Options is a middleware function that appends headers
  44. // for options requests and aborts then exits the middleware
  45. // chain and ends the request.
  46. func Options(c *gin.Context) {
  47. if c.Request.Method != "OPTIONS" {
  48. c.Next()
  49. } else {
  50. c.Header("Access-Control-Allow-Origin", "*")
  51. c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
  52. c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")
  53. c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
  54. c.Header("Content-Type", "application/json")
  55. c.AbortWithStatus(200)
  56. }
  57. }
  58. // Secure is a middleware function that appends security
  59. // and resource access headers.
  60. func Secure(c *gin.Context) {
  61. c.Header("Access-Control-Allow-Origin", "*")
  62. //c.Header("X-Frame-Options", "DENY")
  63. c.Header("X-Content-Type-Options", "nosniff")
  64. c.Header("X-XSS-Protection", "1; mode=block")
  65. if c.Request.TLS != nil {
  66. c.Header("Strict-Transport-Security", "max-age=31536000")
  67. }
  68. // Also consider adding Content-Security-Policy headers
  69. // c.Header("Content-Security-Policy", "script-src 'self' https://cdnjs.cloudflare.com")
  70. }
  71. func CheckLanguage(c *gin.Context) {
  72. ok := false
  73. language := c.Request.Header.Get("Language")
  74. for _, l := range common.MetadataConfig.GetLanguages() {
  75. slog.Info("----------", "language", l)
  76. if language == l.ToString() {
  77. ok = true
  78. }
  79. }
  80. slog.Info("----------", "language", language, "ok", ok)
  81. if !ok {
  82. c.AbortWithStatusJSON(200, common.ErrToH(common.InvalidLanguage, c.GetHeader("locale")))
  83. } else {
  84. c.Set("language", language)
  85. }
  86. c.Next()
  87. }
  88. func CheckSource(c *gin.Context) {
  89. source := c.Request.Header.Get("Source")
  90. ok := false
  91. for _, s := range common.MetadataConfig.GetSources() {
  92. if source == s.ToString() {
  93. ok = true
  94. }
  95. }
  96. if !ok {
  97. c.AbortWithStatusJSON(200, common.ErrToH(common.InvalidSource, c.GetHeader("locale")))
  98. } else {
  99. c.Set("source", source)
  100. }
  101. c.Next()
  102. }
  103. func CheckProduct(c *gin.Context) {
  104. product := c.Request.Header.Get("Product")
  105. if product != common.MetadataConfig.GetProduct().ToString() {
  106. c.AbortWithStatusJSON(200, common.ErrToH(common.InvalidProduct, product))
  107. } else {
  108. c.Set("product", product)
  109. }
  110. c.Next()
  111. }
  112. func CheckAuth(c *gin.Context) {
  113. if strings.HasPrefix(c.FullPath(), "/dr/api/v1/auth") {
  114. token := c.Request.Header.Get("Authorization")
  115. uid, username, err := common.ParseToken(strings.TrimPrefix(token, "Bearer "))
  116. if err != nil {
  117. c.AbortWithStatusJSON(200, common.ErrToH(common.InvalidToken, c.GetHeader("locale")))
  118. }
  119. c.Set("uid", uid)
  120. c.Set("username", username)
  121. }
  122. c.Next()
  123. }
  124. func GinLogger(logger *slog.Logger) gin.HandlerFunc {
  125. return func(c *gin.Context) {
  126. start := time.Now()
  127. path := c.Request.URL.Path
  128. if len(c.Request.URL.RawQuery) > 0 {
  129. path += "?" + c.Request.URL.RawQuery
  130. }
  131. c.Next()
  132. cost := time.Since(start)
  133. logger.Info(fmt.Sprintf("[%s]%s, header[%s-%s-%s] ip[%s], resp[%d] %s errors[%s]",
  134. c.Request.Method,
  135. path,
  136. c.GetHeader("Product"),
  137. c.GetHeader("Source"),
  138. c.GetHeader("Language"),
  139. c.ClientIP(),
  140. c.Writer.Status(),
  141. cost.String(),
  142. c.Errors.ByType(gin.ErrorTypePrivate).String(),
  143. ))
  144. }
  145. }
  146. func GinRecovery(logger *slog.Logger) gin.HandlerFunc {
  147. return gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
  148. logger.Error("Recovery from panic", "recoverd", recovered, "stack", string(debug.Stack()))
  149. common.HttpErr(c, common.Unknown)
  150. c.AbortWithStatus(http.StatusOK)
  151. })
  152. }