-
Notifications
You must be signed in to change notification settings - Fork 21
/
onfido.go
231 lines (198 loc) · 4.81 KB
/
onfido.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 onfido
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/tomnomnom/linkheader"
)
// Constants
const (
ClientVersion = "0.1.0"
DefaultEndpoint = "https://api.onfido.com/v2"
TokenEnv = "ONFIDO_TOKEN"
)
// Client represents an Onfido API client
type Client struct {
Endpoint string
HTTPClient HTTPRequester
Token Token
}
// HTTPRequester represents an HTTP requester
type HTTPRequester interface {
Do(*http.Request) (*http.Response, error)
}
// Error represents an Onfido API error response
type Error struct {
Resp *http.Response
// see https://documentation.onfido.com/#error-object
Err struct {
ID string `json:"id"`
Type string `json:"type"`
Msg string `json:"message"`
Fields ErrorFields `json:"fields"`
} `json:"error"`
}
// known shapes of the values are []string and map[string][]string for recursive field validation
type ErrorFields map[string]interface{}
func (e *Error) Error() string {
if e.Err.Msg != "" {
return e.Err.Msg
}
if e.Resp != nil {
return fmt.Sprintf("http request failed with status code %d", e.Resp.StatusCode)
}
return "an unknown error occurred"
}
// Token is an Onfido authentication token
type Token string
// String returns the token as a string.
func (t Token) String() string {
return string(t)
}
// Prod checks if this is a production token or not.
func (t Token) Prod() bool {
return !strings.HasPrefix(string(t), "test_") &&
!strings.HasPrefix(string(t), "api_sandbox.")
}
// NewClientFromEnv creates a new Onfido client using configuration
// from environment variables.
func NewClientFromEnv() (*Client, error) {
token := os.Getenv(TokenEnv)
if token == "" {
return nil, fmt.Errorf("onfido token not found in environmental variable `%s`", TokenEnv)
}
return NewClient(token), nil
}
// NewClient creates a new Onfido client.
func NewClient(token string) *Client {
return &Client{
Endpoint: DefaultEndpoint,
HTTPClient: http.DefaultClient,
Token: Token(token),
}
}
func (c *Client) newRequest(method, uri string, body io.Reader) (*http.Request, error) {
if !strings.HasPrefix(uri, "http") {
if !strings.HasPrefix(uri, "/") {
uri = "/" + uri
}
uri = c.Endpoint + uri
}
req, err := http.NewRequest(method, uri, body)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "Go-Onfido/"+ClientVersion)
req.Header.Set("Authorization", "Token token="+c.Token.String())
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
return req, nil
}
func (c *Client) do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error) {
req = req.WithContext(ctx)
resp, err := c.HTTPClient.Do(req)
if err != nil {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
return nil, err
}
}
if resp.Body != nil {
defer resp.Body.Close()
}
if c := resp.StatusCode; c < 200 || c > 299 {
return nil, handleResponseErr(resp)
}
if v != nil {
if w, ok := v.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
} else if isJSONResponse(resp) {
err = json.NewDecoder(resp.Body).Decode(v)
} else {
err = fmt.Errorf("unable to parse respose body into %T", v)
}
}
return resp, err
}
func isJSONResponse(resp *http.Response) bool {
return strings.Contains(resp.Header.Get("Content-Type"), "application/json")
}
func handleResponseErr(resp *http.Response) error {
var onfidoErr Error
if resp.Body != nil && isJSONResponse(resp) {
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&onfidoErr); err != nil {
return err
}
} else {
onfidoErr = Error{}
}
onfidoErr.Resp = resp
return &onfidoErr
}
type iter struct {
c *Client
nextURL string
handler iterHandler
values []interface{}
cur interface{}
err error
}
type iterHandler func(body []byte) ([]interface{}, error)
func (it *iter) Current() interface{} {
return it.cur
}
func (it *iter) Err() error {
return it.err
}
func (it *iter) Next(ctx context.Context) bool {
if it.err != nil {
return false
}
if len(it.values) == 0 && it.nextURL != "" {
req, err := it.c.newRequest("GET", it.nextURL, nil)
if err != nil {
it.err = err
return false
}
var body bytes.Buffer
resp, err := it.c.do(ctx, req, &body)
if err != nil {
it.err = err
return false
}
if !isJSONResponse(resp) {
it.err = errors.New("non json response")
return false
}
values, err := it.handler(body.Bytes())
if err != nil {
it.err = err
return false
}
it.values = values
links := linkheader.Parse(resp.Header.Get("Link"))
links = links.FilterByRel("next")
if len(links) > 0 {
it.nextURL = links[0].URL
} else {
it.nextURL = ""
}
}
if len(it.values) == 0 {
return false
}
it.cur = it.values[0]
it.values = it.values[1:]
return true
}