Browse Source

完善校验

xuzhiheng 4 years ago
parent
commit
7745716c4e
7 changed files with 69 additions and 28 deletions
  1. 10 4
      api/v1/userRecharge.go
  2. 2 2
      conf/dev/base.toml
  3. 31 3
      middleware/auth.go
  4. 11 13
      model/product.go
  5. 5 5
      service/user.go
  6. 6 1
      sword_base/utils/stringutil.go
  7. 4 0
      utils/api_util.go

+ 10 - 4
api/v1/userRecharge.go

@@ -3,6 +3,7 @@ package v1
 import (
 	"encoding/json"
 	"sfbase/global"
+	"sfis/model/response"
 	"sfis/service"
 	"strconv"
 
@@ -23,7 +24,10 @@ func RechargeApiRegister(router *gin.Engine) {
 //余额充值接口
 func moneyRecharge(c *gin.Context) {
 	appid := c.PostForm("appid")
-	money, _ := strconv.Atoi(c.PostForm("money"))
+	money, err := strconv.Atoi(c.PostForm("money"))
+	if err != nil {
+		response.FailWithDetailed(response.ParamError, nil, "参数错误", c)
+	}
 	p := gin.H{
 		"appid": appid,
 		"money": money,
@@ -37,10 +41,12 @@ func moneyRecharge(c *gin.Context) {
 //产品剩余量充值接口
 func productRecharge(c *gin.Context) {
 	appid := c.PostForm("appid")
-	productId, _ := strconv.Atoi(c.PostForm("productId"))
-	rechargeNum, _ := strconv.Atoi(c.PostForm("rechargeNum"))
+	productId, err := strconv.Atoi(c.PostForm("productId"))
+	rechargeNum, errs := strconv.Atoi(c.PostForm("rechargeNum"))
 	endTime := c.PostForm("endTime")
-
+	if err != nil || errs != nil {
+		response.FailWithDetailed(response.ParamError, nil, "参数错误", c)
+	}
 	p := gin.H{
 		"appid":       appid,
 		"productId":   productId,

+ 2 - 2
conf/dev/base.toml

@@ -1,5 +1,5 @@
 [http]
-    http_port =":8080"                       # 监听地址, default "=8700"
+    http_port =":8081"                       # 监听地址, default "=8700"
     read_timeout = 200                   # 读取超时时长
     write_timeout = 200                  # 写入超时时长
     max_header_bytes = 40               # 最大的header大小,二进制位长度
@@ -18,4 +18,4 @@
     stacktrace-key= 'stacktrace'
     log-in-console= true
 [session]
-    redis_token = "token=39.107.203.162:10079"
+    redis_token = "token=39.107.203.162:10079,limit=192.168.3.128:1712"

+ 31 - 3
middleware/auth.go

@@ -3,8 +3,10 @@ package middleware
 import (
 	"fmt"
 	"sfbase/global"
+	"sfbase/redis"
 	sutils "sfbase/utils"
-
+	"sfis/db"
+	"sfis/model"
 	"sfis/model/response"
 	"sfis/utils"
 	"strconv"
@@ -40,7 +42,7 @@ func TokenAuth() gin.HandlerFunc {
 			context.Abort()
 			return
 		}
-		productID = 1000
+		// productID = 1000
 		token = context.Request.Header.Get("token")
 		timestamp = context.Request.Header.Get("timestamp")
 		appID = context.PostForm("app_id")
@@ -94,9 +96,35 @@ func TokenAuth() gin.HandlerFunc {
 			return
 		}
 
+		userProduct := &model.UserProduct{}
+		db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
+		//校验是否过期
+		end := userProduct.EndAt
+		loc, _ := time.LoadLocation("Local")
+		endTimes := int64(0)
+		if endTime, err := time.ParseInLocation("2006-01-02 15:04:05", end, loc); err == nil {
+			endTimes = endTime.Unix()
+		}
+		if now > endTimes {
+			response.FailWithDetailed(response.InterfaceExpired, nil, "剩余量已过期", context)
+			context.Abort()
+			return
+		}
+		//校验每日调用上限
+		limittodaykey := fmt.Sprintf("limittoday_%d_%d_%s", time.Now().Day(), productID, appID)
+		limittoday := redis.GetInt("limit", limittodaykey)
+		if limittoday > userProduct.CallTimesLimitDay { //当天调用超过次数
+			response.FailWithDetailed(response.MoreThanEveryDayDataNumberLimit, nil, "请求超过每日调用总量限制", context)
+			context.Abort()
+			return
+		} else {
+			if limittoday == 0 {
+				_, max := sutils.GetDayMinMax(time.Now())
+				redis.Put("limit", limittodaykey, 0, int(max-now))
+			}
+		}
 		context.Set("appID", appID)
 		context.Set("productID", productID)
 		context.Set("requestIP", requestIP)
-
 	}
 }

+ 11 - 13
model/product.go

@@ -1,7 +1,5 @@
 package model
 
-import "time"
-
 type Product struct {
 	BaseModel
 	ID          int    `json:"id" form:"id" gorm:"primaryKey" binding:"required"`
@@ -18,17 +16,17 @@ func (p *Product) TableName() string {
 }
 
 type UserProduct struct {
-	ID                   int       `json:"id" gorm:"primaryKey"`
-	AppID                string    `json:"app_id"`
-	ProductID            int       `json:"product_id"`
-	CreateAt             time.Time `json:"-" gorm:"autoCreateTime"` //标签autoCreateTime设置如果字段名字不为CreatAt时候自动插入当前时间
-	StartAt              time.Time `json:"start_at" grom:"start_at"`
-	EndAt                time.Time `json:"end_at" grom:"end_at"`
-	LeftNum              int       `json:"left_num"`                 //剩余量  加锁处理
-	CostModel            int       `json:"cost_model"`               //扣费模式(0-按剩余量扣,1-按账户余额扣,2-优先扣剩余量,量为0扣余额)
-	InterfaceStatus      int       `json:"interface_status"`         //接口状态(0开启|-1停用|-2异常|-3维护)
-	CallTimesLimitDay    int       `json:"call_times_limit_day"`     //接口调用次数每日上限
-	DataNumLimitOneTimes int       `json:"data_num_limit_one_times"` //接口每次返回数据量上限
+	ID                   int    `json:"id" gorm:"primaryKey"`
+	AppID                string `json:"app_id"`
+	ProductID            int    `json:"product_id"`
+	CreateAt             string `json:"-" gorm:"autoCreateTime"` //标签autoCreateTime设置如果字段名字不为CreatAt时候自动插入当前时间
+	StartAt              string `json:"start_at" grom:"start_at"`
+	EndAt                string `json:"end_at" grom:"end_at"`
+	LeftNum              int    `json:"left_num"`                 //剩余量  加锁处理
+	CostModel            int    `json:"cost_model"`               //扣费模式(0-按剩余量扣,1-按账户余额扣,2-优先扣剩余量,量为0扣余额)
+	InterfaceStatus      int    `json:"interface_status"`         //接口状态(0开启|-1停用|-2异常|-3维护)
+	CallTimesLimitDay    int    `json:"call_times_limit_day"`     //接口调用次数每日上限
+	DataNumLimitOneTimes int    `json:"data_num_limit_one_times"` //接口每次返回数据量上限
 }
 
 func (p *UserProduct) TableName() string {

+ 5 - 5
service/user.go

@@ -1,15 +1,15 @@
 package service
 
 import (
-	"github.com/gin-gonic/gin"
-	"gorm.io/gorm"
 	"log"
 	"sfis/db"
 	"sfis/model"
 	"sfis/model/response"
 	"strconv"
 	"strings"
-	"time"
+
+	"github.com/gin-gonic/gin"
+	"gorm.io/gorm"
 )
 
 func UserProject(projectIds, appId, startTime, endTime string, leftNum, costModel, interfaceStatus, callTimesLimitDay, dataNumOneTimes, tradeMoney, buyType, historyUnitPrice int, c *gin.Context) {
@@ -19,8 +19,8 @@ func UserProject(projectIds, appId, startTime, endTime string, leftNum, costMode
 		for _, v := range projectIdsArr {
 			userProject := &model.UserProduct{}
 			userProject.AppID = appId
-			userProject.StartAt, _ = time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
-			userProject.EndAt, _ = time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
+			userProject.StartAt = startTime
+			userProject.EndAt = endTime
 			userProject.LeftNum = leftNum
 			userProject.CostModel = costModel
 			userProject.InterfaceStatus = interfaceStatus

+ 6 - 1
sword_base/utils/stringutil.go

@@ -151,7 +151,12 @@ func ObjToString(old interface{}) string {
 
 /**
 产生一般订单编号方法
- */
+*/
 func CreateOrderCode() string {
 	return fmt.Sprint(time.Now().Unix()) + fmt.Sprint(GetRandom(6))
 }
+
+func GetDayMinMax(t time.Time) (int64, int64) {
+	min := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local).Unix()
+	return min, min + 86400
+}

+ 4 - 0
utils/api_util.go

@@ -2,8 +2,10 @@ package utils
 
 import (
 	// "context"
+	"fmt"
 	"log"
 	"sfbase/global"
+	"sfbase/redis"
 	"sfis/db"
 	"sfis/lock"
 	"sfis/model"
@@ -88,6 +90,8 @@ func Check(appID string, productID int, c *gin.Context, getData func() ([]map[st
 			"user_product_id": userProduct.ID,
 			"create_at":       time.Now().Unix(),
 		})
+		limittodaykey := fmt.Sprintf("limittoday_%d_%d_%s", time.Now().Day(), userProduct.ProductID, userProduct.AppID)
+		redis.Incr("limit", limittodaykey)
 		response.FailWithDetailed(response.SUCCESS, datas, "OK", c)
 	} else {
 		if strings.Contains(errStr, "不足") {