-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb_ctx.go
108 lines (97 loc) · 2.32 KB
/
web_ctx.go
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package openapi
import (
"errors"
"math"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
const (
defaultExpireTime = 60000
signParam = "sign"
timeParam = "time"
appKey = "app_key"
)
var signHeader = false
// SignHeader whether to sign http request header or not
func SignHeader(s bool) {
var lock sync.Mutex
lock.Lock()
signHeader = s
lock.Unlock()
}
// CheckValid to check if the request is valid from the signing key
// can't do the judge for you automatically, cause you may want to return something
// that is defined by yourself, and the call back form is not quite certain.
func CheckValid(req *http.Request, keeper SecretKeeper) (bool, error) {
if req == nil {
return false, errors.New("illegal request")
}
// time in millis
timeStr := getParamFromRequest(req, timeParam)
signResult := getParamFromRequest(req, signParam)
rt, err := strconv.ParseInt(timeStr, 10, 64)
if err != nil {
return false, errors.New("error parameter")
}
now := time.Now().UnixNano() / int64(time.Millisecond)
duration := math.Abs(float64(rt - now))
if duration > defaultExpireTime {
return false, errors.New("error timestamp")
}
pairs := getPairs(req)
content := buildParams(pairs)
secret, err := keeper.GetSecret(getParamFromRequest(req, appKey))
if err != nil {
return false, err
}
result := verify(signResult, content, secret)
if result {
return result, nil
}
return result, errors.New("error verifying")
}
func getParamFromRequest(req *http.Request, param string) string {
if req == nil {
return ""
}
return req.URL.Query().Get(param)
}
func getPairs(req *http.Request) Pairs {
pairs := make([]KvPair, 0, 10)
if signHeader {
// add all headers
headers := req.Header
headerPairs := getPairsFromMap(headers)
pairs = append(pairs, headerPairs...)
}
// add all params
paramsMap := req.URL.Query()
paramPairs := getPairsFromMap(paramsMap)
pairs = append(pairs, paramPairs...)
return pairs
}
// get params and headers except the param sign
func getPairsFromMap(m map[string][]string) Pairs {
pairs := make([]KvPair, 0, 10)
for k, v := range m {
if len(k) < 1 {
continue
}
var val string
for _, e := range v {
val += e
}
if strings.EqualFold(k, signParam) {
continue
}
p := KvPair{
Key: k,
Value: val,
}
pairs = append(pairs, p)
}
return pairs
}