-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathauth.go
53 lines (45 loc) · 1.1 KB
/
auth.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
package bitmex
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
"github.com/adampointer/go-bitmex/types"
)
type sigParams struct {
secret, method, path, body string
expires time.Time
}
func (s *sigParams) expiryString() string {
return fmt.Sprintf("%d", s.expires.Unix())
}
func calculateSignature(params *sigParams) (string, error) {
raw := fmt.Sprintf("%s%s%d%s", params.method, params.path, params.expires.Unix(), params.body)
sig := hmac.New(sha256.New, []byte(params.secret))
if _, err := sig.Write([]byte(raw)); err != nil {
return "", err
}
return hex.EncodeToString(sig.Sum(nil)), nil
}
func websocketAuthCommand(key, secret string) (*types.Command, error) {
req := &sigParams{
method: "GET",
path: "/realtime",
secret: secret,
body: "",
expires: expiryTime(),
}
sig, err := calculateSignature(req)
if err != nil {
return nil, err
}
cmd := &types.Command{
Op: types.CommandOpAuth,
Args: types.CommandArgs{key, req.expires.Unix(), sig},
}
return cmd, nil
}
func expiryTime() time.Time {
return time.Now().Add(5 * time.Minute)
}