-
Notifications
You must be signed in to change notification settings - Fork 1
/
ims-client.js
254 lines (216 loc) · 7.72 KB
/
ims-client.js
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
/*
* Copyright 2024 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import { createUrl } from '@adobe/fetch';
import { hasText, isObject } from '@adobe/spacecat-shared-utils';
import {
createFormData, emailAddressIsAllowed,
extractIdAndAuthSource,
fetch as httpFetch, getGroupMembersEndpoint,
getImsOrgsApiPath,
IMS_PRODUCT_CONTEXT_BY_ORG_ENDPOINT, IMS_TOKEN_ENDPOINT,
} from '../utils.js';
export default class ImsClient {
static createFrom(context) {
const { log = console } = context;
const {
IMS_HOST: imsHost,
IMS_CLIENT_ID: clientId,
IMS_CLIENT_CODE: clientCode,
IMS_CLIENT_SECRET: clientSecret,
} = context.env;
if (!hasText(imsHost) || !hasText(clientId) || !hasText(clientCode) || !hasText(clientSecret)) {
throw new Error('Context param must include properties: imsHost, clientId, clientCode, and'
+ ' clientSecret.');
}
return new ImsClient({
imsHost,
clientId,
clientCode,
clientSecret,
}, log);
}
/**
* Creates a new Ims client
*
* @param {Object} config - The configuration object.
* @param {string} config.imsHost - The IMS host.
* @param {string} config.clientId - The IMS client ID.
* @param {string} config.clientCode - The IMS client code.
* @param {string} config.clientSecret - The IMS client secret.
* @param {Object} log - The Logger.
* @returns {ImsClient} - the Ims client.
*/
constructor(config, log) {
this.config = config;
this.log = log;
this.serviceAccessToken = null;
}
#logDuration(message, startTime) {
const endTime = process.hrtime.bigint();
const duration = (endTime - startTime) / BigInt(1e6);
this.log.debug(`${message}: took ${duration}ms`);
}
async #prepareImsRequestHeaders(noContentType = false) {
const imsToken = await this.getServiceAccessToken();
return {
...(noContentType ? {} : { 'Content-Type': 'application/json' }),
Authorization: `Bearer ${imsToken.access_token}`,
};
}
async #imsApiCall(
endpoint,
queryString = {},
body = null,
noContentType = false,
) {
const headers = await this.#prepareImsRequestHeaders(noContentType);
return httpFetch(
createUrl(`https://${this.config.imsHost}${endpoint}`, queryString),
{
...(isObject(body) ? { method: 'POST' } : { method: 'GET' }),
headers,
...(isObject(body) ? { body: createFormData(body) } : {}),
},
);
}
async #getImsOrgDetails(imsOrgId) {
const orgDetailsResponse = await this.#imsApiCall(
getImsOrgsApiPath(imsOrgId),
{ client_id: this.config.clientId },
);
if (!orgDetailsResponse.ok) {
throw new Error(`IMS getImsOrgDetails request failed with status: ${orgDetailsResponse.status}`);
}
return orgDetailsResponse.json();
}
async #getProductContextByImsOrgId(imsOrgId) {
const { orgId, authSource } = extractIdAndAuthSource(imsOrgId);
const pcResponse = await this.#imsApiCall(
IMS_PRODUCT_CONTEXT_BY_ORG_ENDPOINT,
{},
{
org_id: orgId,
auth_src: authSource,
client_id: this.config.clientId,
},
true,
);
if (!pcResponse.ok) {
throw new Error(`IMS getProductContextsByImsOrgId request failed with status: ${pcResponse.status}`);
}
const pcData = await pcResponse.json();
// Always return the first product context item
return pcData?.productContexts?.[0];
}
async #getUsersByImsGroupId(imsOrgId, groupId) {
// This endpoint is paginated, but the default page limit is 50 entries — more than enough
// for our use case
const groupResponse = await this.#imsApiCall(
getGroupMembersEndpoint(imsOrgId, groupId),
{ client_id: this.config.clientId },
);
if (!groupResponse.ok) {
throw new Error(`IMS getUsersByImsGroupId request failed with status: ${groupResponse.status}`);
}
const group = await groupResponse.json();
return group.items || [];
}
async #getUsersInAdminGroup(imsOrgId, groups) {
if (!Array.isArray(groups)) {
return [];
}
// Store users by their email address initially to de-dupe the entries
const users = {};
for (const group of groups) {
// Only process Administrators groups
if (group?.role === 'GRP_ADMIN') {
// eslint-disable-next-line no-await-in-loop
const groupUsers = await this.#getUsersByImsGroupId(imsOrgId, group?.ident);
for (const user of groupUsers) {
// Fallback to username if email is not set
const newUser = { ...user };
if (!hasText(newUser.email)) {
newUser.email = newUser.username;
}
if (emailAddressIsAllowed(newUser.email)) {
// Reduce fields in user object to those we need
users[newUser.email] = {
email: newUser.email,
firstName: newUser.firstName,
lastName: newUser.lastName,
};
}
}
}
}
// Transform the object "map" back to a de-duped array
return Object.keys(users).map((email) => users[email]);
}
async getServiceAccessToken() {
if (hasText(this.serviceAccessToken?.access_token)) {
return this.serviceAccessToken;
}
try {
const startTime = process.hrtime.bigint();
const tokenResponse = await httpFetch(
`https://${this.config.imsHost}${IMS_TOKEN_ENDPOINT}`,
{
method: 'POST',
body: createFormData({
client_id: this.config.clientId,
client_secret: this.config.clientSecret,
code: this.config.clientCode,
grant_type: 'authorization_code',
}),
},
);
this.#logDuration('IMS getServiceAccessToken request', startTime);
if (!tokenResponse.ok) {
throw new Error(`IMS getServiceAccessToken request failed with status: ${tokenResponse.status}`);
}
/* eslint-disable camelcase */
const { access_token, token_type, expires_in } = await tokenResponse.json();
this.serviceAccessToken = {
access_token,
expires_in,
token_type,
};
return this.serviceAccessToken;
} catch (error) {
this.log.error('Error while fetching data from Ims API: ', error.message);
throw error;
}
}
async getImsOrganizationDetails(imsOrgId) {
if (!hasText(imsOrgId)) {
throw new Error('imsOrgId param is required.');
}
// Request tenant ID from the IMS "product context"
const productContext = await this.#getProductContextByImsOrgId(imsOrgId);
const tenantId = productContext?.params?.tenant_id;
// Request organization details
const orgDetails = await this.#getImsOrgDetails(imsOrgId);
const orgName = orgDetails?.orgName;
this.log.debug(`IMS Org ID ${imsOrgId} has tenantId: ${tenantId}, name: "${orgName}"`);
// Fetch a list of all users in the Administrators group
const admins = await this.#getUsersInAdminGroup(imsOrgId, orgDetails?.groups);
this.log.debug(`IMS Org ID ${imsOrgId} has ${admins.length} known admin users.`);
return {
imsOrgId,
tenantId,
orgName,
orgType: orgDetails?.orgType,
countryCode: orgDetails?.countryCode,
admins,
};
}
}