base_auth.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta/eta_mini_api/models"
  5. "eta/eta_mini_api/utils"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "time"
  11. "github.com/beego/beego/v2/server/web"
  12. )
  13. type BaseAuthController struct {
  14. web.Controller
  15. User *models.User
  16. Session *models.WxSession
  17. }
  18. func (c *BaseAuthController) Prepare() {
  19. method := c.Ctx.Input.Method()
  20. // uri := c.Ctx.Input.URI()
  21. if method != "HEAD" {
  22. if method == "POST" || method == "GET" {
  23. authorization := c.Ctx.Input.Header("authorization")
  24. if authorization == "" {
  25. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
  26. c.StopRun()
  27. return
  28. }
  29. token := authorization
  30. session, err := models.GetWxSessionByAccessToken(token)
  31. if err != nil {
  32. if err.Error() == utils.ErrNoRow() {
  33. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}, false, false)
  34. c.StopRun()
  35. return
  36. }
  37. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Err:" + err.Error()}, false, false)
  38. c.StopRun()
  39. return
  40. }
  41. if session == nil {
  42. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "session is empty "}, false, false)
  43. c.StopRun()
  44. return
  45. }
  46. user, err := models.GetUserByOpenId(session.OpenId)
  47. if err != nil && err.Error() != utils.ErrNoRow() {
  48. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Err:" + err.Error()}, false, false)
  49. c.StopRun()
  50. return
  51. }
  52. c.User = user
  53. c.Session = session
  54. // 判断正式用户,是否在有效期内
  55. if c.User != nil && c.User.Status == utils.UserStatusFormal {
  56. if c.User.ValidStartTime.Before(time.Now()) && c.User.ValidEndTime.After(time.Now()) {
  57. c.User.Status = utils.UserStatusFormal
  58. } else {
  59. c.User.Status = utils.UserStatusNo
  60. }
  61. }
  62. } else {
  63. c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  64. c.StopRun()
  65. return
  66. }
  67. }
  68. }
  69. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  70. var (
  71. hasIndent = false
  72. hasEncoding = false
  73. )
  74. if web.BConfig.RunMode == web.PROD {
  75. hasIndent = false
  76. }
  77. if len(encoding) > 0 && encoding[0] == true {
  78. hasEncoding = true
  79. }
  80. if c.Data["json"] == nil {
  81. //go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  82. body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
  83. utils.ApiLog.Notice(body)
  84. return
  85. }
  86. baseRes := c.Data["json"].(*models.BaseResponse)
  87. if baseRes != nil && baseRes.Ret != 408 {
  88. body, _ := json.Marshal(baseRes)
  89. var requestBody string
  90. method := c.Ctx.Input.Method()
  91. if method == "GET" {
  92. requestBody = c.Ctx.Request.RequestURI
  93. } else {
  94. //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  95. requestBody = string(c.Ctx.Input.RequestBody)
  96. }
  97. if baseRes.Ret != 200 && c.User != nil {
  98. //go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "URI:"+c.Ctx.Input.URI()+"<br/> "+"Params"+requestBody+" <br/>"+"ErrMsg:"+baseRes.ErrMsg+";<br/>Msg:"+baseRes.Msg+";<br/> Body:"+string(content)+"<br/>"+c.SysUser.RealName, utils.EmailSendToUsers)
  99. content := "URI:" + c.Ctx.Input.URI() + "<br/> " + "Params" + requestBody + " <br/>" + "ErrMsg:" + baseRes.ErrMsg + ";<br/>Msg:" + baseRes.Msg + ";<br/> Body:" + string(body) + "<br/>" + c.User.RealName
  100. // go alarm_msg.SendAlarmMsg(body, 1)
  101. utils.ApiLog.Notice(content)
  102. }
  103. }
  104. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  105. }
  106. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  107. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  108. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  109. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  110. // 设置Cookie为HTTPOnly
  111. c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  112. content, err := json.Marshal(data)
  113. if err != nil {
  114. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  115. return err
  116. }
  117. ip := c.Ctx.Input.IP()
  118. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  119. if err != nil {
  120. utils.ApiLog.Info("err:%s", err.Error())
  121. }
  122. c.logUri(content, requestBody, ip)
  123. if utils.RunMode != "debug" {
  124. content = utils.DesBase64Encrypt(content, utils.DesKey)
  125. content = []byte(`"` + string(content) + `"`)
  126. }
  127. if coding {
  128. content = []byte(utils.StringsToJSON(string(content)))
  129. }
  130. return c.Ctx.Output.Body(content)
  131. }
  132. func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
  133. authorization := ""
  134. method := c.Ctx.Input.Method()
  135. uri := c.Ctx.Input.URI()
  136. if method != "HEAD" {
  137. if method == "POST" || method == "GET" {
  138. authorization = c.Ctx.Input.Header("authorization")
  139. if authorization == "" {
  140. authorization = c.Ctx.Input.Header("Authorization")
  141. }
  142. if authorization == "" {
  143. newAuthorization := c.GetString("authorization")
  144. if newAuthorization != `` {
  145. authorization = "authorization=" + newAuthorization
  146. } else {
  147. newAuthorization = c.GetString("Authorization")
  148. authorization = "authorization=" + newAuthorization
  149. }
  150. } else {
  151. if strings.Contains(authorization, ";") {
  152. authorization = strings.Replace(authorization, ";", "$", 1)
  153. }
  154. }
  155. if authorization == "" {
  156. strArr := strings.Split(uri, "?")
  157. for k, v := range strArr {
  158. fmt.Println(k, v)
  159. }
  160. if len(strArr) > 1 {
  161. authorization = strArr[1]
  162. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  163. fmt.Println(authorization)
  164. }
  165. }
  166. }
  167. }
  168. utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
  169. return
  170. }