From 7dcdb2255616711298430f6e9b382811e2ba8cc7 Mon Sep 17 00:00:00 2001 From: flswld Date: Tue, 1 Aug 2023 02:59:02 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=BC=E5=AE=B9=E5=AE=98=E6=96=B9=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E5=99=A8sdk=E8=B4=A6=E5=8F=B7=E9=AA=8C=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/gate/application.toml | 1 + common/config/config.go | 1 + dispatch/controller/controller.go | 1 + dispatch/controller/dispatch_controller.go | 40 ++--- dispatch/controller/gate_controller.go | 166 ++++++++++++++++++--- dispatch/dao/account_redis.go | 37 +++++ gate/net/session.go | 41 +++-- 7 files changed, 235 insertions(+), 52 deletions(-) diff --git a/cmd/gate/application.toml b/cmd/gate/application.toml index eed218bf..da9a0cd6 100644 --- a/cmd/gate/application.toml +++ b/cmd/gate/application.toml @@ -7,6 +7,7 @@ version = "300,310,320" # 支持的客户端协议版本号 三位数字 多个 gate_tcp_mq_addr = "127.0.0.1" # 访问网关tcp直连消息队列的地址 填网关的内网地址 gate_tcp_mq_port = 33333 login_sdk_url = "http://127.0.0.1:8080" # 网关登录验证token的sdk服务器地址 目前填dispatch的内网地址 +login_sdk_account_key = "" # sdk服务器账号验证的签名密钥 [logger] level = "DEBUG" diff --git a/common/config/config.go b/common/config/config.go index 6cf3aeec..0a531977 100644 --- a/common/config/config.go +++ b/common/config/config.go @@ -49,6 +49,7 @@ type Hk4e struct { GateTcpMqAddr string `toml:"gate_tcp_mq_addr"` // 访问网关tcp直连消息队列的地址 填网关的内网地址 GateTcpMqPort int32 `toml:"gate_tcp_mq_port"` LoginSdkUrl string `toml:"login_sdk_url"` // 网关登录验证token的sdk服务器地址 目前填dispatch的内网地址 + LoginSdkAccountKey string `toml:"login_sdk_account_key"` // sdk服务器账号验证的签名密钥 LoadSceneLuaConfig bool `toml:"load_scene_lua_config"` // 是否加载场景详情LUA配置数据 DispatchUrl string `toml:"dispatch_url"` // 二级dispatch地址 将域名改为dispatch的外网地址 ForwardRegionUrl string `toml:"forward_region_url"` // 转发的一级dispatch地址 diff --git a/dispatch/controller/controller.go b/dispatch/controller/controller.go index 40efa61c..d0503b08 100644 --- a/dispatch/controller/controller.go +++ b/dispatch/controller/controller.go @@ -168,6 +168,7 @@ func (c *Controller) registerRouter() { } engine.Use(c.authorize()) engine.POST("/gate/token/verify", c.gateTokenVerify) + engine.POST("/gate/player/info", c.gatePlayerInfo) port := config.GetConfig().HttpPort addr := ":" + strconv.Itoa(int(port)) err := engine.Run(addr) diff --git a/dispatch/controller/dispatch_controller.go b/dispatch/controller/dispatch_controller.go index 4f8df536..2aa20f57 100644 --- a/dispatch/controller/dispatch_controller.go +++ b/dispatch/controller/dispatch_controller.go @@ -139,8 +139,8 @@ func GetRegionCurr(ec2b *random.Ec2b, gateServerAddr *api.GateServerAddr, stopSe return regionCurr } -// dispatch错误返回 -func (c *Controller) dispatchError(ctx *gin.Context, dispatchLevel uint8) { +// dispatch请求错误响应 +func (c *Controller) dispatchReqErrorRsp(ctx *gin.Context, dispatchLevel uint8) { if dispatchLevel == 1 { // query_region_list _, _ = ctx.Writer.WriteString("CP///////////wE=") @@ -158,7 +158,7 @@ func (c *Controller) queryRegionList(ctx *gin.Context) { regionListData, err := pb.Marshal(regionList) if err != nil { logger.Error("pb marshal QueryRegionListHttpRsp error: %v", err) - c.dispatchError(ctx, 1) + c.dispatchReqErrorRsp(ctx, 1) return } regionListBase64 := base64.StdEncoding.EncodeToString(regionListData) @@ -167,7 +167,7 @@ func (c *Controller) queryRegionList(ctx *gin.Context) { regionListBase64, err := c.queryRegionListForwardMode(ctx.Request.RequestURI) if err != nil { logger.Error("get forward dispatch region list info error: %v", err) - c.dispatchError(ctx, 1) + c.dispatchReqErrorRsp(ctx, 1) return } _, _ = ctx.Writer.WriteString(regionListBase64) @@ -178,12 +178,12 @@ func (c *Controller) queryRegionList(ctx *gin.Context) { func (c *Controller) queryCurRegion(ctx *gin.Context) { versionName := ctx.Query("version") if versionName == "" { - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } version, versionStr := c.getClientVersionByName(versionName) if version == 0 { - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } gateServerAddr, err := c.discovery.GetGateServerAddr(ctx.Request.Context(), &api.GetGateServerAddrReq{ @@ -191,7 +191,7 @@ func (c *Controller) queryCurRegion(ctx *gin.Context) { }) if err != nil { logger.Error("get gate server addr error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } var regionCurr *proto.QueryCurrRegionHttpRsp = nil @@ -200,7 +200,7 @@ func (c *Controller) queryCurRegion(ctx *gin.Context) { stopServerInfo, err := c.discovery.GetStopServerInfo(ctx.Request.Context(), &api.GetStopServerInfoReq{ClientIpAddr: clientIp}) if err != nil { logger.Error("get stop server info error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } regionCurr = GetRegionCurr(c.ec2b, gateServerAddr, stopServerInfo) @@ -208,14 +208,14 @@ func (c *Controller) queryCurRegion(ctx *gin.Context) { regionCurr, err = c.queryCurRegionForwardMode(ctx.Request.RequestURI, version, ctx.Query("key_id"), gateServerAddr) if err != nil { logger.Error("get forward dispatch curr region info error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } } regionCurrData, err := pb.Marshal(regionCurr) if err != nil { logger.Error("pb marshal QueryCurrRegionHttpRsp error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } if version < 275 { @@ -229,7 +229,7 @@ func (c *Controller) queryCurRegion(ctx *gin.Context) { encPubPrivKey, exist := c.encRsaKeyMap[keyId] if !exist { logger.Error("can not found key id: %v", keyId) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } chunkSize := 256 - 11 @@ -243,30 +243,30 @@ func (c *Controller) queryCurRegion(ctx *gin.Context) { pubKey, err := endec.RsaParsePubKeyByPrivKey(encPubPrivKey) if err != nil { logger.Error("parse rsa pub key error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } privKey, err := endec.RsaParsePrivKey(encPubPrivKey) if err != nil { logger.Error("parse rsa priv key error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } encrypt, err := endec.RsaEncrypt(chunk, pubKey) if err != nil { logger.Error("rsa enc error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } decrypt, err := endec.RsaDecrypt(encrypt, privKey) if err != nil { logger.Error("rsa dec error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } if bytes.Compare(decrypt, chunk) != 0 { logger.Error("rsa dec test fail") - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } encryptedRegionInfo = append(encryptedRegionInfo, encrypt...) @@ -274,24 +274,24 @@ func (c *Controller) queryCurRegion(ctx *gin.Context) { signPrivkey, err := endec.RsaParsePrivKey(c.signRsaKey) if err != nil { logger.Error("parse rsa priv key error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } signData, err := endec.RsaSign(regionCurrData, signPrivkey) if err != nil { logger.Error("rsa sign error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } ok, err := endec.RsaVerify(regionCurrData, signData, &signPrivkey.PublicKey) if err != nil { logger.Error("rsa verify error: %v", err) - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } if !ok { logger.Error("rsa verify test fail") - c.dispatchError(ctx, 2) + c.dispatchReqErrorRsp(ctx, 2) return } rsp := &httpapi.QueryCurRegionRspJson{ diff --git a/dispatch/controller/gate_controller.go b/dispatch/controller/gate_controller.go index 832d7d27..b0f0585c 100644 --- a/dispatch/controller/gate_controller.go +++ b/dispatch/controller/gate_controller.go @@ -1,63 +1,183 @@ package controller import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "fmt" "net/http" "strconv" "time" + "hk4e/common/config" + "hk4e/dispatch/model" "hk4e/pkg/logger" "github.com/gin-gonic/gin" ) +// gate请求错误响应 +func (c *Controller) gateReqErrorRsp(ctx *gin.Context) { + ctx.JSON(http.StatusOK, gin.H{"retcode": -101, "message": "系统错误", "data": nil}) +} + type TokenVerifyReq struct { - AccountId string `json:"accountId"` - AccountToken string `json:"accountToken"` + AppID uint32 `json:"app_id"` + ChannelID uint32 `json:"channel_id"` + OpenID string `json:"open_id"` + ComboToken string `json:"combo_token"` + Sign string `json:"sign"` + Region string `json:"region"` } type TokenVerifyRsp struct { - Valid bool `json:"valid"` - Forbid bool `json:"forbid"` - ForbidEndTime uint32 `json:"forbidEndTime"` - PlayerID uint32 `json:"playerID"` + RetCode int32 `json:"retcode"` + Message string `json:"message"` + Data struct { + Guest bool `json:"guest"` + AccountType uint32 `json:"account_type"` + AccountUid uint32 `json:"account_uid"` + IpInfo struct { + CountryCode string `json:"country_code"` + } `json:"ip_info"` + } `json:"data"` } func (c *Controller) gateTokenVerify(ctx *gin.Context) { - verifyFail := func(playerID uint32) { - ctx.JSON(http.StatusOK, &TokenVerifyRsp{ - Valid: false, - Forbid: false, - ForbidEndTime: 0, - PlayerID: playerID, - }) - } tokenVerifyReq := new(TokenVerifyReq) err := ctx.ShouldBindJSON(tokenVerifyReq) if err != nil { - verifyFail(0) + c.gateReqErrorRsp(ctx) return } logger.Info("gate token verify, req: %v", tokenVerifyReq) - accountId, err := strconv.ParseUint(tokenVerifyReq.AccountId, 10, 64) + signStr := fmt.Sprintf("app_id=%d&channel_id=%d&combo_token=%s&open_id=%s", 1, 1, tokenVerifyReq.ComboToken, tokenVerifyReq.OpenID) + signHash := hmac.New(sha256.New, []byte(config.GetConfig().Hk4e.LoginSdkAccountKey)) + signHash.Write([]byte(signStr)) + signData := signHash.Sum(nil) + sign := hex.EncodeToString(signData) + if tokenVerifyReq.Sign != sign { + c.gateReqErrorRsp(ctx) + return + } + accountId, err := strconv.Atoi(tokenVerifyReq.OpenID) if err != nil { - verifyFail(0) + c.gateReqErrorRsp(ctx) return } - account, err := c.dao.QueryAccountByField("AccountID", accountId) + account, err := c.dao.QueryAccountByField("AccountID", uint64(accountId)) if err != nil || account == nil { - verifyFail(0) + c.gateReqErrorRsp(ctx) return } - if tokenVerifyReq.AccountToken != account.ComboToken { - verifyFail(account.PlayerID) + if tokenVerifyReq.ComboToken != account.ComboToken { + c.gateReqErrorRsp(ctx) return } if time.Now().UnixMilli()-int64(account.ComboTokenCreateTime) > time.Hour.Milliseconds()*24 { - verifyFail(account.PlayerID) + c.gateReqErrorRsp(ctx) return } ctx.JSON(http.StatusOK, &TokenVerifyRsp{ - Valid: true, + RetCode: 0, + Message: "OK", + Data: struct { + Guest bool `json:"guest"` + AccountType uint32 `json:"account_type"` + AccountUid uint32 `json:"account_uid"` + IpInfo struct { + CountryCode string `json:"country_code"` + } `json:"ip_info"` + }{ + Guest: false, + AccountType: 1, + AccountUid: uint32(accountId), + IpInfo: struct { + CountryCode string `json:"country_code"` + }{ + CountryCode: "US", + }, + }, + }) +} + +type PlayerInfoReq struct { + AccountId string `json:"accountId"` +} + +type PlayerInfoRsp struct { + RetCode int32 `json:"retcode"` + Message string `json:"message"` + Data struct{} `json:"data"` + Forbid bool `json:"forbid"` + ForbidEndTime uint32 `json:"forbidEndTime"` + PlayerID uint32 `json:"playerID"` +} + +func (c *Controller) gatePlayerInfo(ctx *gin.Context) { + playerInfoReq := new(PlayerInfoReq) + err := ctx.ShouldBindJSON(playerInfoReq) + if err != nil { + c.gateReqErrorRsp(ctx) + return + } + logger.Info("gate player info, req: %v", playerInfoReq) + accountId, err := strconv.Atoi(playerInfoReq.AccountId) + if err != nil { + c.gateReqErrorRsp(ctx) + return + } + account, err := c.dao.QueryAccountByField("AccountID", uint64(accountId)) + if err != nil { + c.gateReqErrorRsp(ctx) + return + } + if account == nil { + // 外部sdk登录 + redisAccountId, err := c.dao.GetAccountId() + if err != nil { + logger.Error("get account id error: %v", err) + c.gateReqErrorRsp(ctx) + return + } + if uint32(accountId) > redisAccountId { + // 临时修正自增id + err := c.dao.SetAccountId(uint32(accountId)) + if err != nil { + logger.Error("set account id error: %v", err) + c.gateReqErrorRsp(ctx) + return + } + } + // 补账号记录 + playerID, err := c.dao.GetNextYuanShenUid() + if err != nil { + logger.Error("get next player id error: %v", err) + c.gateReqErrorRsp(ctx) + return + } + regAccount := &model.Account{ + AccountID: uint32(accountId), + Username: "", + Password: "", + PlayerID: playerID, + Token: "", + ComboToken: "", + Forbid: false, + ForbidEndTime: 0, + } + _, err = c.dao.InsertAccount(regAccount) + if err != nil { + logger.Error("insert account error: %v", err) + c.gateReqErrorRsp(ctx) + return + } + account = regAccount + } + ctx.JSON(http.StatusOK, &PlayerInfoRsp{ + RetCode: 0, + Message: "OK", + Data: struct{}{}, Forbid: account.Forbid, ForbidEndTime: account.ForbidEndTime, PlayerID: account.PlayerID, diff --git a/dispatch/dao/account_redis.go b/dispatch/dao/account_redis.go index f537fa0e..60863df8 100644 --- a/dispatch/dao/account_redis.go +++ b/dispatch/dao/account_redis.go @@ -2,6 +2,7 @@ package dao import ( "context" + "strconv" ) const RedisPlayerKeyPrefix = "HK4E" @@ -17,6 +18,14 @@ func (d *Dao) GetNextAccountId() (uint32, error) { return d.redisInc(RedisPlayerKeyPrefix + ":" + AccountIdRedisKey) } +func (d *Dao) GetAccountId() (uint32, error) { + return d.redisGet(RedisPlayerKeyPrefix + ":" + AccountIdRedisKey) +} + +func (d *Dao) SetAccountId(accountId uint32) error { + return d.redisSet(RedisPlayerKeyPrefix+":"+AccountIdRedisKey, accountId) +} + func (d *Dao) GetNextYuanShenUid() (uint32, error) { return d.redisInc(RedisPlayerKeyPrefix + ":" + YuanShenUidRedisKey) } @@ -60,3 +69,31 @@ func (d *Dao) redisInc(keyName string) (uint32, error) { } return uint32(id), nil } + +func (d *Dao) redisGet(keyName string) (uint32, error) { + var result = "" + var err error = nil + if d.redisCluster != nil { + result, err = d.redisCluster.Get(context.TODO(), keyName).Result() + } else { + result, err = d.redis.Get(context.TODO(), keyName).Result() + } + if err != nil { + return 0, err + } + value, err := strconv.Atoi(result) + if err != nil { + return 0, err + } + return uint32(value), nil +} + +func (d *Dao) redisSet(keyName string, value uint32) error { + var err error = nil + if d.redisCluster != nil { + err = d.redisCluster.Set(context.TODO(), keyName, value, 0).Err() + } else { + err = d.redis.Set(context.TODO(), keyName, value, 0).Err() + } + return err +} diff --git a/gate/net/session.go b/gate/net/session.go index 5c757c12..7ce84b85 100644 --- a/gate/net/session.go +++ b/gate/net/session.go @@ -3,8 +3,11 @@ package net import ( "bytes" "context" + "crypto/hmac" + "crypto/sha256" "encoding/base64" "encoding/binary" + "encoding/hex" "fmt" "strconv" "strings" @@ -475,26 +478,46 @@ func (k *KcpConnectManager) loginFailRsp(uid uint32, retCode proto.Retcode, isFo } func (k *KcpConnectManager) doGateLogin(req *proto.GetPlayerTokenReq, session *Session) *proto.GetPlayerTokenRsp { + // 验证token + signStr := fmt.Sprintf("app_id=%d&channel_id=%d&combo_token=%s&open_id=%s", 1, 1, req.AccountToken, req.AccountUid) + signHash := hmac.New(sha256.New, []byte(config.GetConfig().Hk4e.LoginSdkAccountKey)) + signHash.Write([]byte(signStr)) + signData := signHash.Sum(nil) + sign := hex.EncodeToString(signData) tokenVerifyRsp, err := httpclient.PostJson[controller.TokenVerifyRsp]( config.GetConfig().Hk4e.LoginSdkUrl+"/gate/token/verify", &controller.TokenVerifyReq{ - AccountId: req.AccountUid, - AccountToken: req.AccountToken, + AppID: 1, + ChannelID: 1, + OpenID: req.AccountUid, + ComboToken: req.AccountToken, + Sign: sign, + Region: "", }) if err != nil { logger.Error("verify token error: %v, account uid: %v", err, req.AccountUid) k.loginFailClose(session) return nil } - uid := tokenVerifyRsp.PlayerID - if !tokenVerifyRsp.Valid { - logger.Error("token error, uid: %v", uid) - return k.loginFailRsp(uid, proto.Retcode_RET_TOKEN_ERROR, false, 0) + if tokenVerifyRsp.RetCode != 0 { + logger.Error("token error, account id: %v", req.AccountUid) + return k.loginFailRsp(0, proto.Retcode_RET_TOKEN_ERROR, false, 0) } - // comboToken验证成功 - if tokenVerifyRsp.Forbid { + // 查询玩家账号信息 + playerInfoRsp, err := httpclient.PostJson[controller.PlayerInfoRsp]( + config.GetConfig().Hk4e.LoginSdkUrl+"/gate/player/info", + &controller.PlayerInfoReq{ + AccountId: req.AccountUid, + }) + if err != nil { + logger.Error("query player info error: %v, account uid: %v", err, req.AccountUid) + k.loginFailClose(session) + return nil + } + uid := playerInfoRsp.PlayerID + if playerInfoRsp.Forbid { // 封号通知 - return k.loginFailRsp(uid, proto.Retcode_RET_BLACK_UID, true, tokenVerifyRsp.ForbidEndTime) + return k.loginFailRsp(uid, proto.Retcode_RET_BLACK_UID, true, playerInfoRsp.ForbidEndTime) } addr := session.conn.RemoteAddr().String() addrSplit := strings.Split(addr, ":")