base_auth.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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/client/orm"
  8. "github.com/beego/beego/v2/server/web"
  9. )
  10. type BaseAuthController struct {
  11. web.Controller
  12. User *models.User
  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. user, err := models.GetUserByToken(token)
  27. if err != nil {
  28. if err == orm.ErrNoRows {
  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: "获取用户信息异常,Eerr:" + err.Error()})
  34. c.StopRun()
  35. return
  36. }
  37. if user == nil {
  38. c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "user is empty "})
  39. c.StopRun()
  40. return
  41. }
  42. c.User = user
  43. } else {
  44. c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"})
  45. c.StopRun()
  46. return
  47. }
  48. }
  49. }
  50. func (c *BaseAuthController) JSON(data interface{}) error {
  51. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  52. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  53. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  54. // 设置Cookie为HTTPOnly
  55. c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  56. content, err := json.Marshal(data)
  57. if err != nil {
  58. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  59. return err
  60. }
  61. if utils.RunMode != "debug" {
  62. content = utils.DesBase64Encrypt(content, utils.DesKey)
  63. content = []byte(`"` + string(content) + `"`)
  64. }
  65. return c.Ctx.Output.Body(content)
  66. }