-
Notifications
You must be signed in to change notification settings - Fork 34
/
api_key_authentication.go
64 lines (51 loc) · 1.53 KB
/
api_key_authentication.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
package coinbase
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"net/http"
"strconv"
"time"
"github.com/fabioberger/coinbase-go/config"
)
// ApiKeyAuthentication Struct implements the Authentication interface and takes
// care of authenticating RPC requests for clients with a Key & Secret pair
type apiKeyAuthentication struct {
Key string
Secret string
BaseUrl string
Client http.Client
}
// ApiKeyAuth instantiates ApiKeyAuthentication with the API key & secret
func apiKeyAuth(key string, secret string) *apiKeyAuthentication {
a := apiKeyAuthentication{
Key: key,
Secret: secret,
BaseUrl: config.BaseUrl,
Client: http.Client{
Transport: &http.Transport{
Dial: dialTimeout,
},
},
}
return &a
}
// API Key + Secret authentication requires a request header of the HMAC SHA-256
// signature of the "message" as well as an incrementing nonce and the API key
func (a apiKeyAuthentication) authenticate(req *http.Request, endpoint string, params []byte) error {
nonce := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
message := nonce + endpoint + string(params) //As per Coinbase Documentation
req.Header.Set("ACCESS_KEY", a.Key)
h := hmac.New(sha256.New, []byte(a.Secret))
h.Write([]byte(message))
signature := hex.EncodeToString(h.Sum(nil))
req.Header.Set("ACCESS_SIGNATURE", signature)
req.Header.Set("ACCESS_NONCE", nonce)
return nil
}
func (a apiKeyAuthentication) getBaseUrl() string {
return a.BaseUrl
}
func (a apiKeyAuthentication) getClient() *http.Client {
return &a.Client
}