修复 AuthKey为空的时候 也可以过.

This commit is contained in:
eson 2023-06-25 11:26:47 +08:00
parent 8bd6f019ba
commit efe02a0355
23 changed files with 267 additions and 125 deletions

19
constants/webset.go Normal file
View File

@ -0,0 +1,19 @@
package constants
type TypeWebSet string
const (
FONT_CONFIG TypeWebSet = "font_config" //字体
POLICY_CONFIG TypeWebSet = "policy" //政策
CLAUSE_CONFIG TypeWebSet = "clause" //条款
FAQ_CONFIG TypeWebSet = "faq" //问答
RECOMMEND_DETAIL_PRODUCT TypeWebSet = "recommend_detail_" //详情页推荐-后街pid
RENDER_DESIGN TypeWebSet = "render_design_" //云渲染 后接client_no
LAST_DESIGN TypeWebSet = "last_design_" //最后设计 后接uid
OTHER_LIST TypeWebSet = "other_list_" //列表页其他列表 后接type 分类id
PRODUCT_INFO TypeWebSet = "product_info_" //详情数据 后接sn
MODEL_DATA TypeWebSet = "model_data" //所有模型数据
TEMPLATE_PRODUCT TypeWebSet = "product_template_" //模板数据 后接产品id
CART_NUM TypeWebSet = "cart_num_" //购物车数量 后接uid
USER_ORDERNO TypeWebSet = "order_no_" //用户最新订单编号
)

View File

@ -33,6 +33,10 @@ func NewServiceContext(c {{.config}}) *ServiceContext {
func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
AuthKey := r.Header.Get("Authorization")
if AuthKey == "" {
return nil, nil
}
if len(AuthKey) <= 50 {
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
}

View File

@ -1,2 +1,10 @@
package gmodel
// TODO: 使用model的属性做你想做的
import "context"
// TODO: 使用model的属性做你想做的
func (m *FsWebSetModel) FindValueByKey(ctx context.Context, keyType string) (data FsWebSet, err error) {
err = m.db.WithContext(ctx).Model(&data).Select("value").Where("`key` = ?", keyType).Take(&data).Error
return data, err
}

View File

@ -31,6 +31,10 @@ func NewServiceContext(c config.Config) *ServiceContext {
func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
AuthKey := r.Header.Get("Authorization")
if AuthKey == "" {
return nil, nil
}
if len(AuthKey) <= 50 {
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
}

View File

@ -2,6 +2,8 @@ package logic
import (
"fmt"
fstests "fusenapi/utils/tests"
"testing"
"github.com/474420502/requests"
@ -14,7 +16,7 @@ func TestAcceptCookieLogic(t *testing.T) {
var result gjson.Result
// 获取 session并携带 JWT token
ses := GetSesssion(t, gserver)
ses := fstests.GetSesssion()
// 向服务器发送 GET 请求,获取 cookie 信息
resp, err = ses.Post(fmt.Sprintf("http://%s:%d/user/accept-cookie", cnf.Host, cnf.Port)).TestExecute(gserver)

View File

@ -6,9 +6,7 @@ import (
"fusenapi/server/home-user-auth/internal/handler"
"fusenapi/server/home-user-auth/internal/svc"
"log"
"testing"
"github.com/474420502/requests"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
@ -19,10 +17,10 @@ var gserver *rest.Server
func init() {
log.SetFlags(log.Llongfile)
gserver = GetTestServer()
gserver = GetTestServer(testConfigFile)
}
func GetTestServer() *rest.Server {
func GetTestServer(testConfigFile string) *rest.Server {
conf.MustLoad(testConfigFile, &cnf)
@ -35,52 +33,3 @@ func GetTestServer() *rest.Server {
fmt.Printf("Starting server at %s:%d...\n", cnf.Host, cnf.Port)
return server
}
func GetSesssion(t *testing.T, server requests.ITestServer) *requests.Session {
ses := requests.NewSession()
return ses
}
func GetSesssionWithUserToken(t *testing.T, server requests.ITestServer) *requests.Session {
ses := requests.NewSession()
tp := ses.Post(fmt.Sprintf("http://%s:%d/user/login", cnf.Host, cnf.Port))
tp.SetBodyJson(map[string]interface{}{
"name": "devenv@sina.cn",
"pwd": "$2y$13$6UFDMZQMEfqFYiNLpiUCi.B3fpvGEamPAjIgzUqv/u7jT05nB3pOC",
})
resp, err := tp.TestExecute(server)
if err != nil {
t.Error(err)
}
result := resp.Json()
code := result.Get("code").Int()
if code != 200 {
t.Error("code is not 200")
}
token := result.Get("data.token")
if !token.Exists() {
t.Error("data.token is not exists")
}
ses.Header.Add("Authorization", token.String())
return ses
}
func GetSesssionWithGuestToken(t *testing.T, server requests.ITestServer) *requests.Session {
ses := requests.NewSession()
tp := ses.Post(fmt.Sprintf("http://%s:%d/accept/cookie", cnf.Host, cnf.Port))
resp, err := tp.TestExecute(server)
if err != nil {
t.Error(err)
}
result := resp.Json()
token := result.Get("data.token")
if !token.Exists() {
t.Error("data.token is not exists")
}
ses.Header.Add("Authorization", token.String())
return ses
}

View File

@ -3,6 +3,7 @@ package logic
import (
"fmt"
"fusenapi/server/home-user-auth/internal/types"
fstests "fusenapi/utils/tests"
"testing"
"github.com/474420502/requests"
@ -15,7 +16,7 @@ func TestCaseUserAddAddress(t *testing.T) {
var result gjson.Result
// 获取 session,并携带 JWT token
ses := GetSesssionWithUserToken(t, gserver)
ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port)
// 构建新增地址请求体
addrReq := types.RequestAddAddress{

View File

@ -2,6 +2,7 @@ package logic
import (
"fmt"
fstests "fusenapi/utils/tests"
"testing"
"github.com/474420502/requests"
@ -14,7 +15,7 @@ func TestCaseAddressList(t *testing.T) {
var result gjson.Result
// 获取 session并携带 JWT token
ses := GetSesssionWithUserToken(t, gserver)
ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port)
// 向服务器发送 GET 请求,获取用户地址列表
resp, err = ses.Get(fmt.Sprintf("http://%s:%d/user/address-list", cnf.Host, cnf.Port)).TestExecute(gserver)

View File

@ -2,6 +2,7 @@ package logic
import (
"fmt"
fstests "fusenapi/utils/tests"
"testing"
"github.com/474420502/requests"
@ -14,7 +15,7 @@ func TestCaseBasicInfoLogic(t *testing.T) {
var result gjson.Result
// 获取 session并携带 JWT token
ses := GetSesssionWithUserToken(t, gserver)
ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port)
// 向服务器发送 GET 请求,获取用户基本信息
resp, err = ses.Get(fmt.Sprintf("http://%s:%d/user/basic-info", cnf.Host, cnf.Port)).TestExecute(gserver)

View File

@ -2,6 +2,7 @@ package logic
import (
"fmt"
fstests "fusenapi/utils/tests"
"testing"
"github.com/474420502/requests"
@ -15,7 +16,7 @@ func TestCaseUserFontsLogic(t *testing.T) {
var result gjson.Result
// 获取 session并携带 JWT token
ses := GetSesssionWithUserToken(t, gserver)
ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port)
// 向服务器发送 GET 请求,获取字体列表
resp, err = ses.Get(fmt.Sprintf("http://%s:%d/user/fonts", cnf.Host, cnf.Port)).TestExecute(gserver)

View File

@ -2,6 +2,7 @@ package logic
import (
"fmt"
fstests "fusenapi/utils/tests"
"testing"
"github.com/474420502/requests"
@ -14,7 +15,7 @@ func TestCaseGetTypeLogic(t *testing.T) {
var result gjson.Result
// 获取 session并携带 JWT token
ses := GetSesssionWithUserToken(t, gserver)
ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port)
// 向服务器发送 GET 请求,获取用户类型信息
resp, err = ses.Get(fmt.Sprintf("http://%s:%d/user/get-type", cnf.Host, cnf.Port)).TestExecute(gserver)

View File

@ -3,6 +3,7 @@ package logic
import (
"fmt"
"fusenapi/server/home-user-auth/internal/types"
fstests "fusenapi/utils/tests"
"testing"
"github.com/474420502/requests"
@ -15,7 +16,7 @@ func TestCaseLogic(t *testing.T) {
var result gjson.Result
// 获取 session并携带 JWT token
ses := GetSesssionWithUserToken(t, gserver)
ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port)
// 向服务器发送 GET 请求,获取用户类型信息
tp := ses.Post(fmt.Sprintf("http://%s:%d/user/order-delete", cnf.Host, cnf.Port))

View File

@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"fusenapi/server/home-user-auth/internal/types"
fstests "fusenapi/utils/tests"
"testing"
"github.com/474420502/requests"
@ -16,7 +17,7 @@ func TestCaseUserSaveBasicinfoLogic(t *testing.T) {
var result gjson.Result
// 获取 session并携带 JWT token
ses := GetSesssionWithUserToken(t, gserver)
ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port)
var tp *requests.Temporary
tp = ses.Get(fmt.Sprintf("http://%s:%d/user/basic-info", cnf.Host, cnf.Port))

View File

@ -2,6 +2,7 @@ package logic
import (
"fmt"
fstests "fusenapi/utils/tests"
"testing"
"github.com/474420502/requests"
@ -14,7 +15,7 @@ func TestCaseUserStatusConfigLogic(t *testing.T) {
var result gjson.Result
// 获取 session并携带 JWT token
ses := GetSesssionWithUserToken(t, gserver)
ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port)
// 向服务器发送 GET 请求,获取用户类型信息
resp, err = ses.Post(fmt.Sprintf("http://%s:%d/user/status-config", cnf.Host, cnf.Port)).TestExecute(gserver)

View File

@ -53,7 +53,7 @@ func WetSetSettingHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
userinfo = &auth.UserInfo{UserId: 0, GuestId: 0}
}
var req types.RequestFaq
var req types.RequestWebSet
// 如果端点有请求结构体则使用httpx.Parse方法从HTTP请求体中解析请求数据
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &basic.Response{

View File

@ -1,6 +1,7 @@
package logic
import (
"encoding/json"
"fusenapi/constants"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
@ -29,53 +30,57 @@ func NewWetSetSettingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Wet
}
}
var TagTexts = map[int]map[string]string{
1: {"title": "order", "icon": "faq/order.png", "icon_name": "orders"},
2: {"title": "Shipping", "icon": "faq/shipping.png", "icon_name": "delivery"},
3: {"title": "Payment", "icon": "faq/payment.png", "icon_name": "wallet"},
4: {"title": "Return", "icon": "faq/return.png", "icon_name": "freight"},
}
func (l *WetSetSettingLogic) WetSetSetting(req *types.RequestFaq, userinfo *auth.UserInfo) (resp *basic.Response) {
func (l *WetSetSettingLogic) WetSetSetting(req *types.RequestWebSet, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
switch req.Type {
case "faq":
typeConf := constants.TypeWebSet(req.Type)
result := make(map[string]interface{})
result["title"] = "Common Problem"
result["introduction"] = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout."
lists := make([]map[string]interface{}, 0)
for tagID, tagText := range TagTexts {
faqs, err := l.svcCtx.AllModels.FsFaq.FindOneByTagId(l.ctx, tagID, int64(constants.STATUS_ON))
if err == gorm.ErrRecordNotFound {
return resp.SetStatus(basic.CodeDbRecordNotFoundErr)
}
// items := getFaqItems(tagID)
for k, item := range items {
content := strings.Split(item.Content, "\n")
items[k].Content = content
}
res := make(map[string]interface{})
res["title"] = tagText["title"]
res["icon"] = tagText["icon"]
res["icon_name"] = tagText["icon_name"]
res["items"] = items
lists = append(lists, res)
//如果是这三个配置项 则读取缓存
var result map[string]interface{}
data, err := l.svcCtx.AllModels.FsWebSet.FindValueByKey(l.ctx, string(typeConf))
if err != nil {
if err == gorm.ErrRecordNotFound {
return resp.SetStatus(basic.CodeDbRecordNotFoundErr)
}
result["list"] = lists
return resp.SetStatus(basic.CodeOK, result)
case "clause":
case "policy":
default:
return resp.SetStatus(basic.CodeDbSqlErr)
}
//读取配置项
err = json.Unmarshal([]byte(*data.Value), &result)
if err != nil {
return resp.SetStatus(basic.CodeJsonErr)
}
//组装配置项的内容数据
for k, v := range result["list"].(map[string]interface{}) {
//按空格分隔内容
result["list"].(map[string]interface{})[k].(map[string]interface{})["content"] = strings.Split(v.(string), "\n")
}
// TODO: 缓存
if typeConf == constants.CLAUSE_CONFIG || typeConf == constants.FAQ_CONFIG || typeConf == constants.POLICY_CONFIG {
// cache := redis.NewClient(&redis.Options{
// Addr: "localhost:6379",
// Password: "", // no password set
// DB: 0, // use default DB
// })
// if cache.Exists(ctx.Query("type")).Val() > 0 {
// result = cache.HGetAll(ctx.Query("type")).Val()
// } else {
// //读取配置项
// model := WebSet{Key: typeStr}
// db.First(&model)
// result = json.Unmarshal([]byte(model.Value), &result)
// //组装配置项的内容数据
// for k, v := range result["list"].(map[string]interface{}) {
// //按空格分隔内容
// result["list"].(map[string]interface{})[k].(map[string]interface{})["content"] = strings.Split(v.(string), "\n")
// }
// cache.HMSet(ctx.Query("type"), result)
// }
} else {
}
return resp.SetStatus(basic.CodeOK)
}

View File

@ -31,6 +31,10 @@ func NewServiceContext(c config.Config) *ServiceContext {
func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
AuthKey := r.Header.Get("Authorization")
if AuthKey == "" {
return nil, nil
}
if len(AuthKey) <= 50 {
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
}

View File

@ -5,7 +5,7 @@ import (
"fusenapi/utils/basic"
)
type RequestFaq struct {
type RequestWebSet struct {
Type string `form:"type"`
}

View File

@ -0,0 +1,35 @@
package logic
import (
"fmt"
"fusenapi/server/webset/internal/config"
"fusenapi/server/webset/internal/handler"
"fusenapi/server/webset/internal/svc"
"log"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var testConfigFile = "../etc/wetset.yaml"
var cnf config.Config
var gserver *rest.Server
func init() {
log.SetFlags(log.Llongfile)
gserver = GetTestServer(testConfigFile)
}
func GetTestServer(testConfigFile string) *rest.Server {
conf.MustLoad(testConfigFile, &cnf)
server := rest.MustNewServer(cnf.RestConf)
defer server.Stop()
ctx := svc.NewServiceContext(cnf)
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", cnf.Host, cnf.Port)
return server
}

View File

@ -0,0 +1,47 @@
package logic
import (
"fmt"
fstests "fusenapi/utils/tests"
"log"
"testing"
"github.com/474420502/requests"
"github.com/tidwall/gjson"
)
func TestWetSetLogic(t *testing.T) {
var err error
var resp *requests.Response
var result gjson.Result
// 获取 session并携带 JWT token
ses := fstests.GetSesssion()
// 向服务器发送 GET 请求,获取 cookie 信息
resp, err = ses.Get(fmt.Sprintf("http://%s:%d/wet-set/setting", cnf.Host, cnf.Port)).TestExecute(gserver)
if err != nil {
t.Error(err)
}
// 使用 gjson 解析返回的 json 数据
result = resp.Json() // gjson
log.Println(result)
// 检查返回值中的 code 字段是否存在,并且值是否为 200
code := result.Get("code").Int()
if code != 200 {
t.Errorf("Invalid code value: %d", code)
}
// 检查返回值中的 msg 字段是否存在,并且值是否为 "success"
msg := result.Get("msg").String()
if msg != "success" {
t.Errorf(`Invalid msg value: "%s"`, msg)
}
// 检查返回值中的 data 字段是否存在,并且值是否符合预期
token := result.Get("data.token").String()
if len(token) == 0 {
t.Error("Missing token field")
}
}

View File

@ -11,10 +11,10 @@ import "basic.api"
service wetset {
@handler WetSetSettingHandler
get /web-set/setting(RequestFaq) returns (response);
get /web-set/setting(RequestWebSet) returns (response);
}
type RequestFaq {
type RequestWebSet {
Type string `form:"type"`
}

View File

@ -9,32 +9,32 @@ type StatusResponse struct {
var (
CodeOK = &StatusResponse{200, "success"} // 成功
CodeApiErr = &StatusResponse{500, "api error"} // API错误
CodeSaveErr = &StatusResponse{501, "fail to save"} // 保存失败
CodeSaveErr = &StatusResponse{501, "failed to save"} // 保存失败
CodeServiceErr = &StatusResponse{510, "server logic error"} // 服务逻辑错误
CodeUnAuth = &StatusResponse{401, "unauthorized"} // 未授权
CodeEmailNotFoundErr = &StatusResponse{5050, "the email was not found"} // 未找到email
CodeUserIdNotFoundErr = &StatusResponse{5051, "the user was not found"} // 未找到用户
CodePasswordErr = &StatusResponse{5052, "invalid password"} // 无效密码
CodeEmailNotFoundErr = &StatusResponse{5050, "email not found"} // 未找到email
CodeUserIdNotFoundErr = &StatusResponse{5051, "user not found"} // 未找到用户
CodePasswordErr = &StatusResponse{5052, "invalid password"} // 无效密码
CodeSafeValueRangeErr = &StatusResponse{5040, "the value was not in values"} // 值不在范围内
CodeSafeValueRangeErr = &StatusResponse{5040, "value not in range"} // 值不在范围内
CodeOrderNotFoundErr = &StatusResponse{5030, "the order not found"} //未找到订单
CodeOrderNotCancelledErr = &StatusResponse{5031, "The current order cannot be cancelled"} // 当前订单无法取消
CodeOrderNotFoundErr = &StatusResponse{5030, "order not found"} //未找到订单
CodeOrderNotCancelledErr = &StatusResponse{5031, "current order cannot be cancelled"} // 当前订单无法取消
CodePayNotFoundErr = &StatusResponse{5020, "The pay not found"} // 支付信息无法查询
CodePayCancelOk = &StatusResponse{5021, "Cancel successfully"} // 支付取消
CodePayCancelNotOk = &StatusResponse{5022, "Cancel failure"} // 支付取消
CodePayNotFoundErr = &StatusResponse{5020, "pay info not found"} // 支付信息无法查询
CodePayCancelOk = &StatusResponse{5021, "cancellation successful"} // 支付取消成功
CodePayCancelNotOk = &StatusResponse{5022, "cancellation failed"} // 支付取消失败
CodeGuestDupErr = &StatusResponse{5010, "the user is already a guest user and does not need to apply again"} // 用户已经是访客用户,不需要重复申请
CodeGuestGenErr = &StatusResponse{5011, "serialization failed for guest_id of the visitor"} // 访客ID序列化失败
CodeGuestDupErr = &StatusResponse{5010, "user is already guest and does not need to reapply"} // 用户已经是访客用户,无需重复申请
CodeGuestGenErr = &StatusResponse{5011, "serialization failed for guest ID"} // 访客ID序列化失败
CodeDbUpdateErr = &StatusResponse{5000, "update database error"} // 数据库更新错误
// 5001
CodeRequestParamsErr = &StatusResponse{5002, "invalid request param"} // 请求参数无效
CodeDbRecordNotFoundErr = &StatusResponse{5003, "db record not found"} //未在数据库中找到记录
CodeDbCreateErr = &StatusResponse{5004, "create one in database error"} // 在数据库中创建错误
CodeDbSqlErr = &StatusResponse{5005, "database is error"} // 数据库错误
CodeDbUpdateErr = &StatusResponse{5000, "database update error"} // 数据库更新错误
CodeRequestParamsErr = &StatusResponse{5002, "invalid request parameters"} // 请求参数无效
CodeDbRecordNotFoundErr = &StatusResponse{5003, "database record not found"} //数据库中未找到记录
CodeDbCreateErr = &StatusResponse{5004, "failed to create record in database"} // 数据库中创建记录失败
CodeDbSqlErr = &StatusResponse{5005, "database error"} // 数据库错误
CodeJsonErr = &StatusResponse{5006, "JSON error"} // JSON解析错误
)
type Response struct {

57
utils/tests/basic.go Normal file
View File

@ -0,0 +1,57 @@
package fstests
import (
"fmt"
"testing"
"github.com/474420502/requests"
)
func GetSesssion() *requests.Session {
ses := requests.NewSession()
return ses
}
func GetSesssionWithUserToken(t *testing.T, server requests.ITestServer, Host string, Port int) *requests.Session {
ses := requests.NewSession()
tp := ses.Post(fmt.Sprintf("http://%s:%d/user/login", Host, Port))
tp.SetBodyJson(map[string]interface{}{
"name": "devenv@sina.cn",
"pwd": "$2y$13$6UFDMZQMEfqFYiNLpiUCi.B3fpvGEamPAjIgzUqv/u7jT05nB3pOC",
})
resp, err := tp.TestExecute(server)
if err != nil {
t.Error(err)
}
result := resp.Json()
code := result.Get("code").Int()
if code != 200 {
t.Error("code is not 200")
}
token := result.Get("data.token")
if !token.Exists() {
t.Error("data.token is not exists")
}
ses.Header.Add("Authorization", token.String())
return ses
}
func GetSesssionWithGuestToken(t *testing.T, server requests.ITestServer, Host string, Port int) *requests.Session {
ses := requests.NewSession()
tp := ses.Post(fmt.Sprintf("http://%s:%d/accept/cookie", Host, Port))
resp, err := tp.TestExecute(server)
if err != nil {
t.Error(err)
}
result := resp.Json()
token := result.Get("data.token")
if !token.Exists() {
t.Error("data.token is not exists")
}
ses.Header.Add("Authorization", token.String())
return ses
}