-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathextension.js
More file actions
282 lines (237 loc) · 10.2 KB
/
Copy pathextension.js
File metadata and controls
282 lines (237 loc) · 10.2 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
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
'use strict';
const validator = require('validator');
const { FdkInvalidExtensionConfig } = require("./error_code");
const urljoin = require('url-join');
const { PlatformClient, PartnerClient } = require("@gofynd/fdk-client-javascript");
const { WebhookRegistry } = require('./webhook');
const logger = require('./logger');
const { fdkAxios } = require('@gofynd/fdk-client-javascript/sdk/common/AxiosHelper');
const { version } = require('./../package.json');
const { RetryManger } = require("./retry_manager")
class Extension {
constructor() {
this.api_key = null;
this.api_secret = null;
this.storage = null;
this.base_url = null;
this.callbacks = null;
this.access_mode = null;
this.cluster = "https://api.fynd.com";
this.webhookRegistry = null;
this._isInitialized = false;
this._retryManager = new RetryManger();
this.configData = null;
}
async initialize(data) {
if (this._isInitialized) {
return;
}
this._isInitialized = false;
this.configData = data;
this.storage = data.storage;
if (!data.api_key) {
throw new FdkInvalidExtensionConfig("Invalid api_key");
}
this.api_key = data.api_key;
if (!data.api_secret) {
throw new FdkInvalidExtensionConfig("Invalid api_secret");
}
this.api_secret = data.api_secret;
if (!data.callbacks || (data.callbacks && (!data.callbacks.auth || !data.callbacks.uninstall))) {
throw new FdkInvalidExtensionConfig("Missing some of callbacks. Please add all `auth` and `uninstall` callbacks.");
}
this.callbacks = data.callbacks;
this.access_mode = data.access_mode || "offline";
if (data.cluster) {
if (!validator.isURL(data.cluster)) {
throw new FdkInvalidExtensionConfig("Invalid cluster value. Invalid value: " + data.cluster);
}
this.cluster = data.cluster;
}
else
data.cluster = this.cluster;
this.webhookRegistry = new WebhookRegistry(this._retryManager);
await this.getExtensionDetails();
if (data.base_url && !validator.isURL(data.base_url)) {
throw new FdkInvalidExtensionConfig("Invalid base_url value. Invalid value: " + data.base_url);
}
else if (!data.base_url) {
data.base_url = this.extensionData.base_url;
}
if (data.base_url && data.base_url !== this.extensionData.base_url) {
await this.updateExtensionBaseUrl(data.base_url);
}
this.base_url = data.base_url;
if (data.scopes) {
logger.warn(`'scopes' in setupFdk config is deprecated and will be ignored. Scopes from Partners panel will be used instead.`);
}
this.scopes = this.extensionData.scope;
logger.debug(`Extension initialized`);
if (data.webhook_config && Object.keys(data.webhook_config)) {
await this.webhookRegistry.initialize(data.webhook_config, data);
}
this._isInitialized = true;
}
get isInitialized() {
return this._isInitialized;
}
getAuthCallback() {
return urljoin(this.base_url, "/fp/auth");
}
isOnlineAccessMode() {
return this.access_mode === 'online';
}
async getPlatformConfig(companyId) {
if (!this._isInitialized){
await this.initialize(this.configData);
}
// Create client without session for OAuth operations only
let platformClient = new PlatformClient({
companyId: parseInt(companyId),
domain: this.cluster,
apiKey: this.api_key,
apiSecret: this.api_secret,
useAutoRenewTimer: false,
logLevel: this.configData.debug === true? "debug": null
});
return platformClient.config; // Return just the config
}
async getPlatformClient(companyId, session) {
if (!this._isInitialized){
await this.initialize(this.configData);
}
const SessionStorage = require('./session/session_storage');
let platformClient = new PlatformClient({
companyId: parseInt(companyId),
domain: this.cluster,
apiKey: this.api_key,
apiSecret: this.api_secret,
useAutoRenewTimer: false,
logLevel: this.configData.debug === true? "debug": null
});
platformClient.config.oauthClient.setToken(session);
platformClient.config.oauthClient.token_expires_at = session.access_token_validity;
if (!session.access_token_validity || session.refresh_token) {
let ac_nr_expired = !session.access_token_validity? true: ((session.access_token_validity - new Date().getTime()) / 1000) <= 120;
if (ac_nr_expired) {
logger.debug(`Renewing access token for company ${companyId}`);
const renewTokenRes = await platformClient.config.oauthClient.renewAccessToken(session.access_mode === 'offline');
renewTokenRes.access_token_validity = platformClient.config.oauthClient.token_expires_at;
session.updateToken(renewTokenRes);
await SessionStorage.saveSession(session);
logger.debug(`Access token renewed for company ${companyId}`);
}
}
platformClient.setExtraHeaders({
'x-ext-lib-version': `js/${version}`
})
return platformClient;
}
getPartnerConfig(organizationId) {
if (!this._isInitialized) {
throw new FdkInvalidExtensionConfig("Extension not initialized due to invalid data");
}
// Create client without session for OAuth operations only
let partnerClient = new PartnerClient({
organizationId: organizationId,
domain: this.cluster,
apiKey: this.api_key,
apiSecret: this.api_secret,
useAutoRenewTimer: false,
logLevel: this.configData.debug === true? "debug": null
});
return partnerClient.config; // Return just the config
}
async getPartnerClient(organizationId, session) {
if (!this._isInitialized) {
throw new FdkInvalidExtensionConfig('Extension not initialized due to invalid data')
}
const SessionStorage = require('./session/session_storage');
let partnerClient = new PartnerClient({
organizationId: organizationId,
domain: this.cluster,
apiKey: this.api_key,
apiSecret: this.api_secret,
useAutoRenewTimer: false,
logLevel: this.configData.debug === true? "debug": null
});
partnerClient.config.oauthClient.setToken(session);
partnerClient.config.oauthClient.token_expires_at = session.access_token_validity;
if (!session.access_token_validity || session.refresh_token) {
let ac_nr_expired = ((session.access_token_validity - new Date().getTime()) / 1000) <= 120;
if (ac_nr_expired) {
logger.debug(`Renewing access token for organization ${organizationId}`);
const renewTokenRes = await partnerClient.config.oauthClient.renewAccessToken(session.access_mode === 'offline');
renewTokenRes.access_token_validity = partnerClient.config.oauthClient.token_expires_at;
session.updateToken(renewTokenRes);
await SessionStorage.saveSession(session);
logger.debug(`Access token renewed for organization ${organizationId}`);
}
}
partnerClient.setExtraHeaders({
'x-ext-lib-version': `js/${version}`
})
return partnerClient;
}
async getExtensionDetails() {
let url = `${this.cluster}/service/panel/partners/v1.0/extensions/details/${this.api_key}`;
const uniqueKey = `${url}`;
const retryInfo = this._retryManager.retryInfoMap.get(uniqueKey);
if (retryInfo && !retryInfo.isRetry) {
this._retryManager.resetRetryState(uniqueKey);
}
try {
const token = Buffer.from(
`${this.api_key}:${this.api_secret}`,
"utf8"
).toString("base64");
const rawRequest = {
method: "GET",
url: url,
headers: {
Authorization: `Basic ${token}`,
"Content-Type": "application/json",
'x-ext-lib-version': `js/${version}`
},
};
let extensionData = await fdkAxios.request(rawRequest);
logger.debug(`Extension details received: ${logger.safeStringify(extensionData)}`);
this.extensionData = extensionData;
} catch (err) {
if (
RetryManger.shouldRetryOnError(err)
&& !this._retryManager.isRetryInProgress(uniqueKey)
) {
logger.debug(`API call failed. Starting retry for ${uniqueKey}`)
return await this._retryManager.retry(uniqueKey, this.getExtensionDetails.bind(this));
}
throw new FdkInvalidExtensionConfig("Invalid api_key or api_secret. Reason:" + err.message);
}
}
async updateExtensionBaseUrl(baseUrl) {
const url = `${this.cluster}/service/panel/partners/v1.0/extensions/details/${this.api_key}`;
const token = Buffer.from(
`${this.api_key}:${this.api_secret}`,
"utf8"
).toString("base64");
try {
await fdkAxios.request({
method: "PATCH",
url: url,
headers: {
Authorization: `Basic ${token}`,
"Content-Type": "application/json",
'x-ext-lib-version': `js/${version}`
},
data: { base_url: baseUrl }
});
logger.debug(`Extension base_url synced to platform: ${baseUrl}`);
} catch (err) {
logger.warn(`Failed to sync base_url to platform: ${err.message}`);
}
}
}
const extension = new Extension();
module.exports = {
extension
};