This commit is contained in:
laodaming
2023-06-15 12:00:32 +08:00
parent 255c3c3c88
commit 33600c48eb
40 changed files with 505 additions and 302 deletions

View File

@@ -0,0 +1,12 @@
package config
import (
"fusenapi/server/map-library/internal/types"
"github.com/zeromicro/go-zero/rest"
)
type Config struct {
rest.RestConf
SourceMysql string
Auth types.Auth
}

View File

@@ -0,0 +1,66 @@
package handler
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/server/map-library/internal/logic"
"fusenapi/server/map-library/internal/svc"
)
func GetMapLibraryListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
// 定义错误变量
err error
// 定义用户信息变量
userinfo *auth.UserInfo
)
// 解析JWT token,并对空用户进行判断
claims, err := svcCtx.ParseJwtToken(r)
// 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息
if err != nil {
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
Code: 401, // 返回401状态码,表示未授权
Message: "unauthorized", // 返回未授权信息
})
logx.Info("unauthorized:", err.Error()) // 记录错误日志
return
}
if claims != nil {
// 从token中获取对应的用户信息
userinfo, err = auth.GetUserInfoFormMapClaims(claims)
// 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息
if err != nil {
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
Code: 401,
Message: "unauthorized",
})
logx.Info("unauthorized:", err.Error())
return
}
} else {
// 如果claims为nil,则认为用户身份为白板用户
userinfo = &auth.UserInfo{UserId: 0, GuestId: 0}
}
l := logic.NewGetMapLibraryListLogic(r.Context(), svcCtx)
resp := l.GetMapLibraryList(userinfo)
// 如果响应不为nil则使用httpx.OkJsonCtx方法返回JSON响应;
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,22 @@
// Code generated by goctl. DO NOT EDIT.
package handler
import (
"net/http"
"fusenapi/server/map-library/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/map-library/list",
Handler: GetMapLibraryListHandler(serverCtx),
},
},
)
}

View File

@@ -0,0 +1,81 @@
package logic
import (
"encoding/json"
"fusenapi/model/gmodel"
"fusenapi/server/map-library/internal/svc"
"fusenapi/server/map-library/internal/types"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"time"
"context"
"github.com/zeromicro/go-zero/core/logx"
)
type GetMapLibraryListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetMapLibraryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMapLibraryListLogic {
return &GetMapLibraryListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetMapLibraryListLogic) GetMapLibraryList(userinfo *auth.UserInfo) (resp *basic.Response) {
if userinfo.GetIdType() != auth.IDTYPE_User {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first")
}
mapLibraryModel := gmodel.NewFsMapLibraryModel(l.svcCtx.MysqlConn)
mapLibraryList, err := mapLibraryModel.GetAllEnabledList(l.ctx)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get map library list")
}
if len(mapLibraryList) == 0 {
return resp.SetStatus(basic.CodeOK)
}
productTemplateTagIds := make([]int64, 0, len(mapLibraryList))
for _, v := range mapLibraryList {
productTemplateTagIds = append(productTemplateTagIds, *v.TagId)
}
//获取标签列表
productTemplateTagsModel := gmodel.NewFsProductTemplateTagsModel(l.svcCtx.MysqlConn)
templateTagList, err := productTemplateTagsModel.GetListByIds(l.ctx, productTemplateTagIds)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product template tags")
}
mapTag := make(map[int64]int)
for k, v := range templateTagList {
mapTag[v.Id] = k
}
list := make([]types.GetMapLibraryListRsp, 0, len(mapLibraryList))
for _, v := range mapLibraryList {
data := types.GetMapLibraryListRsp{
Mid: v.Id,
Ctime: time.Unix(*v.Ctime, 0).Format("2006-01-02 15:04:05"),
}
//tag拼装
if tagIndex, ok := mapTag[*v.TagId]; ok {
data.Tag = types.MapLibraryListTag{
Id: templateTagList[tagIndex].Id,
Title: *templateTagList[tagIndex].Title,
}
}
//解析info
var info types.MapLibraryListInfo
if err = json.Unmarshal([]byte(*v.Info), &info); err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "json parse info err")
}
data.Info = info
list = append(list, data)
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", list)
}

View File

@@ -0,0 +1,51 @@
package svc
import (
"errors"
"fmt"
"fusenapi/initalize"
"fusenapi/server/map-library/internal/config"
"github.com/golang-jwt/jwt"
"gorm.io/gorm"
"net/http"
)
type ServiceContext struct {
Config config.Config
MysqlConn *gorm.DB
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
MysqlConn: initalize.InitMysql(c.SourceMysql),
}
}
func (svcCxt *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
AuthKey := r.Header.Get("Authorization")
if len(AuthKey) <= 50 {
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
}
token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) {
// 检查签名方法是否为 HS256
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// 返回用于验证签名的密钥
return svcCxt.Config.Auth.AccessSecret, nil
})
if err != nil {
return nil, errors.New(fmt.Sprint("Error parsing token:", err))
}
// 验证成功返回
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New(fmt.Sprint("Invalid token", err))
}

View File

@@ -0,0 +1,138 @@
// Code generated by goctl. DO NOT EDIT.
package types
import (
"fusenapi/utils/basic"
)
type GetMapLibraryListRsp struct {
Mid int64 `json:"mid"`
Ctime string `json:"ctime"`
Tag MapLibraryListTag `json:"tag"`
Info MapLibraryListInfo `json:"info"`
}
type MapLibraryListInfo struct {
Id string `json:"id"`
Tag string `json:"tag"`
Title string `json:"title"`
Type string `json:"type"`
Text string `json:"text"`
Fill string `json:"fill"`
FontSize int64 `json:"fontSize"`
FontFamily string `json:"fontFamily"`
IfBr bool `json:"ifBr"`
IfShow bool `json:"ifShow"`
IfGroup bool `json:"ifGroup"`
MaxNum int64 `json:"maxNum"`
Rotation int64 `json:"rotation"`
Align string `json:"align"`
VerticalAlign string `json:"verticalAlign"`
Material string `json:"material"`
QRcodeType int64 `json:"QRcodeType"`
Width float64 `json:"width"`
Height float64 `json:"height"`
X float64 `json:"x"`
Y float64 `json:"y"`
Opacity float64 `json:"opacity"`
OptionalColor []MapLibraryListOptionalColorItem `json:"optionalColor"`
ZIndex int64 `json:"zIndex"`
SvgPath string `json:"svgPath"`
Follow MapLibraryListFollow `json:"follow"`
Group []MapLibraryListGroup `json:"group"`
CameraStand MapLibraryListCameraStand `json:"cameraStand"`
MaterialTime string `json:"materialTime"`
MaterialName string `json:"materialName"`
}
type MapLibraryListCameraStand struct {
X int64 `json:"x"`
Y int64 `json:"y"`
Z int64 `json:"z"`
}
type MapLibraryListGroup struct {
Tag string `json:"tag"`
Text string `json:"text"`
Title string `json:"title"`
IfBr bool `json:"ifBr"`
IfShow bool `json:"ifShow"`
MaxNum int64 `json:"maxNum"`
}
type MapLibraryListFollow struct {
Fill string `json:"fill"`
IfShow string `json:"ifShow"`
Content string `json:"content"`
}
type MapLibraryListOptionalColorItem struct {
Color string `json:"color"`
Name string `json:"name"`
Default bool `json:"default"`
}
type MapLibraryListTag struct {
Id int64 `json:"id"`
Title string `json:"title"`
}
type Response struct {
Code int `json:"code"`
Message string `json:"msg"`
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) *Response {
return &Response{
Code: Code,
Message: Message,
}
}
// Set 设置整个Response
func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response {
return &Response{
Code: Code,
Message: Message,
Data: Data,
}
}
// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数
func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response {
newResp := &Response{
Code: sr.Code,
}
if len(data) == 1 {
newResp.Data = data[0]
}
return newResp
}
// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数
func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response {
newResp := &Response{
Code: sr.Code,
Message: msg,
}
if len(data) == 1 {
newResp.Data = data[0]
}
return newResp
}