1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
// 中间件:logic/middleware/sign.go
package middleware
import (
"errors"
"fmt"
"github.com/labstack/echo/v4"
"xxx/xxx/pkg/helper"
"xxx/xxx/pkg/xecho"
"xxx/xxx/config"
"xxx/xxx/dao"
"xxx/xxx/global"
"net/http"
"strconv"
"time"
)
const ErrCodeSignInvalid = 3 // 签名无效
type sign struct {
name string // 签名类型/平台
secret string // 密钥
ttl int64 // 签名生命周期
}
var (
SignTeamB = &sign{
name: config.SignTypeForTeamB,
secret: config.SignTypeSecretMap[config.SignTypeForTeamB],
ttl: config.SignTTL,
}
)
func (s *sign) Auth(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
var (
sign = c.Request().Header.Get("sign")
requestTime, _ = strconv.ParseInt(c.Request().Header.Get("request-time"), 10, 64)
requestStaffId, _ = strconv.ParseUint(c.Request().Header.Get("request-staff"), 10, 64)
)
if sign == "" {
return c.JSON(http.StatusUnauthorized, xecho.FailCode("sign参数不能为空", ErrCodeSignInvalid))
}
if requestTime <= 0 {
return c.JSON(http.StatusUnauthorized, xecho.FailCode("request-time参数不能为空", ErrCodeSignInvalid))
}
if requestStaffId <= 0 {
return c.JSON(http.StatusUnauthorized, xecho.FailCode("request-staff参数不能为空", ErrCodeSignInvalid))
}
if err := s.CheckSign(sign, requestTime, requestStaffId); err != nil {
return c.JSON(http.StatusUnauthorized, xecho.FailCode(err.Error(), ErrCodeSignInvalid))
}
staff := dao.Staff.GetById(requestStaffId)
c.Set(global.KVStaff, staff)
return next(c)
}
}
// 签名校验
func (s *sign) CheckSign(sign string, requestTime int64, requestStaffId uint64) error {
if s.secret == "" {
return errors.New("该签名类型还没配置密钥")
}
if sign != helper.Md5(fmt.Sprintf("%d-%s-%s-%d", requestTime, s.name, s.secret, requestStaffId)) {
return errors.New("签名有误")
}
currentTime := time.Now().Unix()
if currentTime < requestTime || (currentTime-requestTime) > s.ttl {
return errors.New("签名已过期")
}
return nil
}
// 生成签名
func (s *sign) GenerateSign(requestStaffId uint64) (string, int64, error) {
requestTime := time.Now().Unix()
sign := helper.Md5(fmt.Sprintf("%d-%s-%s-%d", requestTime, s.name, s.secret, requestStaffId))
return sign, requestTime, nil
}
|