middleware.go 4.7 KB

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