-
Notifications
You must be signed in to change notification settings - Fork 2
/
twikey.go
231 lines (194 loc) · 5.54 KB
/
twikey.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// Package twikey provides the bindings for Twikey REST APIs.
package twikey
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const (
baseURLV1 = "https://api.twikey.com"
twikeyBaseAgent = "twikey-api/go-v0.1.1"
)
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
type TimeProvider interface {
Now() time.Time
}
type DefaultTimeProvider struct{}
func (tp DefaultTimeProvider) Now() time.Time {
return time.Now()
}
// Client is the base class, please use a dedicated UserAgent so we can notify the emergency contact
// if weird behaviour is perceived.
type Client struct {
BaseURL string
APIKey string
PrivateKey string
Salt string
UserAgent string
HTTPClient HTTPClient
Debug Logger
apiToken string
lastLogin time.Time
TimeProvider TimeProvider
}
type ClientOption = func(*Client)
type FeedOptions struct {
start int64
includes []string
}
type FeedOption = func(*FeedOptions)
func parseFeedOptions(options []FeedOption) *FeedOptions {
feedOption := &FeedOptions{
start: -1,
}
for _, option := range options {
option(feedOption)
}
return feedOption
}
func FeedInclude(include ...string) FeedOption {
return func(opts *FeedOptions) {
opts.includes = append(opts.includes, include...)
}
}
func FeedStartPosition(start int64) FeedOption {
return func(opts *FeedOptions) {
opts.start = start
}
}
// WithLogger sets the Logger for the Client. If you don't want
// the Client to log anything you can pass in the NullLogger
func WithLogger(logger Logger) ClientOption {
return func(client *Client) {
client.Debug = logger
}
}
// WithBaseURL will set the base URL of the API used when making requests.
//
// In production, you will probably want to use the default but if you want
// to make request to some mock API in a test environment you can use this
// to make the Client make requests to a different host.
//
// The default: https://api.twikey.com
func WithBaseURL(baseURL string) ClientOption {
return func(client *Client) {
client.BaseURL = baseURL
}
}
// WithHTTPClient configures the underlying HTTP client used to make HTTP requests.
func WithHTTPClient(httpClient HTTPClient) ClientOption {
return func(client *Client) {
client.HTTPClient = httpClient
}
}
// WithTimeProvider sets the TimeProvider for this Client.
func WithTimeProvider(provider TimeProvider) ClientOption {
return func(client *Client) {
client.TimeProvider = provider
}
}
// WithSalt sets the salt used in generating one-time-passwords
func WithSalt(salt string) ClientOption {
return func(client *Client) {
client.Salt = salt
}
}
// WithUserAgent will configure the value that is passed on in the HTTP User-Agent header
// for all requests to the Twikey API made with this Client
func WithUserAgent(userAgent string) ClientOption {
return func(client *Client) {
client.UserAgent = userAgent
}
}
// NewClient is a convenience method to hit the ground running with the Twikey Rest API
func NewClient(apiKey string, opts ...ClientOption) *Client {
c := &Client{
BaseURL: baseURLV1,
APIKey: apiKey,
Salt: "own",
UserAgent: twikeyBaseAgent,
HTTPClient: &http.Client{
Timeout: 30 * time.Second,
},
Debug: &NullLogger{},
TimeProvider: DefaultTimeProvider{},
}
for _, opt := range opts {
opt(c)
}
return c
}
type errorResponse struct {
Code string `json:"code"`
Message string `json:"message"` // translated according to Accept-Language
Extra string `json:"extra"`
}
// Ping Try the current credentials
func (c *Client) Ping() error {
if err := c.refreshTokenIfRequired(); err != nil {
return err
}
return nil
}
func (c *Client) sendRequest(req *http.Request, v interface{}) error {
if err := c.refreshTokenIfRequired(); err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", c.UserAgent)
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", c.apiToken)
c.Debug.Tracef("Calling %s %s", req.Method, req.URL)
res, err := c.HTTPClient.Do(req)
if err != nil {
c.Debug.Tracef("Error while connecting %v", err)
return err
}
payload, _ := io.ReadAll(res.Body)
_ = res.Body.Close()
c.Debug.Tracef("Response for %s %s %s", req.Method, req.URL, string(payload))
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
if res.Header.Get("Apierror") == "err_no_login" {
c.Debug.Tracef("Error while using apitoken, renewing")
c.lastLogin = time.Time{} // force re-authenticate
}
var errRes errorResponse
if err = json.Unmarshal(payload, &errRes); err == nil {
return NewTwikeyError(errRes.Code, errRes.Message, errRes.Extra)
}
return NewTwikeyErrorFromResponse(res)
}
if v == nil {
return nil
}
if err = json.Unmarshal(payload, v); err != nil {
return NewTwikeyError("system_error", err.Error(), "")
}
return nil
}
// VerifyWebhook allows the verification of incoming webhooks.
func (c *Client) VerifyWebhook(signatureHeader string, payload string) error {
hash := hmac.New(sha256.New, []byte(c.APIKey))
if _, err := hash.Write([]byte(payload)); err != nil {
c.Debug.Tracef("Error cannot compute the HMAC for request: %v", err)
return err
}
expectedHash := strings.ToUpper(hex.EncodeToString(hash.Sum(nil)))
if signatureHeader == expectedHash {
return nil
}
return NewTwikeyError("invalid_params", "Invalid value", "")
}
func addIfExists(params url.Values, paramKey string, value string) {
if value != "" {
params.Add(paramKey, value)
}
}