From 3d492ff720aef2e135e11694209e3aab2b96765b Mon Sep 17 00:00:00 2001 From: laodaming <11058467+laudamine@user.noreply.gitee.com> Date: Wed, 7 Jun 2023 11:35:04 +0800 Subject: [PATCH] fix --- .../internal/handler/userbasicinfohandler.go | 4 +- .../internal/logic/userbasicinfologic.go | 19 ++--- .../internal/logic/usersavebasicinfologic.go | 16 ++--- product/etc/product.yaml | 8 ++- product/internal/config/config.go | 6 +- .../internal/handler/getproductlisthandler.go | 5 +- .../handler/getsuccessrecommandhandler.go | 5 +- product/internal/handler/routes.go | 1 + product/internal/logic/getproductlistlogic.go | 7 +- .../logic/getsuccessrecommandlogic.go | 7 +- product/internal/types/types.go | 60 ++++++++++++++++ server_api/product.api | 4 +- utils/auth/auth.go | 71 ------------------- utils/auth/user.go | 21 ++++++ 14 files changed, 117 insertions(+), 117 deletions(-) delete mode 100644 utils/auth/auth.go create mode 100644 utils/auth/user.go diff --git a/home-user-auth/internal/handler/userbasicinfohandler.go b/home-user-auth/internal/handler/userbasicinfohandler.go index 2534d8ab..10518661 100644 --- a/home-user-auth/internal/handler/userbasicinfohandler.go +++ b/home-user-auth/internal/handler/userbasicinfohandler.go @@ -10,7 +10,6 @@ import ( "fusenapi/home-user-auth/internal/logic" "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" - "fusenapi/utils/auth" ) func UserBasicInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { @@ -26,8 +25,7 @@ func UserBasicInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { } l := logic.NewUserBasicInfoLogic(r.Context(), svcCtx) - userinfo := auth.CheckAuth(r) - resp := l.UserBasicInfo(&req, &userinfo) + resp := l.UserBasicInfo(&req) if resp != nil { httpx.OkJsonCtx(r.Context(), w, resp) } else { diff --git a/home-user-auth/internal/logic/userbasicinfologic.go b/home-user-auth/internal/logic/userbasicinfologic.go index f53c409f..66da8303 100644 --- a/home-user-auth/internal/logic/userbasicinfologic.go +++ b/home-user-auth/internal/logic/userbasicinfologic.go @@ -2,8 +2,6 @@ package logic import ( "context" - "log" - "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" "fusenapi/model" @@ -27,22 +25,15 @@ func NewUserBasicInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Use } } -func (l *UserBasicInfoLogic) UserBasicInfo(req *types.Request, userinfo *auth.UserInfo) (resp *types.Response) { +func (l *UserBasicInfoLogic) UserBasicInfo(req *types.Request) (resp *types.Response) { // 必须返回response, 前端需要的是内部约定的Code码, 处理相关的逻辑. 例子(eg): resp.Set(501, "error") resp = &types.Response{} - // u := l.ctx.Value("userid").(int64) - u := l.ctx.Value("userid") - log.Println(u) - - if userinfo.UserId == 0 { - resp = &types.Response{ - Code: 510, - Message: "user is not exists", - } + loginInfo := auth.GetUserInfoFormCtx(l.ctx) + if loginInfo.UserId == 0 { + resp.SetStatus(basic.CodeOK, "parse login info err ") return resp } - - fsUserModel, err := model.NewFsUserModel(l.svcCtx.MysqlConn).FindOne(l.ctx, userinfo.UserId) + fsUserModel, err := model.NewFsUserModel(l.svcCtx.MysqlConn).FindOne(l.ctx, loginInfo.UserId) if err != nil { logx.Error(err) resp.Set(510, err.Error()) diff --git a/home-user-auth/internal/logic/usersavebasicinfologic.go b/home-user-auth/internal/logic/usersavebasicinfologic.go index 7f545082..ad72a5cd 100644 --- a/home-user-auth/internal/logic/usersavebasicinfologic.go +++ b/home-user-auth/internal/logic/usersavebasicinfologic.go @@ -2,6 +2,7 @@ package logic import ( "context" + "fusenapi/utils/auth" "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" @@ -28,15 +29,12 @@ func NewUserSaveBasicInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) func (l *UserSaveBasicInfoLogic) UserSaveBasicInfo(req *types.RequestBasicInfoForm) (resp *types.Response) { // 必须返回response, 前端需要的是内部约定的Code码, 处理相关的逻辑. 例子(eg): resp.Set(501, "error") resp = &types.Response{} - // logx.Info(req) - // if userinfo.UserId == 0 { - // resp.SetStatusWithMessage(basic.DefaultError, "user is not exists") - // return resp - // } - - userid := l.ctx.Value("userid").(int64) - - fsUserModel, err := model.NewFsUserModel(l.svcCtx.MysqlConn).FindOne(l.ctx, userid) + loginInfo := auth.GetUserInfoFormCtx(l.ctx) + if loginInfo.UserId == 0 { + resp.SetStatus(basic.CodeOK, "parse login info err ") + return resp + } + fsUserModel, err := model.NewFsUserModel(l.svcCtx.MysqlConn).FindOne(l.ctx, loginInfo.UserId) if err != nil { logx.Error(err) } diff --git a/product/etc/product.yaml b/product/etc/product.yaml index 43aeb8a3..001d772b 100644 --- a/product/etc/product.yaml +++ b/product/etc/product.yaml @@ -1,4 +1,8 @@ Name: product Host: 0.0.0.0 -Port: 8888 -DataSource: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest \ No newline at end of file +Port: 8889 +DataSource: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest +Auth: + AccessSecret: fusen2023 + AccessExpire: 60 + RefreshAfter: 60 \ No newline at end of file diff --git a/product/internal/config/config.go b/product/internal/config/config.go index 0e4c60b5..999479a4 100644 --- a/product/internal/config/config.go +++ b/product/internal/config/config.go @@ -1,8 +1,12 @@ package config -import "github.com/zeromicro/go-zero/rest" +import ( + "fusenapi/product/internal/types" + "github.com/zeromicro/go-zero/rest" +) type Config struct { rest.RestConf DataSource string + Auth types.Auth } diff --git a/product/internal/handler/getproductlisthandler.go b/product/internal/handler/getproductlisthandler.go index 8160c070..5e6e94ce 100644 --- a/product/internal/handler/getproductlisthandler.go +++ b/product/internal/handler/getproductlisthandler.go @@ -2,7 +2,6 @@ package handler import ( "errors" - "fusenapi/utils/auth" "net/http" "github.com/zeromicro/go-zero/core/logx" @@ -15,8 +14,6 @@ import ( func GetProductListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - //用户登录信息 - userInfo := auth.CheckAuth(r) var req types.GetProductListReq if err := httpx.Parse(r, &req); err != nil { httpx.OkJsonCtx(r.Context(), w, &types.Response{ @@ -28,7 +25,7 @@ func GetProductListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { } l := logic.NewGetProductListLogic(r.Context(), svcCtx) - resp := l.GetProductList(&req, userInfo) + resp := l.GetProductList(&req) if resp != nil { httpx.OkJsonCtx(r.Context(), w, resp) } else { diff --git a/product/internal/handler/getsuccessrecommandhandler.go b/product/internal/handler/getsuccessrecommandhandler.go index 2634017d..0f154866 100644 --- a/product/internal/handler/getsuccessrecommandhandler.go +++ b/product/internal/handler/getsuccessrecommandhandler.go @@ -2,7 +2,6 @@ package handler import ( "errors" - "fusenapi/utils/auth" "net/http" "github.com/zeromicro/go-zero/core/logx" @@ -15,8 +14,6 @@ import ( func GetSuccessRecommandHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - //用户登录信息 - userInfo := auth.CheckAuth(r) var req types.GetSuccessRecommandReq if err := httpx.Parse(r, &req); err != nil { httpx.OkJsonCtx(r.Context(), w, &types.Response{ @@ -28,7 +25,7 @@ func GetSuccessRecommandHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { } l := logic.NewGetSuccessRecommandLogic(r.Context(), svcCtx) - resp := l.GetSuccessRecommand(&req, userInfo) + resp := l.GetSuccessRecommand(&req) if resp != nil { httpx.OkJsonCtx(r.Context(), w, resp) } else { diff --git a/product/internal/handler/routes.go b/product/internal/handler/routes.go index b0cca7a2..d8304606 100644 --- a/product/internal/handler/routes.go +++ b/product/internal/handler/routes.go @@ -23,5 +23,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Handler: GetSuccessRecommandHandler(serverCtx), }, }, + rest.WithJwt(serverCtx.Config.Auth.AccessSecret), ) } diff --git a/product/internal/logic/getproductlistlogic.go b/product/internal/logic/getproductlistlogic.go index 6ab1fd41..e691a203 100644 --- a/product/internal/logic/getproductlistlogic.go +++ b/product/internal/logic/getproductlistlogic.go @@ -33,12 +33,11 @@ func NewGetProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Ge } // 获取产品列表 -func (l *GetProductListLogic) GetProductList(req *types.GetProductListReq, loginInfo auth.UserInfo) (resp *types.Response) { +func (l *GetProductListLogic) GetProductList(req *types.GetProductListReq) (resp *types.Response) { resp = &types.Response{} - //校验前台登录情况 + loginInfo := auth.GetUserInfoFormCtx(l.ctx) if loginInfo.UserId == 0 { - resp.Set(constants.CODE_UNAUTH, "please sign in") - return + resp.Set(constants.CODE_SERVICE_ERR, "get login user info err") } //如果是demo if req.IsDemo == 1 { diff --git a/product/internal/logic/getsuccessrecommandlogic.go b/product/internal/logic/getsuccessrecommandlogic.go index e448af22..4ea68752 100644 --- a/product/internal/logic/getsuccessrecommandlogic.go +++ b/product/internal/logic/getsuccessrecommandlogic.go @@ -28,12 +28,11 @@ func NewGetSuccessRecommandLogic(ctx context.Context, svcCtx *svc.ServiceContext } // 获取推荐的产品列表 -func (l *GetSuccessRecommandLogic) GetSuccessRecommand(req *types.GetSuccessRecommandReq, loginInfo auth.UserInfo) (resp *types.Response) { +func (l *GetSuccessRecommandLogic) GetSuccessRecommand(req *types.GetSuccessRecommandReq) (resp *types.Response) { resp = &types.Response{} - //校验前台登录情况 + loginInfo := auth.GetUserInfoFormCtx(l.ctx) if loginInfo.UserId == 0 { - resp.Set(constants.CODE_UNAUTH, "please sign in") - return + resp.Set(constants.CODE_SERVICE_ERR, "get login user info err") } //获取用户信息 userModel := model.NewFsUserModel(l.svcCtx.MysqlConn) diff --git a/product/internal/types/types.go b/product/internal/types/types.go index 46d0aefb..1a4d06d1 100644 --- a/product/internal/types/types.go +++ b/product/internal/types/types.go @@ -78,6 +78,20 @@ type Response struct { Data interface{} `json:"data"` } +type ResponseJwt struct { + Code int `json:"code"` + Message string `json:"msg"` + Data interface{} `json:"data"` + AccessSecret string `json:"accessSecret"` + AccessExpire int64 `json:"accessExpire"` +} + +type Auth struct { + AccessSecret string `json:"accessSecret"` + AccessExpire int64 `json:"accessExpire"` + RefreshAfter int64 `json:"refreshAfter"` +} + // Set 设置Response的Code和Message值 func (resp *Response) Set(Code int, Message string) { resp.Code = Code @@ -123,3 +137,49 @@ func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, resp.Data = data[0] } } + +// Set 设置Response的Code和Message值 +func (resp *ResponseJwt) Set(Code int, Message string) { + resp.Code = Code + resp.Message = Message +} + +// Set 设置整个Response +func (resp *ResponseJwt) SetWithData(Code int, Message string, Data interface{}) { + resp.Code = Code + resp.Message = Message + resp.Data = Data +} + +// SetMessage 设置Response的Message +func (resp *ResponseJwt) SetMessage(msg string) { + resp.Message = msg +} + +// SetWithData 设置Data +func (resp *ResponseJwt) SetData(Data interface{}) { + resp.Data = Data +} + +// SetWithData 设置Response的Code和Message值 带Data入参数 +func (resp *ResponseJwt) SetCode(Code int) { + resp.Code = Code +} + +// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数 +func (resp *ResponseJwt) SetStatus(sr *basic.StatusResponse, data ...interface{}) { + resp.Code = sr.Code + resp.Message = sr.Message + if len(data) == 1 { + resp.Data = data[0] + } +} + +// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数 +func (resp *ResponseJwt) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) { + resp.Code = sr.Code + resp.Message = msg + if len(data) == 1 { + resp.Data = data[0] + } +} diff --git a/server_api/product.api b/server_api/product.api index 32a96e38..bda95caf 100644 --- a/server_api/product.api +++ b/server_api/product.api @@ -7,7 +7,9 @@ info ( email: "" ) import "basic.api" - +@server( + jwt: Auth +) service product { //获取产品列表 @handler GetProductListHandler diff --git a/utils/auth/auth.go b/utils/auth/auth.go deleted file mode 100644 index c0862552..00000000 --- a/utils/auth/auth.go +++ /dev/null @@ -1,71 +0,0 @@ -package auth - -import ( - "encoding/json" - "github.com/golang-jwt/jwt" - "github.com/zeromicro/go-zero/core/logx" - "net/http" - "time" -) - -type UserInfo struct { - UserId int64 `json:"user_id"` //网站前台登录uid - BackendUserId int64 `json:"backend_user_id"` //管理后台uid -} - -// 签名key -var signKey = "FushenFGbhgfhgKgGH556HGlXrsfJKhhjYFGKLO==" -var expireTime = int64(3600) - -// 生成token -func GenJwtToken(userInfo UserInfo) (token string, err error) { - t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ - "user_id": userInfo.UserId, - "backend_user_id": userInfo.BackendUserId, - "exp": time.Now().Add(time.Second * time.Duration(expireTime)).Unix(), //过期时间 - "iss": "fusen", - }) - token, err = t.SignedString([]byte(signKey)) - if err != nil { - return "", err - } - return -} - -// 解释token -func ParseJwtToken(token string) (UserInfo, error) { - t, err := jwt.ParseWithClaims(token, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) { - return []byte(signKey), nil - }) - if err != nil { - return UserInfo{}, err - } - d, err := json.Marshal(t.Claims) - if err != nil { - return UserInfo{}, err - } - var userInfo UserInfo - if err = json.Unmarshal(d, &userInfo); err != nil { - return UserInfo{}, err - } - return userInfo, nil -} - -// 检测授权 -func CheckAuth(r *http.Request) UserInfo { - token := r.Header.Get("Authorization") - if token == "" { - token = r.Header.Get("Auth-Key") - } - if token == "" { - logx.Error("token is empty") - return UserInfo{} - } - //解析token - userInfo, err := ParseJwtToken(token) - if err != nil { - logx.Error(err) - return UserInfo{} - } - return userInfo -} diff --git a/utils/auth/user.go b/utils/auth/user.go new file mode 100644 index 00000000..321fa676 --- /dev/null +++ b/utils/auth/user.go @@ -0,0 +1,21 @@ +package auth + +import ( + "context" + "encoding/json" + "github.com/zeromicro/go-zero/core/logx" +) + +type UserInfo struct { + UserId int64 `json:"userid"` +} + +// 获取登录信息 +func GetUserInfoFormCtx(ctx context.Context) UserInfo { + uid, err := ctx.Value("userid").(json.Number).Int64() + if err != nil { + logx.Error("parse uid form context err:", err.Error()) + return UserInfo{} + } + return UserInfo{UserId: uid} +}