base_auth.go 5.9 KB

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