package controllers import ( "encoding/json" "eta/eta_mini_api/models" "eta/eta_mini_api/utils" "net/http" "github.com/beego/beego/v2/client/orm" "github.com/beego/beego/v2/server/web" ) type BaseAuthController struct { web.Controller User *models.User } func (c *BaseAuthController) Prepare() { method := c.Ctx.Input.Method() // uri := c.Ctx.Input.URI() if method != "HEAD" { if method == "POST" || method == "GET" { authorization := c.Ctx.Input.Header("authorization") if authorization == "" { c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}) c.StopRun() return } token := authorization user, err := models.GetUserByToken(token) if err != nil { if err == orm.ErrNoRows { c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + token}) c.StopRun() return } c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}) c.StopRun() return } if user == nil { c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "user is empty "}) c.StopRun() return } c.User = user } else { c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}) c.StopRun() return } } } func (c *BaseAuthController) JSON(data interface{}) error { c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8") desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt) c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key // 设置Cookie为HTTPOnly c.Ctx.SetCookie("", "", -1, "/", "", false, true, "") content, err := json.Marshal(data) if err != nil { http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError) return err } if utils.RunMode != "debug" { content = utils.DesBase64Encrypt(content, utils.DesKey) content = []byte(`"` + string(content) + `"`) } return c.Ctx.Output.Body(content) }