Skip to content
This repository has been archived by the owner on Nov 29, 2020. It is now read-only.

Commit

Permalink
新增访问频率限制
Browse files Browse the repository at this point in the history
  • Loading branch information
mohuishou committed Jul 15, 2018
1 parent dc0078e commit 4c3e60e
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 7 deletions.
47 changes: 47 additions & 0 deletions cache/api/api.go
@@ -0,0 +1,47 @@
package api

import (
"log"

"fmt"

"strconv"

"github.com/mohuishou/scuplus-go/cache"
)

// 过期时间十分钟
const exp = 60 * 10

// Get get
func Get(uid uint) int {
v, err := cache.Do("GET", getKey(uid))
if err != nil {
log.Println("get cache code err:", err)
}
val, ok := v.([]byte)
if !ok {
return 0
}
n, _ := strconv.Atoi(string(val))
return n
}

// Add +1
func Add(uid uint) error {
key := getKey(uid)
_, err := cache.Do("INCR", key)
if err != nil {
log.Println("set cache code err:", err)
}
// 设置过期时间
_, err = cache.Do("Expire", key, exp)
if err != nil {
log.Println("set cache code err:", err)
}
return err
}

func getKey(uid uint) string {
return fmt.Sprintf("api.count.%d", uid)
}
9 changes: 9 additions & 0 deletions cache/api/api_test.go
@@ -0,0 +1,9 @@
package api

import "testing"

func TestGet(t *testing.T) {
t.Log(Get(1))
t.Log(Add(1))
t.Log(Get(1))
}
18 changes: 11 additions & 7 deletions middleware/jwt.go
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/dgrijalva/jwt-go"
jwtmiddleware "github.com/iris-contrib/middleware/jwt"
"github.com/kataras/iris"
"github.com/mohuishou/scuplus-go/cache/api"
)

func jwtMiddle(ctx iris.Context) {
Expand Down Expand Up @@ -63,16 +64,16 @@ func jwtMiddle(ctx iris.Context) {

// 设置用户id
ctx.Values().Set("user_id", userID)
// TODO: 临时手动封号
if userID == 18137 {
uid := uint(userID.(float64))
if api.Get(uid) > 300 {
ctx.JSON(map[string]interface{}{
"status": 403,
"msg": "账号更换次数过多,暂被封号!",
"data": nil,
"msg": "访问过于频繁,休息一会儿吧",
})
ctx.StopExecution()
return
}
api.Add(uid)
ctx.Next()
}

Expand All @@ -82,8 +83,6 @@ func skipJWT(path string) bool {
"/login",
"/notices",
"/webhook",
"/spider/webhook",
"/spider/jwc/cookies",
"/helps",
}
for _, v := range urls {
Expand All @@ -96,7 +95,12 @@ func skipJWT(path string) bool {

// GetUserID 获取用户的id
func GetUserID(ctx iris.Context) uint {
return uint(ctx.Values().Get("user_id").(float64))
uid := ctx.Values().Get("user_id")
switch uid.(type) {
case float64:
return uint(uid.(float64))
}
return 0
}

// CreateToken 新建一个Token
Expand Down

0 comments on commit 4c3e60e

Please sign in to comment.