-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
93 lines (79 loc) · 2.28 KB
/
option.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
package signature
import (
"fmt"
"math"
"time"
)
type OptionFunc func(*option)
type option struct {
appID string // app id
secret string // secret
expire time.Duration // | Now - Timestamp | < Expire
noiseFunc func() string // noise string, generate n0ise
hmacFunc func(secret string, rawArr ...string) string // hmac func
unSignedKeys []string // no signed key
withToken bool // with token
}
func (o *option) HMac(rawArr ...string) string {
return o.hmacFunc(o.secret, rawArr...)
}
func (o *option) Valid(timestamp int64) error {
if v := math.Abs(float64(time.Now().Unix()) - float64(timestamp)); v > o.expire.Seconds() {
return fmt.Errorf("sign overdue,ts not in %.2fs", o.expire.Seconds())
}
return nil
}
func (o *option) Noise() string {
return o.noiseFunc()
}
func NewOption() *option {
return &option{
secret: "",
expire: time.Minute * 2,
noiseFunc: DefaultNoiseRand,
hmacFunc: HashMacSha1,
unSignedKeys: []string{},
}
}
// WithAppID set app_id, when generate
func WithAppID(v string) OptionFunc {
return func(opt *option) {
opt.appID = v
}
}
// WithSecret set secret, when generate or verify
func WithSecret(v string) OptionFunc {
return func(opt *option) {
opt.secret = v
}
}
// WithExpire set timestamp expire, when verify
func WithExpire(v time.Duration) OptionFunc {
return func(opt *option) {
opt.expire = v
}
}
// WithNoiseFunc set noise generate func, when generate
func WithNoiseFunc(f func() string) OptionFunc {
return func(opt *option) {
opt.noiseFunc = f
}
}
// WithUnSignedKey set unsigned field, when generate & verify
func WithUnSignedKey(v ...string) OptionFunc {
return func(opt *option) {
opt.unSignedKeys = append(opt.unSignedKeys, v...)
}
}
// WithHmacFunc set hmac func, when generate & verify. default is hmac sha1
func WithHmacFunc(f func(secret string, rawArr ...string) string) OptionFunc {
return func(opt *option) {
opt.hmacFunc = f
}
}
// WithToken sign hmac with token
func WithToken(iswith bool) OptionFunc {
return func(opt *option) {
opt.withToken = true
}
}