From 5966b397d0fcef0546f819ae125f59a4f3cf0a22 Mon Sep 17 00:00:00 2001 From: gazebo Date: Tue, 4 Sep 2018 15:54:51 +0800 Subject: [PATCH 1/4] - weixinsns. --- business/jxcallback/auth/weixin/weixin.go | 25 +++++++++++ controllers/wx_controller.go | 54 +++++++++++++++++++++++ routers/router.go | 2 + 3 files changed, 81 insertions(+) create mode 100644 business/jxcallback/auth/weixin/weixin.go create mode 100644 controllers/wx_controller.go diff --git a/business/jxcallback/auth/weixin/weixin.go b/business/jxcallback/auth/weixin/weixin.go new file mode 100644 index 000000000..8c04adea3 --- /dev/null +++ b/business/jxcallback/auth/weixin/weixin.go @@ -0,0 +1,25 @@ +package weixin + +import ( + "fmt" + + "git.rosy.net.cn/baseapi/platformapi/weixinsnsapi" + "git.rosy.net.cn/jx-callback/globals/api" +) + +var ( + StrStateIsWrong = "state:%s状态不对" +) + +func GetUserInfo(code string, state string) (token *weixinsnsapi.UserInfo, err error) { + if state == "" { + wxapi := weixinsnsapi.New(api.WeixinAPI.GetAppID(), api.WeixinAPI.GetSecret()) + token, err2 := wxapi.RefreshToken(code) + if err = err2; err == nil { + return wxapi.GetUserInfo(token.OpenID) + } + } else { + err = fmt.Errorf(StrStateIsWrong, state) + } + return nil, err +} diff --git a/controllers/wx_controller.go b/controllers/wx_controller.go new file mode 100644 index 000000000..afd767b0f --- /dev/null +++ b/controllers/wx_controller.go @@ -0,0 +1,54 @@ +package controllers + +import ( + "encoding/base64" + "fmt" + + "git.rosy.net.cn/baseapi/utils" + "git.rosy.net.cn/jx-callback/business/jxcallback/auth/weixin" + "git.rosy.net.cn/jx-callback/globals" + "github.com/astaxie/beego" +) + +type WeinCallbackResult struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:data` +} + +// Operations about ELMOrder +type WeiXinController struct { + beego.Controller +} + +var ( + ErrParameterIsIllegal = "参数不全或不合法" +) + +// https://open.shop.ele.me/openapi/documents/httppushmethod +func (c *WeiXinController) GetUserInfo() { + retVal := &WeinCallbackResult{} + var err error + code := c.GetString("code") + block := c.GetString("block") + state := c.GetString("state") + str := "" + if block != "" { + if code != "" { + result, err2 := weixin.GetUserInfo(code, state) + if err = err2; err == nil { + retVal.Code = 1 + retVal.Msg = "微信登录成功" + retVal.Data = result + } else { + retVal.Msg = err.Error() + } + } else { + retVal.Msg = "code为空" + } + c.Ctx.Output.Header("Location", fmt.Sprintf("%s?info=%s", block, base64.StdEncoding.EncodeToString(utils.MustMarshal(retVal)))) + } else { + str = "没有block" + } + globals.SugarLogger.Debug(str) +} diff --git a/routers/router.go b/routers/router.go index ec0c4455b..7d9210739 100644 --- a/routers/router.go +++ b/routers/router.go @@ -29,6 +29,8 @@ func init() { beego.AutoRouter(&controllers.ElemeController{}) beego.AutoRouter(&controllers.DadaDeliveryController{}) + beego.AutoRouter(&controllers.WeiXinController{}) + beego.Any("/", func(ctx *beecontext.Context) { ctx.WriteString("pong\n") }) From 1dda77ee3af046fe219cec560bf10566416a4dea Mon Sep 17 00:00:00 2001 From: gazebo Date: Tue, 4 Sep 2018 16:31:00 +0800 Subject: [PATCH 2/4] - redirect added. --- controllers/wx_controller.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/controllers/wx_controller.go b/controllers/wx_controller.go index afd767b0f..0cd449fbf 100644 --- a/controllers/wx_controller.go +++ b/controllers/wx_controller.go @@ -3,10 +3,10 @@ package controllers import ( "encoding/base64" "fmt" + "net/http" "git.rosy.net.cn/baseapi/utils" "git.rosy.net.cn/jx-callback/business/jxcallback/auth/weixin" - "git.rosy.net.cn/jx-callback/globals" "github.com/astaxie/beego" ) @@ -32,7 +32,6 @@ func (c *WeiXinController) GetUserInfo() { code := c.GetString("code") block := c.GetString("block") state := c.GetString("state") - str := "" if block != "" { if code != "" { result, err2 := weixin.GetUserInfo(code, state) @@ -46,9 +45,8 @@ func (c *WeiXinController) GetUserInfo() { } else { retVal.Msg = "code为空" } - c.Ctx.Output.Header("Location", fmt.Sprintf("%s?info=%s", block, base64.StdEncoding.EncodeToString(utils.MustMarshal(retVal)))) } else { - str = "没有block" + retVal.Msg = "没有block" } - globals.SugarLogger.Debug(str) + c.Redirect(fmt.Sprintf("%s?info=%s", block, base64.StdEncoding.EncodeToString(utils.MustMarshal(retVal))), http.StatusTemporaryRedirect) } From deca8efb96fd5221024015b73ce9209ab99686ee Mon Sep 17 00:00:00 2001 From: gazebo Date: Tue, 4 Sep 2018 21:23:51 +0800 Subject: [PATCH 3/4] - auth for weixin. --- .gitignore | 3 +- business/jxcallback/auth/auth.go | 79 ++++ business/jxcallback/auth/weixin/weixin.go | 49 +- business/jxutils/cache/cache.go | 13 + business/jxutils/cache/redis/redis.go | 60 +++ business/jxutils/cache/redis/redis_test.go | 48 ++ controllers/auth_controller.go | 103 +++++ controllers/jx_order.go | 1 + controllers/param_parser.go | 513 --------------------- controllers/wx_controller.go | 52 --- cpauto.sh => gen_param_parser.sh | 2 + globals/globals.go | 6 + main.go | 2 +- routers/commentsRouter_controllers.go | 32 ++ routers/router.go | 7 +- 15 files changed, 399 insertions(+), 571 deletions(-) create mode 100644 business/jxcallback/auth/auth.go create mode 100644 business/jxutils/cache/cache.go create mode 100644 business/jxutils/cache/redis/redis.go create mode 100644 business/jxutils/cache/redis/redis_test.go create mode 100644 controllers/auth_controller.go delete mode 100644 controllers/param_parser.go delete mode 100644 controllers/wx_controller.go rename cpauto.sh => gen_param_parser.sh (54%) diff --git a/.gitignore b/.gitignore index 054440af3..fa22aebc1 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,5 @@ debug .DS_Store *.log *.bak -OFF/ \ No newline at end of file +OFF/ +param_parser.go diff --git a/business/jxcallback/auth/auth.go b/business/jxcallback/auth/auth.go new file mode 100644 index 000000000..2601232fd --- /dev/null +++ b/business/jxcallback/auth/auth.go @@ -0,0 +1,79 @@ +package auth + +import ( + "errors" + "time" + + "git.rosy.net.cn/baseapi/utils" + "git.rosy.net.cn/jx-callback/globals" +) + +const ( + DefTokenDuration = 7 * 24 * time.Hour // 7天 +) + +type IAuther interface { + Login(id, secret string) error + Logout(id string) error +} + +var ( + authers map[string]IAuther +) + +var ( + ErrLoginTypeNotSupported = errors.New("不支持指定的登录类型") +) + +type LoginInfo struct { + ID string + LoginType string + ExpiresIn int64 + Token string +} + +func init() { + authers = make(map[string]IAuther) +} + +func RegisterAuther(loginType string, handler IAuther) { + authers[loginType] = handler +} + +func Login(id, loginType, secret string) (loginInfo *LoginInfo, err error) { + if handler := authers[loginType]; handler != nil { + if err = handler.Login(id, secret); err == nil { + token := utils.GetUUID() + loginInfo = &LoginInfo{ + ID: id, + LoginType: loginType, + ExpiresIn: time.Now().Add(DefTokenDuration).Unix(), + Token: token, + } + globals.Cacher.Set(token, loginInfo, DefTokenDuration) + return loginInfo, nil + } + } else { + err = ErrLoginTypeNotSupported + } + return nil, err +} + +func Logout(token string) (err error) { + loginInfo := new(LoginInfo) + if err = globals.Cacher.GetAs(token, loginInfo); err == nil { + if handler := authers[loginInfo.LoginType]; handler != nil { + err = handler.Logout(loginInfo.ID) + } + globals.Cacher.Del(token) + } + return err +} + +func GetUserInfo(token string) (loginInfo *LoginInfo, err error) { + loginInfo = new(LoginInfo) + if err = globals.Cacher.GetAs(token, loginInfo); err == nil { + return loginInfo, nil + } + return nil, err +} diff --git a/business/jxcallback/auth/weixin/weixin.go b/business/jxcallback/auth/weixin/weixin.go index 8c04adea3..330300aab 100644 --- a/business/jxcallback/auth/weixin/weixin.go +++ b/business/jxcallback/auth/weixin/weixin.go @@ -1,25 +1,70 @@ package weixin import ( + "errors" "fmt" + "time" "git.rosy.net.cn/baseapi/platformapi/weixinsnsapi" + "git.rosy.net.cn/baseapi/utils" + "git.rosy.net.cn/jx-callback/business/jxcallback/auth" + "git.rosy.net.cn/jx-callback/globals" "git.rosy.net.cn/jx-callback/globals/api" ) +const ( + LoginType = "weixinsns" + DefTempPasswordDuration = 5 * time.Minute // 登录时间限制在5分钟内 +) + var ( + ErrLoginFailed = errors.New("登录失败") StrStateIsWrong = "state:%s状态不对" ) -func GetUserInfo(code string, state string) (token *weixinsnsapi.UserInfo, err error) { +type Auther struct { +} + +type UserInfoExt struct { + weixinsnsapi.UserInfo + TempPassword string `json:"tempPassword"` // 一段时间有效的登录密码 +} + +func init() { + auth.RegisterAuther(LoginType, new(Auther)) +} + +func GetUserInfo(code string, state string) (token *UserInfoExt, err error) { if state == "" { wxapi := weixinsnsapi.New(api.WeixinAPI.GetAppID(), api.WeixinAPI.GetSecret()) token, err2 := wxapi.RefreshToken(code) if err = err2; err == nil { - return wxapi.GetUserInfo(token.OpenID) + wxUserinfo, err2 := wxapi.GetUserInfo(token.OpenID) + if err = err2; err == nil { + pwd := utils.GetUUID() + globals.Cacher.Set(wxUserinfo.OpenID, pwd, DefTempPasswordDuration) + return &UserInfoExt{ + UserInfo: *wxUserinfo, + TempPassword: pwd, + }, nil + } } } else { err = fmt.Errorf(StrStateIsWrong, state) } return nil, err } + +func (a *Auther) Login(openid, password string) error { + if value := globals.Cacher.Get(openid); value != nil { + if password == value.(string) { + globals.Cacher.Del(openid) + return nil + } + } + return ErrLoginFailed +} + +func (a *Auther) Logout(openid string) error { + return globals.Cacher.Del(openid) +} diff --git a/business/jxutils/cache/cache.go b/business/jxutils/cache/cache.go new file mode 100644 index 000000000..3766d542c --- /dev/null +++ b/business/jxutils/cache/cache.go @@ -0,0 +1,13 @@ +package cache + +import ( + "time" +) + +type ICacher interface { + FlushAll() error + Set(key string, value interface{}, expiration time.Duration) error + Del(key string) error + Get(key string) interface{} + GetAs(key string, ptr interface{}) error +} diff --git a/business/jxutils/cache/redis/redis.go b/business/jxutils/cache/redis/redis.go new file mode 100644 index 000000000..76ccfffb8 --- /dev/null +++ b/business/jxutils/cache/redis/redis.go @@ -0,0 +1,60 @@ +package redis + +import ( + "fmt" + "time" + + "git.rosy.net.cn/baseapi/utils" + "github.com/go-redis/redis" +) + +type Cacher struct { + client *redis.Client +} + +func New(host string, port int, password string) *Cacher { + if port == 0 { + port = 6379 + } + return &Cacher{ + client: redis.NewClient(&redis.Options{ + Addr: fmt.Sprintf("%s:%d", host, port), + Password: password, + }, + ), + } +} + +func (c *Cacher) FlushAll() error { + return c.client.FlushAll().Err() +} + +func (c *Cacher) Set(key string, value interface{}, expiration time.Duration) error { + strValue := string(utils.MustMarshal(value)) + return c.client.Set(key, strValue, expiration).Err() +} + +func (c *Cacher) Del(key string) error { + return c.client.Del(key).Err() +} + +func (c *Cacher) Get(key string) interface{} { + result, err := c.client.Get(key).Result() + if err == nil { + var retVal interface{} + if err = utils.UnmarshalUseNumber([]byte(result), &retVal); err == nil { + return retVal + } + } + return nil +} + +func (c *Cacher) GetAs(key string, ptr interface{}) error { + result, err := c.client.Get(key).Result() + if err == nil { + if err = utils.UnmarshalUseNumber([]byte(result), ptr); err == nil { + return nil + } + } + return err +} diff --git a/business/jxutils/cache/redis/redis_test.go b/business/jxutils/cache/redis/redis_test.go new file mode 100644 index 000000000..8759d01cc --- /dev/null +++ b/business/jxutils/cache/redis/redis_test.go @@ -0,0 +1,48 @@ +package redis + +import ( + "testing" + + "git.rosy.net.cn/jx-callback/globals" + "git.rosy.net.cn/jx-callback/globals/api" + "git.rosy.net.cn/jx-callback/globals/beegodb" + "github.com/astaxie/beego" +) + +func init() { + //E:/goprojects/src/git.rosy.net.cn/jx-callback/conf/app.conf + ///Users/xujianhua/go/src/git.rosy.net.cn/jx-callback/conf/app.conf + beego.InitBeegoBeforeTest("/Users/xujianhua/go/src/git.rosy.net.cn/jx-callback/conf/app.conf") + beego.BConfig.RunMode = "dev" // InitBeegoBeforeTest会将runmode设置为test + + globals.Init() + beegodb.Init() + api.Init() +} + +type FuckYou struct { + Key string `json:"key"` +} + +func TestIt(t *testing.T) { + cacher := New("localhost", 6379, "") + cacher.FlushAll() + if cacher.Get("key") != nil { + t.Fatal("should get nothing") + } + if err := cacher.Set("key", map[string]interface{}{ + "key": "value", + }, 0); err != nil { + t.Fatal(err) + } + + if cacher.Get("key") == nil { + t.Fatal("should not get nothing") + } + + result := new(FuckYou) + cacher.GetAs("key", result) + if result.Key != "value" { + t.Fatal("should get value") + } +} diff --git a/controllers/auth_controller.go b/controllers/auth_controller.go new file mode 100644 index 000000000..24979be55 --- /dev/null +++ b/controllers/auth_controller.go @@ -0,0 +1,103 @@ +package controllers + +import ( + "encoding/base64" + "fmt" + "net/http" + + "git.rosy.net.cn/baseapi/utils" + "git.rosy.net.cn/jx-callback/business/jxcallback/auth" + "git.rosy.net.cn/jx-callback/business/jxcallback/auth/weixin" + "git.rosy.net.cn/jx-callback/globals" + "github.com/astaxie/beego" +) + +type WeixinCallbackResult struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data"` +} + +// 认证相关API +type AuthController struct { + beego.Controller +} + +var ( + ErrParameterIsIllegal = "参数不全或不合法" +) + +// @Title 给微信用的回调接口 +// @Description 给微信用的回调接口,自己不能直接调用 +// @Param code query string true "门店ID" +// @Param block query string true "门店所属的厂商ID" +// @Param state query string false "门店所属的厂商ID" +// @Success 200 {object} controllers.CallResult +// @Failure 200 {object} controllers.CallResult +// @router /GetWeiXinUserInfo [get] +func (c *AuthController) GetWeiXinUserInfo() { + retVal := &WeixinCallbackResult{} + var err error + code := c.GetString("code") + block := c.GetString("block") + state := c.GetString("state") + if block != "" { + if code != "" { + result, err2 := weixin.GetUserInfo(code, state) + if err = err2; err == nil { + retVal.Code = 1 + retVal.Msg = "微信登录成功" + retVal.Data = result + } else { + retVal.Msg = err.Error() + } + } else { + retVal.Msg = "code为空" + } + } else { + retVal.Msg = "没有block" + } + c.Redirect(fmt.Sprintf("%s?info=%s", block, base64.StdEncoding.EncodeToString(utils.MustMarshal(retVal))), http.StatusTemporaryRedirect) +} + +// @Title 登录接口 +// @Description 登录接口 +// @Param id query string true "登录ID" +// @Param type query string true "登录类型,当前支持[weixinsns,password]" +// @Param secret query string true "不同登录类型的登录秘密" +// @Success 200 {object} controllers.CallResult +// @Failure 200 {object} controllers.CallResult +// @router /Login [post] +func (c *AuthController) Login() { + c.callLogin(func(params *tAuthLoginParams) (retVal interface{}, errCode string, err error) { + retVal, err = auth.Login(params.Id, params.Type, params.Secret) + return retVal, "", err + }) +} + +// @Title 登出接口 +// @Description 登出接口 +// @Param token header string true "认证token" +// @Success 200 {object} controllers.CallResult +// @Failure 200 {object} controllers.CallResult +// @router /Logout [delete] +func (c *AuthController) Logout() { + c.callLogout(func(params *tAuthLogoutParams) (retVal interface{}, errCode string, err error) { + err = auth.Logout(params.Token) + globals.SugarLogger.Debug(err) + return nil, "", err + }) +} + +// @Title 得到用户信息 +// @Description 得到用户信息(从token中) +// @Param token header string true "认证token" +// @Success 200 {object} controllers.CallResult +// @Failure 200 {object} controllers.CallResult +// @router /GetUserInfo [get] +func (c *AuthController) GetUserInfo() { + c.callGetUserInfo(func(params *tAuthGetUserInfoParams) (retVal interface{}, errCode string, err error) { + retVal, err = auth.GetUserInfo(params.Token) + return retVal, "", err + }) +} diff --git a/controllers/jx_order.go b/controllers/jx_order.go index 34a721845..9fe1fbe9b 100644 --- a/controllers/jx_order.go +++ b/controllers/jx_order.go @@ -6,6 +6,7 @@ import ( "github.com/astaxie/beego" ) +// 订单相关API type OrderController struct { beego.Controller } diff --git a/controllers/param_parser.go b/controllers/param_parser.go deleted file mode 100644 index 4109f3807..000000000 --- a/controllers/param_parser.go +++ /dev/null @@ -1,513 +0,0 @@ - -// this file was automatically generated by modified bee tool (https://github.com/GazeboXu/bee) -// bee generate docs -// please don't modify it manually!!! -package controllers - -import ( - "encoding/json" - "errors" - "fmt" - "strings" -) - -const ( - StrRequiredParamIsEmpty = "参数[%s]为空或数值不合法!" -) - -type tOrderSelfDeliveredParams struct { - Token string - VendorOrderID string - VendorID int -} - -// func (c *OrderController) SelfDelivered() { -// c.callSelfDelivered(func(params *tOrderSelfDeliveredParams) (retVal interface{}, errCode string, err error) { -// return retVal, "", err -// }) -// } -func (c *OrderController) callSelfDelivered(handler func(params *tOrderSelfDeliveredParams) (interface{}, string, error)) { - var err error - params := &tOrderSelfDeliveredParams{} - errParams := []string{} - params.Token = c.Ctx.Input.Header("token") - params.VendorOrderID = c.GetString("vendorOrderID") - - if params.VendorID, err = c.GetInt("vendorID", 0); err != nil { - errParams = append(errParams, "vendorID") - } - if params.Token == "" { // 对于token缺失,报一个模糊的错误信息 - err = errors.New("something wrong!") - } - if params.VendorOrderID == "" { - errParams = append(errParams, "vendorOrderID") - } - if err == nil && len(errParams) > 0 { - err = fmt.Errorf(StrRequiredParamIsEmpty, strings.Join(errParams, ",")) - } - - errCode := "-1" - if err == nil { - result, errCode2, err2 := handler(params) - if err = err2; err == nil { - resultMarshal, _ := json.Marshal(result) - c.Data["json"] = &CallResult{ - Code: "0", - Data: string(resultMarshal), - } - } else if errCode2 != "0" && errCode2 != "" { - errCode = errCode2 - } - } - if err != nil { - c.Data["json"] = &CallResult{ - Code: errCode, - Desc: err.Error(), - } - } - c.ServeJSON() -} - -type tOrderGetOrderSkuInfoParams struct { - Token string - VendorOrderID string - VendorID int -} - -// func (c *OrderController) GetOrderSkuInfo() { -// c.callGetOrderSkuInfo(func(params *tOrderGetOrderSkuInfoParams) (retVal interface{}, errCode string, err error) { -// return retVal, "", err -// }) -// } -func (c *OrderController) callGetOrderSkuInfo(handler func(params *tOrderGetOrderSkuInfoParams) (interface{}, string, error)) { - var err error - params := &tOrderGetOrderSkuInfoParams{} - errParams := []string{} - params.Token = c.Ctx.Input.Header("token") - params.VendorOrderID = c.GetString("vendorOrderID") - - if params.VendorID, err = c.GetInt("vendorID", 0); err != nil { - errParams = append(errParams, "vendorID") - } - if params.Token == "" { // 对于token缺失,报一个模糊的错误信息 - err = errors.New("something wrong!") - } - if params.VendorOrderID == "" { - errParams = append(errParams, "vendorOrderID") - } - if err == nil && len(errParams) > 0 { - err = fmt.Errorf(StrRequiredParamIsEmpty, strings.Join(errParams, ",")) - } - - errCode := "-1" - if err == nil { - result, errCode2, err2 := handler(params) - if err = err2; err == nil { - resultMarshal, _ := json.Marshal(result) - c.Data["json"] = &CallResult{ - Code: "0", - Data: string(resultMarshal), - } - } else if errCode2 != "0" && errCode2 != "" { - errCode = errCode2 - } - } - if err != nil { - c.Data["json"] = &CallResult{ - Code: errCode, - Desc: err.Error(), - } - } - c.ServeJSON() -} - -type tOrderGetStoreOrderInfoParams struct { - Token string - StoreID string - LastHours int - FromStatus int - ToStatus int - Offset int - PageSize int -} - -// func (c *OrderController) GetStoreOrderInfo() { -// c.callGetStoreOrderInfo(func(params *tOrderGetStoreOrderInfoParams) (retVal interface{}, errCode string, err error) { -// return retVal, "", err -// }) -// } -func (c *OrderController) callGetStoreOrderInfo(handler func(params *tOrderGetStoreOrderInfoParams) (interface{}, string, error)) { - var err error - params := &tOrderGetStoreOrderInfoParams{} - errParams := []string{} - params.Token = c.Ctx.Input.Header("token") - params.StoreID = c.GetString("storeID") - - if params.LastHours, err = c.GetInt("lastHours", 0); err != nil { - errParams = append(errParams, "lastHours") - } - if params.FromStatus, err = c.GetInt("fromStatus", 0); err != nil { - errParams = append(errParams, "fromStatus") - } - if params.ToStatus, err = c.GetInt("toStatus", 0); err != nil { - errParams = append(errParams, "toStatus") - } - if params.Offset, err = c.GetInt("offset", 0); err != nil { - errParams = append(errParams, "offset") - } - if params.PageSize, err = c.GetInt("pageSize", 0); err != nil { - errParams = append(errParams, "pageSize") - } - if params.Token == "" { // 对于token缺失,报一个模糊的错误信息 - err = errors.New("something wrong!") - } - if params.StoreID == "" { - errParams = append(errParams, "storeID") - } - if err == nil && len(errParams) > 0 { - err = fmt.Errorf(StrRequiredParamIsEmpty, strings.Join(errParams, ",")) - } - - errCode := "-1" - if err == nil { - result, errCode2, err2 := handler(params) - if err = err2; err == nil { - resultMarshal, _ := json.Marshal(result) - c.Data["json"] = &CallResult{ - Code: "0", - Data: string(resultMarshal), - } - } else if errCode2 != "0" && errCode2 != "" { - errCode = errCode2 - } - } - if err != nil { - c.Data["json"] = &CallResult{ - Code: errCode, - Desc: err.Error(), - } - } - c.ServeJSON() -} - -type tOrderGetOrderInfoParams struct { - Token string - VendorOrderID string - VendorID int - Refresh bool -} - -// func (c *OrderController) GetOrderInfo() { -// c.callGetOrderInfo(func(params *tOrderGetOrderInfoParams) (retVal interface{}, errCode string, err error) { -// return retVal, "", err -// }) -// } -func (c *OrderController) callGetOrderInfo(handler func(params *tOrderGetOrderInfoParams) (interface{}, string, error)) { - var err error - params := &tOrderGetOrderInfoParams{} - errParams := []string{} - params.Token = c.Ctx.Input.Header("token") - params.VendorOrderID = c.GetString("vendorOrderID") - - if params.VendorID, err = c.GetInt("vendorID", 0); err != nil { - errParams = append(errParams, "vendorID") - } - if params.Refresh, err = c.GetBool("refresh", false); err != nil { - errParams = append(errParams, "refresh") - } - if params.Token == "" { // 对于token缺失,报一个模糊的错误信息 - err = errors.New("something wrong!") - } - if params.VendorOrderID == "" { - errParams = append(errParams, "vendorOrderID") - } - if err == nil && len(errParams) > 0 { - err = fmt.Errorf(StrRequiredParamIsEmpty, strings.Join(errParams, ",")) - } - - errCode := "-1" - if err == nil { - result, errCode2, err2 := handler(params) - if err = err2; err == nil { - resultMarshal, _ := json.Marshal(result) - c.Data["json"] = &CallResult{ - Code: "0", - Data: string(resultMarshal), - } - } else if errCode2 != "0" && errCode2 != "" { - errCode = errCode2 - } - } - if err != nil { - c.Data["json"] = &CallResult{ - Code: errCode, - Desc: err.Error(), - } - } - c.ServeJSON() -} - -type tOrderSelfDeliveringParams struct { - Token string - VendorOrderID string - VendorID int -} - -// func (c *OrderController) SelfDelivering() { -// c.callSelfDelivering(func(params *tOrderSelfDeliveringParams) (retVal interface{}, errCode string, err error) { -// return retVal, "", err -// }) -// } -func (c *OrderController) callSelfDelivering(handler func(params *tOrderSelfDeliveringParams) (interface{}, string, error)) { - var err error - params := &tOrderSelfDeliveringParams{} - errParams := []string{} - params.Token = c.Ctx.Input.Header("token") - params.VendorOrderID = c.GetString("vendorOrderID") - - if params.VendorID, err = c.GetInt("vendorID", 0); err != nil { - errParams = append(errParams, "vendorID") - } - if params.Token == "" { // 对于token缺失,报一个模糊的错误信息 - err = errors.New("something wrong!") - } - if params.VendorOrderID == "" { - errParams = append(errParams, "vendorOrderID") - } - if err == nil && len(errParams) > 0 { - err = fmt.Errorf(StrRequiredParamIsEmpty, strings.Join(errParams, ",")) - } - - errCode := "-1" - if err == nil { - result, errCode2, err2 := handler(params) - if err = err2; err == nil { - resultMarshal, _ := json.Marshal(result) - c.Data["json"] = &CallResult{ - Code: "0", - Data: string(resultMarshal), - } - } else if errCode2 != "0" && errCode2 != "" { - errCode = errCode2 - } - } - if err != nil { - c.Data["json"] = &CallResult{ - Code: errCode, - Desc: err.Error(), - } - } - c.ServeJSON() -} - -type tOrderFinishedPickupParams struct { - Token string - VendorOrderID string - VendorID int -} - -// func (c *OrderController) FinishedPickup() { -// c.callFinishedPickup(func(params *tOrderFinishedPickupParams) (retVal interface{}, errCode string, err error) { -// return retVal, "", err -// }) -// } -func (c *OrderController) callFinishedPickup(handler func(params *tOrderFinishedPickupParams) (interface{}, string, error)) { - var err error - params := &tOrderFinishedPickupParams{} - errParams := []string{} - params.Token = c.Ctx.Input.Header("token") - params.VendorOrderID = c.GetString("vendorOrderID") - - if params.VendorID, err = c.GetInt("vendorID", 0); err != nil { - errParams = append(errParams, "vendorID") - } - if params.Token == "" { // 对于token缺失,报一个模糊的错误信息 - err = errors.New("something wrong!") - } - if params.VendorOrderID == "" { - errParams = append(errParams, "vendorOrderID") - } - if err == nil && len(errParams) > 0 { - err = fmt.Errorf(StrRequiredParamIsEmpty, strings.Join(errParams, ",")) - } - - errCode := "-1" - if err == nil { - result, errCode2, err2 := handler(params) - if err = err2; err == nil { - resultMarshal, _ := json.Marshal(result) - c.Data["json"] = &CallResult{ - Code: "0", - Data: string(resultMarshal), - } - } else if errCode2 != "0" && errCode2 != "" { - errCode = errCode2 - } - } - if err != nil { - c.Data["json"] = &CallResult{ - Code: errCode, - Desc: err.Error(), - } - } - c.ServeJSON() -} - -type tOrderCreateWaybillOnProvidersParams struct { - Token string - VendorOrderID string - VendorID int -} - -// func (c *OrderController) CreateWaybillOnProviders() { -// c.callCreateWaybillOnProviders(func(params *tOrderCreateWaybillOnProvidersParams) (retVal interface{}, errCode string, err error) { -// return retVal, "", err -// }) -// } -func (c *OrderController) callCreateWaybillOnProviders(handler func(params *tOrderCreateWaybillOnProvidersParams) (interface{}, string, error)) { - var err error - params := &tOrderCreateWaybillOnProvidersParams{} - errParams := []string{} - params.Token = c.Ctx.Input.Header("token") - params.VendorOrderID = c.GetString("vendorOrderID") - - if params.VendorID, err = c.GetInt("vendorID", 0); err != nil { - errParams = append(errParams, "vendorID") - } - if params.Token == "" { // 对于token缺失,报一个模糊的错误信息 - err = errors.New("something wrong!") - } - if params.VendorOrderID == "" { - errParams = append(errParams, "vendorOrderID") - } - if err == nil && len(errParams) > 0 { - err = fmt.Errorf(StrRequiredParamIsEmpty, strings.Join(errParams, ",")) - } - - errCode := "-1" - if err == nil { - result, errCode2, err2 := handler(params) - if err = err2; err == nil { - resultMarshal, _ := json.Marshal(result) - c.Data["json"] = &CallResult{ - Code: "0", - Data: string(resultMarshal), - } - } else if errCode2 != "0" && errCode2 != "" { - errCode = errCode2 - } - } - if err != nil { - c.Data["json"] = &CallResult{ - Code: errCode, - Desc: err.Error(), - } - } - c.ServeJSON() -} - -type tOrderGetStoreOrderCountInfoParams struct { - Token string - StoreID string - LastHours int -} - -// func (c *OrderController) GetStoreOrderCountInfo() { -// c.callGetStoreOrderCountInfo(func(params *tOrderGetStoreOrderCountInfoParams) (retVal interface{}, errCode string, err error) { -// return retVal, "", err -// }) -// } -func (c *OrderController) callGetStoreOrderCountInfo(handler func(params *tOrderGetStoreOrderCountInfoParams) (interface{}, string, error)) { - var err error - params := &tOrderGetStoreOrderCountInfoParams{} - errParams := []string{} - params.Token = c.Ctx.Input.Header("token") - params.StoreID = c.GetString("storeID") - - if params.LastHours, err = c.GetInt("lastHours", 0); err != nil { - errParams = append(errParams, "lastHours") - } - if params.Token == "" { // 对于token缺失,报一个模糊的错误信息 - err = errors.New("something wrong!") - } - if params.StoreID == "" { - errParams = append(errParams, "storeID") - } - if err == nil && len(errParams) > 0 { - err = fmt.Errorf(StrRequiredParamIsEmpty, strings.Join(errParams, ",")) - } - - errCode := "-1" - if err == nil { - result, errCode2, err2 := handler(params) - if err = err2; err == nil { - resultMarshal, _ := json.Marshal(result) - c.Data["json"] = &CallResult{ - Code: "0", - Data: string(resultMarshal), - } - } else if errCode2 != "0" && errCode2 != "" { - errCode = errCode2 - } - } - if err != nil { - c.Data["json"] = &CallResult{ - Code: errCode, - Desc: err.Error(), - } - } - c.ServeJSON() -} - -type tOrderGetOrderWaybillInfoParams struct { - Token string - VendorOrderID string - VendorID int -} - -// func (c *OrderController) GetOrderWaybillInfo() { -// c.callGetOrderWaybillInfo(func(params *tOrderGetOrderWaybillInfoParams) (retVal interface{}, errCode string, err error) { -// return retVal, "", err -// }) -// } -func (c *OrderController) callGetOrderWaybillInfo(handler func(params *tOrderGetOrderWaybillInfoParams) (interface{}, string, error)) { - var err error - params := &tOrderGetOrderWaybillInfoParams{} - errParams := []string{} - params.Token = c.Ctx.Input.Header("token") - params.VendorOrderID = c.GetString("vendorOrderID") - - if params.VendorID, err = c.GetInt("vendorID", 0); err != nil { - errParams = append(errParams, "vendorID") - } - if params.Token == "" { // 对于token缺失,报一个模糊的错误信息 - err = errors.New("something wrong!") - } - if params.VendorOrderID == "" { - errParams = append(errParams, "vendorOrderID") - } - if err == nil && len(errParams) > 0 { - err = fmt.Errorf(StrRequiredParamIsEmpty, strings.Join(errParams, ",")) - } - - errCode := "-1" - if err == nil { - result, errCode2, err2 := handler(params) - if err = err2; err == nil { - resultMarshal, _ := json.Marshal(result) - c.Data["json"] = &CallResult{ - Code: "0", - Data: string(resultMarshal), - } - } else if errCode2 != "0" && errCode2 != "" { - errCode = errCode2 - } - } - if err != nil { - c.Data["json"] = &CallResult{ - Code: errCode, - Desc: err.Error(), - } - } - c.ServeJSON() -} diff --git a/controllers/wx_controller.go b/controllers/wx_controller.go deleted file mode 100644 index 0cd449fbf..000000000 --- a/controllers/wx_controller.go +++ /dev/null @@ -1,52 +0,0 @@ -package controllers - -import ( - "encoding/base64" - "fmt" - "net/http" - - "git.rosy.net.cn/baseapi/utils" - "git.rosy.net.cn/jx-callback/business/jxcallback/auth/weixin" - "github.com/astaxie/beego" -) - -type WeinCallbackResult struct { - Code int `json:"code"` - Msg string `json:"msg"` - Data interface{} `json:data` -} - -// Operations about ELMOrder -type WeiXinController struct { - beego.Controller -} - -var ( - ErrParameterIsIllegal = "参数不全或不合法" -) - -// https://open.shop.ele.me/openapi/documents/httppushmethod -func (c *WeiXinController) GetUserInfo() { - retVal := &WeinCallbackResult{} - var err error - code := c.GetString("code") - block := c.GetString("block") - state := c.GetString("state") - if block != "" { - if code != "" { - result, err2 := weixin.GetUserInfo(code, state) - if err = err2; err == nil { - retVal.Code = 1 - retVal.Msg = "微信登录成功" - retVal.Data = result - } else { - retVal.Msg = err.Error() - } - } else { - retVal.Msg = "code为空" - } - } else { - retVal.Msg = "没有block" - } - c.Redirect(fmt.Sprintf("%s?info=%s", block, base64.StdEncoding.EncodeToString(utils.MustMarshal(retVal))), http.StatusTemporaryRedirect) -} diff --git a/cpauto.sh b/gen_param_parser.sh similarity index 54% rename from cpauto.sh rename to gen_param_parser.sh index e4e6d576d..1a1f33b26 100755 --- a/cpauto.sh +++ b/gen_param_parser.sh @@ -1 +1,3 @@ +rm controllers/param_parser.go +bee generate docs cp swagger/param_parser.go.txt controllers/param_parser.go diff --git a/globals/globals.go b/globals/globals.go index 689b3a414..9121df509 100644 --- a/globals/globals.go +++ b/globals/globals.go @@ -2,6 +2,8 @@ package globals import ( "git.rosy.net.cn/baseapi" + "git.rosy.net.cn/jx-callback/business/jxutils/cache" + "git.rosy.net.cn/jx-callback/business/jxutils/cache/redis" "github.com/astaxie/beego" "github.com/astaxie/beego/logs" _ "github.com/go-sql-driver/mysql" // import your used driver @@ -23,6 +25,8 @@ var ( JxorderskuTableName string ElemeorderTableName string JdorderTableName string + + Cacher cache.ICacher ) func init() { @@ -47,4 +51,6 @@ func Init() { JxorderskuTableName = "jxordersku" ElemeorderTableName = "elemeorder" JdorderTableName = "jdorder" + + Cacher = redis.New(beego.AppConfig.DefaultString("redisHost", "localhost"), beego.AppConfig.DefaultInt("redisPort", 0), beego.AppConfig.DefaultString("redisPassword", "")) } diff --git a/main.go b/main.go index 51a70d28a..1d02c02a1 100644 --- a/main.go +++ b/main.go @@ -94,7 +94,7 @@ func main() { beego.Handler("/admin/*", mux) } - if beego.BConfig.RunMode == "dev" { + if beego.BConfig.RunMode != "prod" { beego.BConfig.WebConfig.DirectoryIndex = true beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger" } diff --git a/routers/commentsRouter_controllers.go b/routers/commentsRouter_controllers.go index aced310ca..88677dab1 100644 --- a/routers/commentsRouter_controllers.go +++ b/routers/commentsRouter_controllers.go @@ -7,6 +7,38 @@ import ( func init() { + beego.GlobalControllerRouter["git.rosy.net.cn/jx-callback/controllers:AuthController"] = append(beego.GlobalControllerRouter["git.rosy.net.cn/jx-callback/controllers:AuthController"], + beego.ControllerComments{ + Method: "GetUserInfo", + Router: `/GetUserInfo`, + AllowHTTPMethods: []string{"get"}, + MethodParams: param.Make(), + Params: nil}) + + beego.GlobalControllerRouter["git.rosy.net.cn/jx-callback/controllers:AuthController"] = append(beego.GlobalControllerRouter["git.rosy.net.cn/jx-callback/controllers:AuthController"], + beego.ControllerComments{ + Method: "GetWeiXinUserInfo", + Router: `/GetWeiXinUserInfo`, + AllowHTTPMethods: []string{"get"}, + MethodParams: param.Make(), + Params: nil}) + + beego.GlobalControllerRouter["git.rosy.net.cn/jx-callback/controllers:AuthController"] = append(beego.GlobalControllerRouter["git.rosy.net.cn/jx-callback/controllers:AuthController"], + beego.ControllerComments{ + Method: "Login", + Router: `/Login`, + AllowHTTPMethods: []string{"post"}, + MethodParams: param.Make(), + Params: nil}) + + beego.GlobalControllerRouter["git.rosy.net.cn/jx-callback/controllers:AuthController"] = append(beego.GlobalControllerRouter["git.rosy.net.cn/jx-callback/controllers:AuthController"], + beego.ControllerComments{ + Method: "Logout", + Router: `/Logout`, + AllowHTTPMethods: []string{"delete"}, + MethodParams: param.Make(), + Params: nil}) + beego.GlobalControllerRouter["git.rosy.net.cn/jx-callback/controllers:OrderController"] = append(beego.GlobalControllerRouter["git.rosy.net.cn/jx-callback/controllers:OrderController"], beego.ControllerComments{ Method: "CreateWaybillOnProviders", diff --git a/routers/router.go b/routers/router.go index 7d9210739..2573e222a 100644 --- a/routers/router.go +++ b/routers/router.go @@ -21,6 +21,11 @@ func init() { &controllers.OrderController{}, ), ), + beego.NSNamespace("/auth", + beego.NSInclude( + &controllers.AuthController{}, + ), + ), ) beego.AddNamespace(ns) @@ -29,8 +34,6 @@ func init() { beego.AutoRouter(&controllers.ElemeController{}) beego.AutoRouter(&controllers.DadaDeliveryController{}) - beego.AutoRouter(&controllers.WeiXinController{}) - beego.Any("/", func(ctx *beecontext.Context) { ctx.WriteString("pong\n") }) From d9031612e1b9225295f44ca24475c434f4e011d0 Mon Sep 17 00:00:00 2001 From: gazebo Date: Tue, 4 Sep 2018 22:02:37 +0800 Subject: [PATCH 4/4] - copy swagger files. --- deploy/ansible.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/deploy/ansible.yml b/deploy/ansible.yml index 1bbd6dbef..e74b0f47d 100644 --- a/deploy/ansible.yml +++ b/deploy/ansible.yml @@ -26,5 +26,13 @@ owner: ubuntu group: ubuntu mode: 0555 + - name: copy swagger files to dest + copy: + src: ../swagger + dest: /jxdata/jx-callback/ + owner: ubuntu + group: ubuntu + mode: 0555 + - name: shell shell: cd /jxdata/jx-callback/conf && sed -i 's/runmode\s*=\s*.*/runmode = {{ runmode }}/' app.conf && sudo systemctl restart jx-callback