forked from uphold/uphold-sdk-javascript
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsdk.js
More file actions
194 lines (160 loc) · 5.68 KB
/
sdk.js
File metadata and controls
194 lines (160 loc) · 5.68 KB
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
import * as actions from './actions';
import { AuthorizationRequiredError, UnauthorizedError } from './errors';
import { OAuthClient, Paginator } from './services';
import { buildBearerAuthorizationHeader, buildUrl } from './utils';
import { get } from 'lodash';
export default class SDK {
constructor(options) {
if (!options) {
throw new Error(`Missing options`);
}
if (!options.clientId) {
throw new Error(`Missing 'clientId' option`);
}
if (!options.clientSecret) {
throw new Error(`Missing 'clientSecret' option`);
}
const defaultOptions = {
accessTokenKey: 'uphold.access_token',
baseUrl: 'https://api.uphold.com',
itemsPerPage: 10,
otpTokenStatus: 'uphold.otp_token_status',
refreshTokenKey: 'uphold.refresh_token',
scope: 'uphold.scope',
version: 'v0'
};
this.options = { ...defaultOptions, ...options };
this.refreshRequestPromise = null;
this.tokenRequestPromise = null;
// Instantiate oauth client.
this.oauthClient = new OAuthClient(this.options);
}
api(uri, options = {}) {
const { authenticate = true, headers = {}, method = 'get', queryParams, raw, version = this.options.version } = options;
let { body } = options;
const url = buildUrl(uri, this.options.baseUrl, version, queryParams);
let request;
if (body) {
if (typeof body === 'object') {
body = JSON.stringify(body);
}
headers['content-type'] = 'application/json';
}
if (authenticate && !headers.authorization) {
request = this.getToken().then(tokens => {
return this.client.request(url, method, body, {
...buildBearerAuthorizationHeader(tokens.access_token),
...headers
}, options);
});
} else {
request = this.client.request(url, method, body, headers, options);
}
return request
.then(data => { return raw ? data : data.body; })
.catch(this._refreshToken(url, method, body, headers, options));
}
authorize(code) {
const accessTokenRequest = this.oauthClient.buildAccessTokenRequestByAuthorizationCodeGrant(code);
this.tokenRequestPromise = this._authenticationRequest(accessTokenRequest);
return this.tokenRequestPromise;
}
getToken() {
return this.storage.getItem(this.options.accessTokenKey)
.then(access_token => {
if (!access_token) {
this.tokenRequestPromise = null;
return Promise.reject();
}
return this.storage.getItem(this.options.refreshTokenKey)
.then(refresh_token => ({
access_token,
refresh_token
}))
// Do not reject if refresh token does not exist.
.catch(() => ({ access_token }));
})
.catch(() => {
// If there is a token request in progress, we wait for it.
if (this.tokenRequestPromise) {
return this.tokenRequestPromise;
}
// There was never a token request.
return Promise.reject(new AuthorizationRequiredError());
});
}
logout() {
return this._revokeToken()
.catch(e => {
// Do not reject an attempt to revoke an invalid token.
if (!(e instanceof UnauthorizedError)) {
return Promise.reject(e);
}
})
.then(() => this.removeToken());
}
paginate(url, page = 1, itemsPerPage = this.options.itemsPerPage, options) {
return new Paginator(this, url, itemsPerPage, options).getPage(page);
}
removeToken() {
return Promise.all([
this.storage.removeItem(this.options.accessTokenKey),
this.storage.removeItem(this.options.refreshTokenKey)
]);
}
setToken(token, headers = {}) {
return this.storage.setItem(this.options.accessTokenKey, token.access_token)
.then(() => {
this.storage.setItem(this.options.scope, get(token, 'scope', ''));
this.storage.setItem(this.options.otpTokenStatus, get(headers, 'otp-token', ''));
if (token.refresh_token) {
this.storage.setItem(this.options.refreshTokenKey, token.refresh_token);
}
})
.then(() => token);
}
_authenticationRequest({ body, headers, url }) {
return this.client.request(url, 'post', body, headers)
.then(({ body, headers }) => this.setToken(body, headers));
}
_refreshToken(url, method, body, headers, options) { // eslint-disable-line max-params
return response => {
if (!response || !response.body || response.body.error !== 'invalid_token') {
return Promise.reject(response);
}
if (!this.refreshRequestPromise) {
this.refreshRequestPromise = this._requestRefreshToken(response);
}
return this.refreshRequestPromise
.then(tokens => {
return this.client.request(url, method, body, {
...buildBearerAuthorizationHeader(tokens.access_token),
...headers
}, options)
.then(data => data.body);
});
};
}
_requestRefreshToken(response) {
return this.storage.getItem(this.options.refreshTokenKey)
.catch(() => Promise.reject(response))
.then(refreshToken => {
const refreshTokenRequest = this.oauthClient.buildRefreshTokenRequest(refreshToken);
return this._authenticationRequest(refreshTokenRequest)
.then(tokens => {
this.refreshRequestPromise = null;
return tokens;
});
});
}
_revokeToken() {
return this.getToken()
.then(tokens => {
const { body, headers, url } = this.oauthClient.buildRevokeTokenRequest(tokens.access_token);
return this.client.request(url, 'post', body, headers);
});
}
}
for (const action in actions) {
SDK.prototype[action] = actions[action];
}