base_auth.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta/eta_mini_api/models"
  5. "eta/eta_mini_api/utils"
  6. "net/http"
  7. "github.com/beego/beego/v2/server/web"
  8. )
  9. type BaseAuthController struct {
  10. web.Controller
  11. User *models.User
  12. Session *models.WxSession
  13. }
  14. func (c *BaseAuthController) Prepare() {
  15. method := c.Ctx.Input.Method()
  16. // uri := c.Ctx.Input.URI()
  17. if method != "HEAD" {
  18. if method == "POST" || method == "GET" {
  19. authorization := c.Ctx.Input.Header("authorization")
  20. if authorization == "" {
  21. c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"})
  22. c.StopRun()
  23. return
  24. }
  25. token := authorization
  26. session, err := models.GetWxSessionByAccessToken(token)
  27. if err != nil {
  28. if err.Error() == utils.ErrNoRow() {
  29. c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token})
  30. c.StopRun()
  31. return
  32. }
  33. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Err:" + err.Error()})
  34. c.StopRun()
  35. return
  36. }
  37. if session == nil {
  38. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "session is empty "})
  39. c.StopRun()
  40. return
  41. }
  42. user, err := models.GetUserByOpenId(session.OpenId)
  43. if err != nil && err.Error() != utils.ErrNoRow() {
  44. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Err:" + err.Error()})
  45. c.StopRun()
  46. return
  47. }
  48. c.User = user
  49. c.Session = session
  50. } else {
  51. c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"})
  52. c.StopRun()
  53. return
  54. }
  55. }
  56. }
  57. func (c *BaseAuthController) JSON(data interface{}) error {
  58. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  59. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  60. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  61. // 设置Cookie为HTTPOnly
  62. c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  63. content, err := json.Marshal(data)
  64. if err != nil {
  65. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  66. return err
  67. }
  68. if utils.RunMode != "debug" {
  69. content = utils.DesBase64Encrypt(content, utils.DesKey)
  70. content = []byte(`"` + string(content) + `"`)
  71. }
  72. return c.Ctx.Output.Body(content)
  73. }