Skip to content

Commit

Permalink
feat: tgtoken
Browse files Browse the repository at this point in the history
  • Loading branch information
Natsume-wuhu committed Jan 23, 2025
1 parent d8e62f4 commit 1a74128
Show file tree
Hide file tree
Showing 5 changed files with 175 additions and 0 deletions.
155 changes: 155 additions & 0 deletions api/http/controller/tg_user_login.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package controller

import (
"errors"
"github.com/duke-git/lancet/v2/cryptor"
"github.com/gin-gonic/gin"
"github.com/hellodex/HelloSecurity/api/common"
"github.com/hellodex/HelloSecurity/codes"
"github.com/hellodex/HelloSecurity/model"
"github.com/hellodex/HelloSecurity/system"
"gorm.io/gorm"
"net/http"
"strconv"
"time"
)

type GetUserTokenReq struct {
Channel string `json:"channel"`
UserID string `json:"userId"`
}

func GetUserLoginToken(c *gin.Context) {
res := common.Response{}
var req GetUserTokenReq
appid, exists := c.Get("appId")
if !exists {
res.Code = codes.CODE_ERR_AUTH_FAIL
res.Msg = "channel err, appid is empty"
c.JSON(http.StatusOK, res)
return
}
if appid == nil || appid.(string) != "tg" {
res.Code = codes.CODE_ERR_AUTH_FAIL
res.Msg = "channel err, appid is not tg"
c.JSON(http.StatusOK, res)
return
}
if err := c.ShouldBindJSON(&req); err != nil {
res.Code = codes.CODE_ERR_REQFORMAT
res.Msg = "Invalid request"
c.JSON(http.StatusOK, res)
return
}

db := system.GetDb()
var userLogin model.TgLogin
result := db.Model(&model.TgLogin{}).Where("tg_user_id = ?", req.UserID).First(&userLogin)
//没有记录则创建
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
token, _ := generateToken(userLogin)
userLogin = model.TgLogin{
TgUserId: req.UserID,
Token: token,
GenerateTime: time.Now().Unix(),
ExpireTime: time.Now().Unix() + 60*5,
IsUsed: 0,
}
userLogin.Token, _ = generateToken(userLogin)
create := db.Create(&userLogin)
if create.Error != nil {
res.Code = codes.CODE_ERR_102
res.Msg = "db error"
c.JSON(http.StatusOK, res)
return
}
}
//过期则重新生成
if userLogin.ExpireTime < time.Now().Unix() {
userLogin.Token, _ = generateToken(userLogin)
userLogin.ExpireTime = time.Now().Unix() + 60*5
userLogin.GenerateTime = time.Now().Unix()
db.Save(&userLogin)
c.JSON(http.StatusOK, res)
return
}
//使用过的token则重新生成
if userLogin.IsUsed == 1 {
userLogin.Token, _ = generateToken(userLogin)
userLogin.ExpireTime = time.Now().Unix() + 60*5
userLogin.GenerateTime = time.Now().Unix()
userLogin.IsUsed = 0
db.Save(&userLogin)
c.JSON(http.StatusOK, res)
return
}
res.Data = userLogin.Token
c.JSON(http.StatusOK, res)
}

type VerifyUserTokenReq struct {
Token string `json:"token"`
UserID string `json:"userId"`
}

func VerifyUserLoginToken(c *gin.Context) {
res := common.Response{}
var req VerifyUserTokenReq
if err := c.ShouldBindJSON(&req); err != nil {
res.Code = codes.CODE_ERR_REQFORMAT
res.Msg = "Invalid request"
c.JSON(http.StatusOK, res)
return
}
appid, exists := c.Get("appId")
if !exists {
res.Code = codes.CODE_ERR_AUTH_FAIL
res.Msg = "channel err, appid is empty"
c.JSON(http.StatusOK, res)
return
}
if appid == nil || appid.(string) != "tg" {
res.Code = codes.CODE_ERR_AUTH_FAIL
res.Msg = "channel err, appid is not tg"
c.JSON(http.StatusOK, res)
return
}

db := system.GetDb()
var userLogin model.TgLogin
result := db.Model(&model.TgLogin{}).Where("tg_user_id = ?", req.UserID).Where("token", req.Token).First(&userLogin)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
res.Code = codes.CODE_ERR_INVALID
res.Msg = "token not exist"
c.JSON(http.StatusOK, res)
return
}
//用过的token
if userLogin.IsUsed == 1 {
res.Code = codes.CODE_ERR_INVALID
res.Msg = "token already used"
c.JSON(http.StatusOK, res)
return
}
//过期
if userLogin.ExpireTime < time.Now().Unix() {
res.Code = codes.CODE_ERR_INVALID
res.Msg = "token expired"
c.JSON(http.StatusOK, res)
return
}
//验证通过
userLogin.IsUsed = 1
db.Save(&userLogin)
res.Code = codes.CODE_SUCCESS
res.Msg = "success"
c.JSON(http.StatusOK, res)

}

func generateToken(login model.TgLogin) (string, error) {
//用时间戳和用户id进行base64编码
formatInt := strconv.FormatInt(time.Now().Unix(), 10)
token := cryptor.Base64StdEncode(login.TgUserId + formatInt)
return token, nil
}
3 changes: 3 additions & 0 deletions api/http/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,7 @@ func Routers(e *gin.RouterGroup) {
sysGroup.POST("/wallet/authCreateBatch", controller.AuthCreateBatchWallet) //批量创建钱包
//sysGroup.POST("/wallet/authCreateBatchTg", controller.AuthCreateBatchTgWallet) //批量创建钱包
sysGroup.POST("/wallet/authCreateBatchTg1", controller.AuthCreateBatchTgWallet1) //批量创建钱包

sysGroup.POST("/wallet/getUserLoginToken", controller.GetUserLoginToken) //批量创建钱包
sysGroup.POST("/wallet/verifyUserLoginToken", controller.VerifyUserLoginToken) //批量创建钱包
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/deckarep/golang-set/v2 v2.6.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 // indirect
github.com/duke-git/lancet/v2 v2.3.4 // indirect
github.com/ethereum/c-kzg-4844 v1.0.3 // indirect
github.com/ethereum/go-verkle v0.1.1-0.20240829091221-dffa7562dbe9 // indirect
github.com/fatih/color v1.17.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5il
github.com/decred/dcrd/crypto/blake256 v1.0.1/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 h1:rpfIENRNNilwHwZeG5+P150SMrnNEcHYvcCuK6dPZSg=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0=
github.com/duke-git/lancet/v2 v2.3.4 h1:8XGI7P9w+/GqmEBEXYaH/XuNiM0f4/90Ioti0IvYJls=
github.com/duke-git/lancet/v2 v2.3.4/go.mod h1:zGa2R4xswg6EG9I6WnyubDbFO/+A/RROxIbXcwryTsc=
github.com/ethereum/c-kzg-4844 v1.0.3 h1:IEnbOHwjixW2cTvKRUlAAUOeleV7nNM/umJR+qy4WDs=
github.com/ethereum/c-kzg-4844 v1.0.3/go.mod h1:VewdlzQmpT5QSrVhbBuGoCdFJkpaJlO1aQputP83wc0=
github.com/ethereum/go-ethereum v1.14.10 h1:kC24WjYeRjDy86LVo6MfF5Xs7nnUu+XG4AjaYIaZYko=
Expand Down
14 changes: 14 additions & 0 deletions model/mapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,17 @@ type LimitKeys struct {
func (LimitKeys) TableName() string {
return "limit_keys"
}

type TgLogin struct {
ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
Token string `gorm:"column:token" json:"token"`
TgUserId string `gorm:"column:tg_user_id" json:"tgUserId"`
GenerateTime int64 `gorm:"column:generate_time" json:"generateTime"`
ExpireTime int64 `gorm:"column:expire_time" json:"expireTime"`
IsUsed int8 `gorm:"column:is_used" json:"isUsed"`
}

// tg登录信息表
func (TgLogin) TableName() string {
return "tg_login"
}

0 comments on commit 1a74128

Please sign in to comment.