middleware.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. package middleware
  2. import (
  3. elastic "app.yhyue.com/moapp/jybase/es"
  4. "strings"
  5. //. "app.yhyue.com/moapp/jybase/api"
  6. "context"
  7. "fmt"
  8. "jyOrderManager/internal/consts"
  9. "jyOrderManager/internal/jyutil"
  10. "jyOrderManager/internal/model"
  11. "jyOrderManager/internal/service"
  12. "net/http"
  13. "sync"
  14. "time"
  15. util "app.yhyue.com/moapp/jybase/common"
  16. "github.com/gogf/gf/v2/errors/gcode"
  17. "github.com/gogf/gf/v2/errors/gerror"
  18. "github.com/gogf/gf/v2/frame/g"
  19. "github.com/gogf/gf/v2/net/ghttp"
  20. )
  21. type sMiddleware struct {
  22. }
  23. var (
  24. logArr = []map[string]interface{}{}
  25. logLock = &sync.Mutex{}
  26. logSaveCount int
  27. )
  28. func init() {
  29. logSaveCount = g.Cfg().MustGet(context.Background(), "logger.logSaveCount", 500).Int()
  30. elastic.NewEs("v7", g.Cfg().MustGet(context.Background(), "esAddress").String(), g.Cfg().MustGet(context.Background(), "esSize").Int(), g.Cfg().MustGet(context.Background(), "esUserName").String(), g.Cfg().MustGet(context.Background(), "esPassword").String())
  31. service.RegisterMiddleware(&sMiddleware{})
  32. }
  33. // 定时保存日志
  34. func SaveLogTask() {
  35. logLock.Lock()
  36. if len(logArr) >= 1 {
  37. tmpArr := logArr
  38. logArr = make([]map[string]interface{}, 0)
  39. go func() {
  40. g.Log().Info(context.TODO(), "timer..save..visit..log", len(tmpArr))
  41. jyutil.MG.DB("log").SaveBulk("jy_order_manager", tmpArr...)
  42. }()
  43. }
  44. logLock.Unlock()
  45. time.AfterFunc(5*time.Minute, SaveLogTask)
  46. }
  47. // 访问日志
  48. func (s *sMiddleware) Log(r *ghttp.Request) {
  49. timeNow := time.Now()
  50. data := map[string]interface{}{
  51. "date": timeNow.Unix(),
  52. "ip": r.GetClientIp(),
  53. "refer": r.Referer(),
  54. "year": timeNow.Year(),
  55. "month": timeNow.Month(),
  56. "day": timeNow.Day(),
  57. "hour": timeNow.Hour(),
  58. "minutes": timeNow.Minute(),
  59. "mdescribe": r.GetBodyString(),
  60. "client": r.UserAgent(),
  61. "os": util.GetOS(r.UserAgent()),
  62. "browse": util.GetBrowse(r.UserAgent()),
  63. "method": r.Method,
  64. "url": r.RequestURI,
  65. "entUserId": r.Session.MustGet("entUserId", 0).Int64(),
  66. "entUserName": r.Session.MustGet("entUserName", "").String(),
  67. }
  68. logLock.Lock()
  69. logArr = append(logArr, data)
  70. if len(logArr) >= logSaveCount {
  71. tmpArr := logArr
  72. logArr = make([]map[string]interface{}, 0)
  73. go func() {
  74. g.Log().Info(r.Context(), "save..visit..log", len(tmpArr))
  75. jyutil.MG.DB("log").SaveBulk("jy_order_manager", tmpArr...)
  76. }()
  77. }
  78. logLock.Unlock()
  79. r.Middleware.Next()
  80. }
  81. // LoginFilter 登录过滤拦截
  82. func (s *sMiddleware) LoginFilter(r *ghttp.Request) {
  83. var (
  84. uMsg *model.User
  85. err error
  86. )
  87. if !strings.HasPrefix(r.RequestURI, "/debug") {
  88. if token := r.Header.Get("Token"); token != "" {
  89. uMsg, err = jyutil.GetUserMsgFromToken(r.Context(), token)
  90. if err != nil {
  91. r.SetError(fmt.Errorf("无效token"))
  92. return
  93. }
  94. } else {
  95. uMsg = &model.User{
  96. PositionId: r.Session.MustGet("positionId", 0).Int64(),
  97. EntUserId: r.Session.MustGet("entUserId", 0).Int64(),
  98. EntId: r.Session.MustGet("entId", 0).Int64(),
  99. EntDeptId: r.Session.MustGet("entDeptId", 0).Int64(),
  100. EntRole: r.Session.MustGet("entRole", 0).Int64(),
  101. AccountId: r.Session.MustGet("accountId", 0).Int64(),
  102. //MgoUserId: r.Session.MustGet("mgoUserId", 0).String(),
  103. EntUserName: r.Session.MustGet("entUserName", "").String(),
  104. }
  105. }
  106. if uMsg == nil || uMsg.EntId == 0 || uMsg.EntUserId == 0 {
  107. r.SetError(fmt.Errorf("身份异常"))
  108. return
  109. }
  110. if uMsg.EntId != g.Cfg("global").MustGet(r.Context(), "powerEntId", 25917).Int64() {
  111. r.SetError(fmt.Errorf("非法请求"))
  112. return
  113. }
  114. r.SetCtxVar(consts.ContextKey, uMsg)
  115. }
  116. r.Middleware.Next()
  117. }
  118. // CORS 允许跨域请求
  119. func (s *sMiddleware) CORS(r *ghttp.Request) {
  120. r.Response.CORSDefault()
  121. r.Middleware.Next()
  122. }
  123. // MiddlewareHandlerResponse is the default middleware handling handler response object and its error.
  124. func (s *sMiddleware) MiddlewareHandlerResponse(r *ghttp.Request) {
  125. r.Middleware.Next()
  126. // There's custom buffer content, it then exits current handler.
  127. if r.Response.BufferLength() > 0 {
  128. return
  129. }
  130. var (
  131. msg string
  132. err = r.GetError()
  133. res = r.GetHandlerResponse()
  134. code = gerror.Code(err)
  135. )
  136. if err != nil {
  137. if code == gcode.CodeNil {
  138. code = gcode.CodeInternalError
  139. }
  140. msg = err.Error()
  141. } else {
  142. if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
  143. msg = http.StatusText(r.Response.Status)
  144. switch r.Response.Status {
  145. case http.StatusNotFound:
  146. code = gcode.CodeNotFound
  147. case http.StatusForbidden:
  148. code = gcode.CodeNotAuthorized
  149. default:
  150. code = gcode.CodeUnknown
  151. }
  152. // It creates error as it can be retrieved by otherProduct middlewares.
  153. err = gerror.NewCode(code, msg)
  154. r.SetError(err)
  155. } else {
  156. code = gcode.CodeOK
  157. }
  158. }
  159. r.Response.WriteJson(model.DefaultResponse{
  160. Code: code.Code(),
  161. Message: msg,
  162. Data: res,
  163. })
  164. }