Merge branch 'develop' of gitee.com:fusenpack/fusenapi into develop

This commit is contained in:
momo 2023-11-07 14:13:14 +08:00
commit 241bed34c3
10 changed files with 254 additions and 119 deletions

View File

@ -100,7 +100,7 @@ func main() {
indexHtmlPath := vueBuild + "/index.html"
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") {
r.ParseMultipartForm(100 << 20)
r.ParseMultipartForm(500 << 20)
// 对/api开头的请求进行反向代理
proxy := httputil.NewSingleHostReverseProxy(apiURL)
proxy.ServeHTTP(w, r)
@ -179,14 +179,14 @@ func NewBackend(mux *http.ServeMux, httpAddress string, muxPaths ...string) *Bac
client := &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 300 * time.Second,
KeepAlive: 60 * time.Second,
Timeout: 1500 * time.Second,
KeepAlive: 120 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 300 * time.Second,
TLSHandshakeTimeout: 300 * time.Second,
MaxIdleConns: 200,
MaxIdleConnsPerHost: 200,
IdleConnTimeout: 600 * time.Second,
TLSHandshakeTimeout: 600 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}

View File

@ -14,8 +14,8 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
[]rest.Route{
{
Method: http.MethodPost,
Path: "/api/feishu/ticket_webhook",
Handler: TicketWebhookHandler(serverCtx),
Path: "/api/feishu/webhook",
Handler: WebhookHandler(serverCtx),
},
},
)

View File

@ -1,35 +0,0 @@
package handler
import (
"net/http"
"reflect"
"fusenapi/utils/basic"
"fusenapi/server/feishu-sync/internal/logic"
"fusenapi/server/feishu-sync/internal/svc"
"fusenapi/server/feishu-sync/internal/types"
)
func TicketWebhookHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.TicketWebhookReq
userinfo, err := basic.RequestParse(w, r, svcCtx, &req)
if err != nil {
return
}
// 创建一个业务逻辑层实例
l := logic.NewTicketWebhookLogic(r.Context(), svcCtx)
rl := reflect.ValueOf(l)
basic.BeforeLogic(w, r, rl)
resp := l.TicketWebhook(&req, userinfo)
if !basic.AfterLogic(w, r, rl, resp) {
basic.NormalAfterLogic(w, r, resp)
}
}
}

View File

@ -0,0 +1,15 @@
package handler
import (
"fusenapi/server/feishu-sync/internal/logic"
"fusenapi/server/feishu-sync/internal/svc"
"net/http"
)
func WebhookHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 创建一个业务逻辑层实例
l := logic.NewWebhookLogic(r.Context(), svcCtx)
l.Webhook(w, r)
}
}

View File

@ -1,43 +0,0 @@
package logic
import (
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"context"
"fusenapi/server/feishu-sync/internal/svc"
"fusenapi/server/feishu-sync/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type TicketWebhookLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewTicketWebhookLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TicketWebhookLogic {
return &TicketWebhookLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
// func (l *TicketWebhookLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
func (l *TicketWebhookLogic) TicketWebhook(req *types.TicketWebhookReq, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
return resp.SetStatus(basic.CodeOK)
}
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *TicketWebhookLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }

View File

@ -0,0 +1,177 @@
package logic
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"fusenapi/server/feishu-sync/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type WebhookLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewWebhookLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WebhookLogic {
return &WebhookLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
type EncryptWebhookMsg struct {
Encrypt string `json:"encrypt"` //加密的消息
}
type WebhookMsg struct {
Type string `json:"type"`
Challenge string `json:"challenge"`
Header map[string]interface{} `json:"header"`
Event map[string]interface{} `json:"event"`
}
// webhook消息事件header(body参数)基础信息
type BaseWebhookMsgHeaderType struct {
EventId string `json:"event_id"` //事件id(可作为消息唯一性确认)
EventType string `json:"event_type"` //事件类型
CreateTime string `json:"create_time"` //创建时间
Token string `json:"token"` //事件token
AppId string `json:"app_id"` //app id
TenantKey string `json:"tenant_key"` //租户key
}
func (l *WebhookLogic) Webhook(w http.ResponseWriter, r *http.Request) {
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
logx.Error("读取请求body失败", err)
return
}
defer r.Body.Close()
//计算签名
timestamp := r.Header.Get("X-Lark-Request-Timestamp")
nonce := r.Header.Get("X-Lark-Request-Nonce")
encryptKey := "DmiHQ2bHhKiR3KK4tIjLShbs13eErxKA"
signature := r.Header.Get("X-Lark-Signature")
sign := l.CalculateFeiShuWebhookSignature(timestamp, nonce, encryptKey, bodyBytes)
if signature != sign {
logx.Error("非法的消息,签名验证不通过", sign, "====", signature)
return
}
var encryptMsg EncryptWebhookMsg
if err = json.Unmarshal(bodyBytes, &encryptMsg); err != nil {
logx.Error("反序列化body失败", err, "body数据:", string(bodyBytes))
return
}
if encryptMsg.Encrypt == "" {
logx.Error("消息加密信息是空的")
return
}
//解密
realMsgBytes, err := l.DecryptFeiShuWebhookMsg(encryptMsg.Encrypt, encryptKey)
if err != nil {
logx.Error(err)
return
}
//如果只是验证http连接的消息
var webhookMsg WebhookMsg
if err = json.Unmarshal(realMsgBytes, &webhookMsg); err != nil {
logx.Error("反序列化请求body失败", err, "解密数据:", string(realMsgBytes))
return
}
//验证连接(直接返回)
if webhookMsg.Type == "url_verification" {
challengeRsp := map[string]string{
"challenge": webhookMsg.Challenge,
}
b, _ := json.Marshal(challengeRsp)
w.Write(b)
return
}
headerByte, err := json.Marshal(webhookMsg.Header)
if err != nil {
logx.Error("序列化请求体header失败:", err)
return
}
var msgHeader BaseWebhookMsgHeaderType
if err = json.Unmarshal(headerByte, &msgHeader); err != nil {
logx.Error("反序列化请求体中的header失败", err)
return
}
logx.Info("触发webhook:", msgHeader.EventType)
switch msgHeader.EventType {
case "contact.custom_attr_event.updated_v3": //成员字段管理属性变更事件
case "contact.department.created_v3": //部门新建
case "contact.department.deleted_v3": //部门删除
case "contact.department.updated_v3": //部门信息变化
case "contact.employee_type_enum.actived_v3": //启动人员类型事件
case "contact.employee_type_enum.created_v3": //新建人员类型事件
case "contact.employee_type_enum.deactivated_v3": //停用人员类型事件
case "contact.employee_type_enum.deleted_v3": //删除人员类型事件
case "contact.employee_type_enum.updated_v3": //修改人员类型名称事件
case "contact.scope.updated_v3": //通讯录范围权限被更新
case "contact.user.created_v3": //员工入职
case "contact.user.deleted_v3": //员工离职
case "contact.user.updated_v3": //员工信息变化
}
return
}
// 计算签名
func (l *WebhookLogic) CalculateFeiShuWebhookSignature(timestamp, nonce, encryptKey string, body []byte) string {
var b strings.Builder
b.WriteString(timestamp)
b.WriteString(nonce)
b.WriteString(encryptKey)
b.Write(body) //bodystring 指整个请求体,不要在反序列化后再计算
bs := []byte(b.String())
h := sha256.New()
h.Write(bs)
bs = h.Sum(nil)
sig := fmt.Sprintf("%x", bs)
return sig
}
// 解密事件消息
func (l *WebhookLogic) DecryptFeiShuWebhookMsg(encrypt string, encryptKey string) ([]byte, error) {
buf, err := base64.StdEncoding.DecodeString(encrypt)
if err != nil {
return nil, fmt.Errorf("base64StdEncode Error[%v]", err)
}
if len(buf) < aes.BlockSize {
return nil, errors.New("cipher too short")
}
keyBs := sha256.Sum256([]byte(encryptKey))
block, err := aes.NewCipher(keyBs[:sha256.Size])
if err != nil {
return nil, fmt.Errorf("AESNewCipher Error[%v]", err)
}
iv := buf[:aes.BlockSize]
buf = buf[aes.BlockSize:]
// CBC mode always works in whole blocks.
if len(buf)%aes.BlockSize != 0 {
return nil, errors.New("ciphertext is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(buf, buf)
n := strings.Index(string(buf), "{")
if n == -1 {
n = 0
}
m := strings.LastIndex(string(buf), "}")
if m == -1 {
m = len(buf) - 1
}
return buf[n : m+1], nil
}

View File

@ -5,19 +5,6 @@ import (
"fusenapi/utils/basic"
)
type TicketWebhookReq struct {
Ts string `json:"ts"` //webhook时间
Uuid string `json:"uuid"` //事件唯一标识
Token string `json:"token"` //即Verification Token
Event Event `json:"event"` //事件
}
type Event struct {
AppId string `json:"app_id"`
AppTicket string `json:"app_ticket"`
Type string `json:"type"`
}
type Request struct {
}

View File

@ -1,6 +1,9 @@
package logic
import (
"fusenapi/constants"
"fusenapi/model/gmodel"
"fusenapi/service/repositories"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
@ -34,13 +37,57 @@ func (l *GetCartNumLogic) GetCartNum(req *types.Request, userinfo *auth.UserInfo
if !userinfo.IsUser() {
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in")
}
count, err := l.svcCtx.AllModels.FsShoppingCart.CountUserCart(l.ctx, userinfo.UserId)
currentPage := constants.DEFAULT_PAGE
limit := 1000
//获取用户购物车列表
carts, total, err := l.svcCtx.AllModels.FsShoppingCart.GetAllCartsByParam(l.ctx, gmodel.GetAllCartsByParamReq{
UserId: userinfo.UserId,
Sort: "id DESC",
Page: currentPage,
Limit: limit,
})
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "failed to get cart num")
return resp.SetStatusWithMessage(basic.CodeDbSqlErr, "system err:failed to get your shopping carts")
}
var (
mapSize = make(map[int64]gmodel.FsProductSize)
mapModel = make(map[int64]gmodel.FsProductModel3d)
mapTemplate = make(map[int64]gmodel.FsProductTemplateV2)
mapProduct = make(map[int64]gmodel.FsProduct)
mapResourceMetadata = make(map[string]interface{})
)
//获取相关信息
err = NewGetCartsLogic(l.ctx, l.svcCtx).GetRelationInfo(GetRelationInfoReq{
Carts: carts,
MapSize: mapSize,
MapModel: mapModel,
MapTemplate: mapTemplate,
MapProduct: mapProduct,
MapResourceMetadata: mapResourceMetadata,
})
if err != nil {
return resp.SetStatusWithMessage(basic.CodeServiceErr, err.Error())
}
//定义map收集变更信息
mapCartChange := make(map[int64]string)
mapSnapshot := make(map[int64]gmodel.CartSnapshot)
//校验购物车数据是否变更
err = l.svcCtx.Repositories.NewShoppingCart.VerifyShoppingCartSnapshotDataChange(repositories.VerifyShoppingCartSnapshotDataChangeReq{
Carts: carts,
MapSize: mapSize,
MapModel: mapModel,
MapTemplate: mapTemplate,
MapCartChange: mapCartChange,
MapSnapshot: mapSnapshot,
MapProduct: mapProduct,
})
if err != nil {
logx.Error("VerifyShoppingCartSnapshotDataChange err:", err.Error())
return resp.SetStatusWithMessage(basic.CodeServiceErr, "system err:failed to check shopping cart change data")
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", types.GetCartNumRsp{
TotalCount: count,
TotalCount: total - int64(len(mapCartChange)),
})
}

View File

@ -42,7 +42,7 @@ func (l *GetCartsLogic) GetCarts(req *types.GetCartsReq, userinfo *auth.UserInfo
return resp.SetStatusWithMessage(basic.CodeUnAuth, "please sign in")
}
currentPage := constants.DEFAULT_PAGE
limit := 300
limit := 1000
//获取用户购物车列表
var cartIds []int64
if req.CartId > 0 {

View File

@ -11,19 +11,6 @@ import "basic.api"
service feishu-sync {
//飞书ticket webhook事件接口
@handler TicketWebhookHandler
post /api/feishu/ticket_webhook (TicketWebhookReq) returns (response);
}
type TicketWebhookReq {
Ts string `json:"ts"` //webhook时间
Uuid string `json:"uuid"` //事件唯一标识
Token string `json:"token"` //即Verification Token
Event Event `json:"event"` //事件
}
type Event {
AppId string `json:"app_id"`
AppTicket string `json:"app_ticket"`
Type string `json:"type"`
@handler WebhookHandler
post /api/feishu/webhook(request) returns (response);
}