瀏覽代碼

Merge branch 'master' of http://192.168.3.207:10080/group3/SwordFish_Interface_Service

jiaojiao7 4 年之前
父節點
當前提交
c4a5a0fe15

+ 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,

+ 1 - 1
conf/dev/base.toml

@@ -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"

+ 2 - 3
lock/lock.go

@@ -5,9 +5,8 @@ import (
 )
 
 var (
-	UserLockMap   = map[string]*sync.Mutex{}
-	MainLock      = sync.Mutex{}
-	OrderCodeLock = sync.Mutex{}
+	UserLockMap = map[string]*sync.Mutex{}
+	MainLock    = sync.Mutex{}
 )
 
 func InitUserLock(appID string) {

+ 2 - 3
main.go

@@ -33,6 +33,7 @@ func main() {
 		db.GetSFISDB().Find(&users)
 		for _, user := range users {
 			utils.UserCaches.Map.Store(user.AppID, user)
+			lock.UserLockMap[user.AppID] = &sync.Mutex{}
 		}
 		global.Logger.Info("初始化用户缓存信息,", zap.Any("用户数量:", len(users)))
 
@@ -40,12 +41,10 @@ func main() {
 		db.GetSFISDB().Find(&apis)
 		for _, api := range apis {
 			utils.ProductCaches.Map.Store(api.ID, api)
-			utils.ApiUrlCache.Store(api.Path, *api)
+			utils.ApiUrlCache.Store(api.Path, api.ID)
 		}
 		global.Logger.Info("初始化产品缓存信息,", zap.Any("产品数量:", len(apis)))
 	}
-	lock.UserLockMap["sfGSVYRQMAAgkGBAUBJg4f"] = &sync.Mutex{}
-	lock.UserLockMap["sfPQRYRQMAAwcGBwYBCgcA"] = &sync.Mutex{}
 	//全局redis的使用?
 	redis.InitRedis(global.BaseConfig.RedisSession.RedisToken)
 	//启动web server

+ 43 - 12
middleware/auth.go

@@ -2,15 +2,19 @@ package middleware
 
 import (
 	"fmt"
-	"github.com/gin-gonic/gin"
-	"go.uber.org/zap"
 	"sfbase/global"
+	"sfbase/redis"
 	sutils "sfbase/utils"
+	"sfis/db"
+	"sfis/model"
 	"sfis/model/response"
 	"sfis/utils"
 	"strconv"
 	"strings"
 	"time"
+
+	"github.com/gin-gonic/gin"
+	"go.uber.org/zap"
 )
 
 const TimestampExpireTime = 600 //单位秒,header里的时间戳超时时间 10分钟
@@ -26,17 +30,19 @@ func TokenAuth() gin.HandlerFunc {
 			requestIP  string
 		)
 		requestUrl = context.Request.URL.String()
-		requestUrl = strings.Split(requestUrl, "?")[0]
-		a := strings.Split(requestUrl, "/")
-		requestUrl = a[4]
-		/*if p, ok := utils.ApiUrlCache.Load(requestUrl); ok {
-			productID = p.(*model.Product).ID
+		global.Logger.Info(requestUrl)
+		requestUrl = strings.Split(requestUrl, "v1")[1]
+		global.Logger.Info(requestUrl)
+		// a := strings.Split(requestUrl, "/")
+		// requestUrl = a[4]
+		if p, ok := utils.ApiUrlCache.Load(requestUrl); ok {
+			productID = p.(int)
 		} else {
 			response.FailWithDetailed(response.ParamError, nil, "url错误", context)
 			context.Abort()
 			return
-		}*/
-		productID = 1000
+		}
+		// productID = 1000
 		token = context.Request.Header.Get("token")
 		timestamp = context.Request.Header.Get("timestamp")
 		appID = context.PostForm("app_id")
@@ -53,7 +59,11 @@ func TokenAuth() gin.HandlerFunc {
 			return
 		}
 		now := time.Now().Unix()
-		if now-_timestamp > TimestampExpireTime {
+		TimestampExpire := now - _timestamp
+		if TimestampExpire < 0 {
+			TimestampExpire = -TimestampExpire
+		}
+		if TimestampExpire > TimestampExpireTime {
 			//token时间验证 十分钟
 			response.FailWithDetailed(response.TokenExpired, nil, "签名过期", context)
 			context.Abort()
@@ -68,8 +78,8 @@ func TokenAuth() gin.HandlerFunc {
 		/**
 		第一步:ip白名单校验
 		*/
+		requestIP = utils.GetIp(context.Request)
 		if ipWhiteList != "*" {
-			requestIP = utils.GetIp(context.Request)
 			if strings.Index(ipWhiteList, requestIP) < 0 {
 				response.FailWithDetailed(response.IpInvalid, nil, "ip不在白名单", context)
 				context.Abort()
@@ -86,9 +96,30 @@ func TokenAuth() gin.HandlerFunc {
 			return
 		}
 
+		userProduct := &model.UserProduct{}
+		db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appID, ProductID: productID})
+		//校验是否过期
+		end := userProduct.EndAt
+		if now > end.Unix() {
+			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)
-
 	}
 }

+ 3 - 1
model/product.go

@@ -1,6 +1,8 @@
 package model
 
-import "time"
+import (
+	"time"
+)
 
 type Product struct {
 	BaseModel

+ 4 - 1
service/projectDetail.go

@@ -16,7 +16,10 @@ func ProjectDetailData(id string) (data []map[string]interface{}, httpStatus int
 	query := fmt.Sprintf(_query, id, fields)
 	INDEX := core.GetStringConf("es.project.index")
 	TYPE := core.GetStringConf("es.project.itype")
-	infos := db.Es.Get(INDEX, TYPE, query)
+	infos, err := db.Es.Get(INDEX, TYPE, query)
+	if err != nil {
+		return nil, 200, err
+	}
 	if infos != nil && len(*infos) > 0 {
 		data = *infos
 		for _, val := range data {

+ 7 - 4
service/projects.go

@@ -81,8 +81,11 @@ func ProjectListData(productId int, appid, projectName, winner, times string, is
 	}
 	userProduct := &model.UserProduct{}
 	db.GetSFISDB().First(userProduct, &model.UserProduct{AppID: appid, ProductID: productId})
-	repl := GetAllByNgram(Es, INDEX, TYPE, qstr, "", pjt_sort, fields, 0, userProduct.DataNumLimitOneTimes, 0, false)
-	if repl != nil && len(*repl) > 0 {
+	repl, err := GetAllByNgram(Es, INDEX, TYPE, qstr, "", pjt_sort, fields, 0, userProduct.DataNumLimitOneTimes, 0, false)
+	if err != nil {
+		err = errors.New("查询失败")
+		return
+	} else if repl != nil && len(*repl) > 0 {
 		data = *repl
 		for _, i := range data {
 			i["project_id"] = SE.EncodeString(utils.ObjToString(i["_id"]))
@@ -92,7 +95,7 @@ func ProjectListData(productId int, appid, projectName, winner, times string, is
 	return
 }
 
-func GetAllByNgram(Es *elastic.Elastic, index, itype, qstr, findfields, order, fields string, start, limit, count int, highlight bool) *[]map[string]interface{} {
+func GetAllByNgram(Es *elastic.Elastic, index, itype, qstr, findfields, order, fields string, start, limit, count int, highlight bool) (*[]map[string]interface{}, error) {
 	if qstr != "" {
 		if highlight {
 			ws := []string{}
@@ -113,6 +116,6 @@ func GetAllByNgram(Es *elastic.Elastic, index, itype, qstr, findfields, order, f
 		global.Logger.Info("GetAllByNgram方法es查询", zap.Any("es语句", qstr))
 		return Es.Get(index, itype, qstr)
 	} else {
-		return nil
+		return nil, nil
 	}
 }

+ 3 - 2
service/user.go

@@ -1,8 +1,6 @@
 package service
 
 import (
-	"github.com/gin-gonic/gin"
-	"gorm.io/gorm"
 	"log"
 	"sfis/db"
 	"sfis/lock"
@@ -11,6 +9,9 @@ import (
 	"strconv"
 	"strings"
 	"time"
+
+	"github.com/gin-gonic/gin"
+	"gorm.io/gorm"
 )
 
 func UserProduct(productIds, appId, startTime, endTime string, leftNum, costModel, interfaceStatus, callTimesLimitDay, dataNumOneTimes, tradeMoney, buyType int, c *gin.Context) {

+ 3 - 3
sword_base/elastic/elasticSim.go

@@ -82,7 +82,7 @@ func (e *Elastic) GetEsConn() *es.Client {
 	}
 }
 
-func (e *Elastic) Get(index, itype, query string) *[]map[string]interface{} {
+func (e *Elastic) Get(index, itype, query string) (*[]map[string]interface{}, error) {
 	client := e.GetEsConn()
 	defer func() {
 		go e.DestoryEsConn(client)
@@ -104,7 +104,7 @@ func (e *Elastic) Get(index, itype, query string) *[]map[string]interface{} {
 		searchResult, err := client.Search().Index(index).Type(itype).Source(query).Do()
 		if err != nil {
 			log.Println("从ES查询出错", err.Error())
-			return nil
+			return nil, err
 		}
 		if searchResult.Hits != nil {
 			resNum := len(searchResult.Hits.Hits)
@@ -121,7 +121,7 @@ func (e *Elastic) Get(index, itype, query string) *[]map[string]interface{} {
 			}
 		}
 	}
-	return &res
+	return &res, nil
 }
 
 //关闭elastic

+ 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, "不足") {

+ 4 - 4
utils/cost_by_account_balance.go

@@ -7,7 +7,6 @@ import (
 	"sfbase/global"
 	"sfbase/utils"
 	"sfis/db"
-	"sfis/lock"
 	"sfis/model"
 
 	"go.uber.org/zap"
@@ -31,7 +30,10 @@ func costByAccountBalance(getData func() ([]map[string]interface{}, int, error),
 	var err error
 	errStr := ""
 	orderCode := ""
-	data, statusCode, _ := execute(getData, appID, productID)
+	data, statusCode, errs := execute(getData, appID, productID)
+	if errs != nil {
+		return nil, "", errs, "查询失败"
+	}
 	beforeJudge, payMoney := beforeCheck(productType, product.UnitPrice, len(data), userProduct)
 	if beforeJudge {
 		global.Logger.Info("交易金额", zap.Any("payMoney:", payMoney))
@@ -81,9 +83,7 @@ func afterCheck(dataLen, payMoney int, userProduct *model.UserProduct, statusCod
 	userAccount := &model.UserAccount{}
 	db.GetSFISDB().First(userAccount, &model.UserAccount{AppID: userProduct.AppID})
 	var errs error
-	lock.OrderCodeLock.Lock()
 	orderCode := utils.CreateOrderCode()
-	lock.OrderCodeLock.Unlock()
 	//按次扣费-(每调一次剩余量-1)
 	errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
 		orderBefore := userAccount.Money

+ 0 - 3
utils/cost_by_left_num.go

@@ -6,7 +6,6 @@ import (
 	"sfbase/global"
 	"sfbase/utils"
 	"sfis/db"
-	"sfis/lock"
 	"sfis/model"
 
 	"gorm.io/gorm"
@@ -85,9 +84,7 @@ func after(productType int, dataLen int, userProduct *model.UserProduct, statusC
 	productID := userProduct.ProductID
 	userProductID := userProduct.ID
 	var errs error
-	lock.OrderCodeLock.Lock()
 	orderCode := utils.CreateOrderCode()
-	lock.OrderCodeLock.Unlock()
 	switch productType {
 	case 0:
 		//按次扣费-(每调一次剩余量-1)