@iyio/aws-credential-providers 0.6.5 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,9 @@
1
- var _a;
2
- import { __awaiter } from "tslib";
3
1
  import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";
4
2
  import { awsRegionParam } from '@iyio/aws';
5
3
  import { UserFactory, authServicePopupOAuthSignOutMessageId, currentBaseUser, getPopupWindowMessageAsync, getUriProtocol, httpClient, parseConfigBool, parseJwt, promiseFromErrorResultCallback } from '@iyio/common';
6
4
  import { AuthenticationDetails, CognitoAccessToken, CognitoIdToken, CognitoRefreshToken, CognitoUser, CognitoUserAttribute, CognitoUserPool, CognitoUserSession } from 'amazon-cognito-identity-js';
7
5
  import { cognitoDomainPrefixParam, cognitoIdentityPoolIdParam, cognitoOAuthRedirectUriParam, cognitoOAuthScopesParams, cognitoUserPoolClientIdParam, cognitoUserPoolIdParam, disableCognitoUnauthenticatedParam } from './_types.aws-credential-providers';
8
- const trackIssuedCreds = parseConfigBool((_a = process.env['NX_TRACK_COGNITO_ISSUED_CREDS']) !== null && _a !== void 0 ? _a : process.env['NX_PUBLIC_TRACK_COGNITO_ISSUED_CREDS']);
6
+ const trackIssuedCreds = parseConfigBool(process.env['NX_TRACK_COGNITO_ISSUED_CREDS'] ?? process.env['NX_PUBLIC_TRACK_COGNITO_ISSUED_CREDS']);
9
7
  /**
10
8
  * Used for testing
11
9
  */
@@ -27,28 +25,27 @@ export class CognitoAuthProvider {
27
25
  constructor(config) {
28
26
  this.type = CognitoAuthProviderType;
29
27
  this.unCreds = null;
30
- this.getCredentials = () => __awaiter(this, void 0, void 0, function* () {
31
- var _a, _b;
28
+ this.getCredentials = async () => {
32
29
  const user = this.currentUser.value;
33
30
  if (!user) {
34
31
  if (disableCognitoUnauthenticatedParam.get()) {
35
32
  throw new Error('Unauthenticated cognito users disabled');
36
33
  }
37
- return yield this.getUnauthenticatedCredentials()();
34
+ return await this.getUnauthenticatedCredentials()();
38
35
  }
39
- let session = (_a = user.providerData.providerData) === null || _a === void 0 ? void 0 : _a[sessionKey];
36
+ let session = user.providerData.providerData?.[sessionKey];
40
37
  if (!session) {
41
38
  if (disableCognitoUnauthenticatedParam.get()) {
42
39
  throw new Error('Unauthenticated cognito users disabled');
43
40
  }
44
- return yield this.getUnauthenticatedCredentials()();
41
+ return await this.getUnauthenticatedCredentials()();
45
42
  }
46
43
  if (!session.isValid()) {
47
44
  console.info('getAuthProvider', 'refresh session');
48
- const cognitoUser = (_b = user.providerData.providerData) === null || _b === void 0 ? void 0 : _b[userKey];
45
+ const cognitoUser = user.providerData.providerData?.[userKey];
49
46
  if (cognitoUser) {
50
47
  const refreshToken = session.getRefreshToken();
51
- const newSession = yield promiseFromErrorResultCallback(cb => cognitoUser.refreshSession(refreshToken, cb));
48
+ const newSession = await promiseFromErrorResultCallback(cb => cognitoUser.refreshSession(refreshToken, cb));
52
49
  if (newSession) {
53
50
  session = newSession;
54
51
  if (user.providerData.providerData) {
@@ -70,8 +67,8 @@ export class CognitoAuthProvider {
70
67
  if (trackIssuedCreds) {
71
68
  _allIssuedCognitoCreds.push(provider);
72
69
  }
73
- return yield provider();
74
- });
70
+ return await provider();
71
+ };
75
72
  this.userPool = new CognitoUserPool(config);
76
73
  this.config = config;
77
74
  this.currentUser = config.currentUser;
@@ -90,227 +87,200 @@ export class CognitoAuthProvider {
90
87
  getAuthProvider() {
91
88
  return this.getCredentials;
92
89
  }
93
- getCurrentUser() {
94
- return __awaiter(this, void 0, void 0, function* () {
95
- try {
96
- const cognitoUser = this.userPool.getCurrentUser();
97
- if (cognitoUser) {
98
- const user = yield this.convertCognitoUserAsync(cognitoUser);
99
- return user !== null && user !== void 0 ? user : null;
100
- }
101
- }
102
- catch (ex) {
103
- console.error('User initialization failed', ex);
90
+ async getCurrentUser() {
91
+ try {
92
+ const cognitoUser = this.userPool.getCurrentUser();
93
+ if (cognitoUser) {
94
+ const user = await this.convertCognitoUserAsync(cognitoUser);
95
+ return user ?? null;
104
96
  }
105
- return null;
106
- });
97
+ }
98
+ catch (ex) {
99
+ console.error('User initialization failed', ex);
100
+ }
101
+ return null;
107
102
  }
108
- convertCognitoUserAsync(user) {
109
- return __awaiter(this, void 0, void 0, function* () {
110
- var _a, _b, _c;
111
- let session = yield promiseFromErrorResultCallback(cb => user.getSession(cb));
112
- if (session) {
113
- if (!session.isValid()) {
114
- const refreshToken = session.getRefreshToken();
115
- const newSession = yield promiseFromErrorResultCallback(cb => user.refreshSession(refreshToken, cb));
116
- if (newSession) {
117
- session = newSession;
118
- }
119
- }
120
- const atts = yield promiseFromErrorResultCallback(cb => user.getUserAttributes(cb));
121
- const id = user.getUsername();
122
- const data = {};
123
- if (atts) {
124
- for (const att of atts) {
125
- data[att.Name] = att.Value;
126
- }
103
+ async convertCognitoUserAsync(user) {
104
+ let session = await promiseFromErrorResultCallback(cb => user.getSession(cb));
105
+ if (session) {
106
+ if (!session.isValid()) {
107
+ const refreshToken = session.getRefreshToken();
108
+ const newSession = await promiseFromErrorResultCallback(cb => user.refreshSession(refreshToken, cb));
109
+ if (newSession) {
110
+ session = newSession;
127
111
  }
128
- const name = (_a = data['nickname']) !== null && _a !== void 0 ? _a : id;
129
- const email = data['email'];
130
- const phoneNumber = (_c = (_b = data['phone']) !== null && _b !== void 0 ? _b : data['phone_number']) !== null && _c !== void 0 ? _c : data['phoneNumber'];
131
- const options = {
132
- id,
133
- name,
134
- email,
135
- phoneNumber,
136
- data,
137
- providerData: {
138
- type: this.type,
139
- userId: id,
140
- providerData: {
141
- [sessionKey]: session,
142
- [userKey]: user
143
- }
144
- },
145
- provider: this
146
- };
147
- const baseUser = this.config.userFactory.generate(options);
148
- if (!baseUser) {
149
- throw new Error('No user factory provided a user');
112
+ }
113
+ const atts = await promiseFromErrorResultCallback(cb => user.getUserAttributes(cb));
114
+ const id = user.getUsername();
115
+ const data = {};
116
+ if (atts) {
117
+ for (const att of atts) {
118
+ data[att.Name] = att.Value;
150
119
  }
151
- return baseUser;
152
120
  }
153
- else {
154
- throw new Error('Unable to get user session');
121
+ const name = data['nickname'] ?? id;
122
+ const email = data['email'];
123
+ const phoneNumber = data['phone'] ?? data['phone_number'] ?? data['phoneNumber'];
124
+ const options = {
125
+ id,
126
+ name,
127
+ email,
128
+ phoneNumber,
129
+ data,
130
+ providerData: {
131
+ type: this.type,
132
+ userId: id,
133
+ providerData: {
134
+ [sessionKey]: session,
135
+ [userKey]: user
136
+ }
137
+ },
138
+ provider: this
139
+ };
140
+ const baseUser = this.config.userFactory.generate(options);
141
+ if (!baseUser) {
142
+ throw new Error('No user factory provided a user');
155
143
  }
156
- });
144
+ return baseUser;
145
+ }
146
+ else {
147
+ throw new Error('Unable to get user session');
148
+ }
157
149
  }
158
- getIdentitiesAsync(user) {
159
- return __awaiter(this, void 0, void 0, function* () {
160
- try {
161
- const atts = yield promiseFromErrorResultCallback(cb => user.getUserAttributes(cb));
162
- if (!atts) {
163
- return undefined;
164
- }
165
- const idAtt = atts.find(a => a.Name === 'identities');
166
- if (!idAtt) {
167
- return undefined;
168
- }
169
- try {
170
- const identities = JSON.parse(idAtt.Value);
171
- return identities !== null && identities !== void 0 ? identities : ((typeof identities === 'object') ? identities : undefined);
172
- }
173
- catch (_a) {
174
- return undefined;
175
- }
150
+ async getIdentitiesAsync(user) {
151
+ try {
152
+ const atts = await promiseFromErrorResultCallback(cb => user.getUserAttributes(cb));
153
+ if (!atts) {
154
+ return undefined;
176
155
  }
177
- catch (_b) {
156
+ const idAtt = atts.find(a => a.Name === 'identities');
157
+ if (!idAtt) {
178
158
  return undefined;
179
159
  }
180
- });
181
- }
182
- getUserAsync(data) {
183
- return __awaiter(this, void 0, void 0, function* () {
184
- var _a;
185
- const user = (_a = data.providerData) === null || _a === void 0 ? void 0 : _a[userKey];
186
- if (!user) {
187
- if (!data.userId) {
188
- return null;
189
- }
190
- const currentUser = yield this.getCurrentUser();
191
- return (currentUser === null || currentUser === void 0 ? void 0 : currentUser.id) === data.userId ? currentUser : null;
160
+ try {
161
+ const identities = JSON.parse(idAtt.Value);
162
+ return identities ?? ((typeof identities === 'object') ? identities : undefined);
192
163
  }
193
- return yield this.convertCognitoUserAsync(user);
194
- });
195
- }
196
- deleteAsync(user) {
197
- return __awaiter(this, void 0, void 0, function* () {
198
- var _a;
199
- const cUser = (_a = user.providerData.providerData) === null || _a === void 0 ? void 0 : _a[userKey];
200
- if (!cUser) {
201
- return;
164
+ catch {
165
+ return undefined;
202
166
  }
203
- return yield new Promise((resolve) => {
204
- cUser.deleteUser((err) => {
205
- if (err) {
206
- resolve({
207
- status: 'error',
208
- message: 'Delete user failed',
209
- error: err
210
- });
211
- }
212
- else {
213
- resolve({
214
- status: 'success'
215
- });
216
- }
217
- });
218
- });
219
- });
167
+ }
168
+ catch {
169
+ return undefined;
170
+ }
220
171
  }
221
- signOutAsync(user) {
222
- return __awaiter(this, void 0, void 0, function* () {
223
- var _a;
224
- const cUser = (_a = user.providerData.providerData) === null || _a === void 0 ? void 0 : _a[userKey];
225
- if (!cUser) {
226
- return;
172
+ async getUserAsync(data) {
173
+ const user = data.providerData?.[userKey];
174
+ if (!user) {
175
+ if (!data.userId) {
176
+ return null;
227
177
  }
228
- const prefix = cognitoDomainPrefixParam.get();
229
- if (prefix) {
230
- const ids = yield this.getIdentitiesAsync(cUser);
231
- if (ids) {
232
- const url = (`https://${prefix}.auth.${awsRegionParam()}.amazoncognito.com/logout?client_id=${cognitoUserPoolClientIdParam()}&logout_uri=${this.getOAuthRedirectUri()}`);
233
- yield getPopupWindowMessageAsync({
234
- url,
235
- triggerOnSameHost: true,
236
- timeoutMs: 30000,
237
- messageId: authServicePopupOAuthSignOutMessageId
178
+ const currentUser = await this.getCurrentUser();
179
+ return currentUser?.id === data.userId ? currentUser : null;
180
+ }
181
+ return await this.convertCognitoUserAsync(user);
182
+ }
183
+ async deleteAsync(user) {
184
+ const cUser = user.providerData.providerData?.[userKey];
185
+ if (!cUser) {
186
+ return;
187
+ }
188
+ return await new Promise((resolve) => {
189
+ cUser.deleteUser((err) => {
190
+ if (err) {
191
+ resolve({
192
+ status: 'error',
193
+ message: 'Delete user failed',
194
+ error: err
195
+ });
196
+ }
197
+ else {
198
+ resolve({
199
+ status: 'success'
238
200
  });
239
201
  }
240
- }
241
- yield new Promise((resolve) => {
242
- cUser.signOut(() => resolve());
243
202
  });
244
203
  });
245
204
  }
246
- getJwtAsync(data) {
247
- return __awaiter(this, void 0, void 0, function* () {
248
- var _a, _b, _c, _d;
249
- return (_d = (_c = (_b = (_a = data.providerData) === null || _a === void 0 ? void 0 : _a[sessionKey]) === null || _b === void 0 ? void 0 : _b.getIdToken()) === null || _c === void 0 ? void 0 : _c.getJwtToken()) !== null && _d !== void 0 ? _d : null;
250
- });
251
- }
252
- getClaimsAsync(data) {
253
- return __awaiter(this, void 0, void 0, function* () {
254
- const jwt = yield this.getJwtAsync(data);
255
- if (!jwt) {
256
- return null;
205
+ async signOutAsync(user) {
206
+ const cUser = user.providerData.providerData?.[userKey];
207
+ if (!cUser) {
208
+ return;
209
+ }
210
+ const prefix = cognitoDomainPrefixParam.get();
211
+ if (prefix) {
212
+ const ids = await this.getIdentitiesAsync(cUser);
213
+ if (ids) {
214
+ const url = (`https://${prefix}.auth.${awsRegionParam()}.amazoncognito.com/logout?client_id=${cognitoUserPoolClientIdParam()}&logout_uri=${this.getOAuthRedirectUri()}`);
215
+ await getPopupWindowMessageAsync({
216
+ url,
217
+ triggerOnSameHost: true,
218
+ timeoutMs: 30000,
219
+ messageId: authServicePopupOAuthSignOutMessageId
220
+ });
257
221
  }
258
- return parseJwt(jwt);
222
+ }
223
+ await new Promise((resolve) => {
224
+ cUser.signOut(() => resolve());
259
225
  });
260
226
  }
261
- signInWithTokenAsync(token) {
262
- return __awaiter(this, void 0, void 0, function* () {
263
- var _a, _b, _c, _d;
264
- const idToken = (_a = token === null || token === void 0 ? void 0 : token.IdToken) !== null && _a !== void 0 ? _a : token === null || token === void 0 ? void 0 : token.id_token;
265
- const accessToken = (_b = token === null || token === void 0 ? void 0 : token.AccessToken) !== null && _b !== void 0 ? _b : token === null || token === void 0 ? void 0 : token.access_token;
266
- const refreshToken = (_c = token === null || token === void 0 ? void 0 : token.RefreshToken) !== null && _c !== void 0 ? _c : token === null || token === void 0 ? void 0 : token.refresh_token;
267
- const session = new CognitoUserSession({
268
- IdToken: (typeof idToken === 'string') ? new CognitoIdToken({ IdToken: idToken }) : idToken,
269
- AccessToken: (typeof accessToken === 'string') ? new CognitoAccessToken({ AccessToken: accessToken }) : accessToken,
270
- RefreshToken: (typeof refreshToken === 'string') ? new CognitoRefreshToken({ RefreshToken: refreshToken }) : refreshToken,
271
- });
272
- if (!session.isValid()) {
273
- return {
274
- success: false,
275
- message: 'Invalid session from token'
276
- };
277
- }
278
- const cognitoUser = new CognitoUser({
279
- Username: (_d = session.getAccessToken().payload['username']) !== null && _d !== void 0 ? _d : 'user',
280
- Pool: this.userPool,
281
- });
282
- cognitoUser.setSignInUserSession(session);
283
- const user = yield this.convertCognitoUserAsync(cognitoUser);
227
+ async getJwtAsync(data) {
228
+ return data.providerData?.[sessionKey]?.getIdToken()?.getJwtToken() ?? null;
229
+ }
230
+ async getClaimsAsync(data) {
231
+ const jwt = await this.getJwtAsync(data);
232
+ if (!jwt) {
233
+ return null;
234
+ }
235
+ return parseJwt(jwt);
236
+ }
237
+ async signInWithTokenAsync(token) {
238
+ const idToken = token?.IdToken ?? token?.id_token;
239
+ const accessToken = token?.AccessToken ?? token?.access_token;
240
+ const refreshToken = token?.RefreshToken ?? token?.refresh_token;
241
+ const session = new CognitoUserSession({
242
+ IdToken: (typeof idToken === 'string') ? new CognitoIdToken({ IdToken: idToken }) : idToken,
243
+ AccessToken: (typeof accessToken === 'string') ? new CognitoAccessToken({ AccessToken: accessToken }) : accessToken,
244
+ RefreshToken: (typeof refreshToken === 'string') ? new CognitoRefreshToken({ RefreshToken: refreshToken }) : refreshToken,
245
+ });
246
+ if (!session.isValid()) {
284
247
  return {
285
- success: true,
286
- user,
248
+ success: false,
249
+ message: 'Invalid session from token'
287
250
  };
251
+ }
252
+ const cognitoUser = new CognitoUser({
253
+ Username: session.getAccessToken().payload['username'] ?? 'user',
254
+ Pool: this.userPool,
288
255
  });
256
+ cognitoUser.setSignInUserSession(session);
257
+ const user = await this.convertCognitoUserAsync(cognitoUser);
258
+ return {
259
+ success: true,
260
+ user,
261
+ };
289
262
  }
290
263
  getOAuthRedirectUri() {
291
- var _a, _b, _c, _d;
292
264
  let redirectUri = cognitoOAuthRedirectUriParam();
293
265
  if (!getUriProtocol(redirectUri)) {
294
266
  if (redirectUri.startsWith('/')) {
295
267
  redirectUri = redirectUri.substring(1);
296
268
  }
297
- redirectUri = `${(_b = (_a = globalThis.location) === null || _a === void 0 ? void 0 : _a.protocol) !== null && _b !== void 0 ? _b : 'https:'}//${(_d = (_c = globalThis.location) === null || _c === void 0 ? void 0 : _c.host) !== null && _d !== void 0 ? _d : 'localhost'}/${redirectUri}`;
269
+ redirectUri = `${globalThis.location?.protocol ?? 'https:'}//${globalThis.location?.host ?? 'localhost'}/${redirectUri}`;
298
270
  }
299
271
  return redirectUri;
300
272
  }
301
- signInWithCodeAsync(code) {
302
- return __awaiter(this, void 0, void 0, function* () {
303
- const token = yield httpClient().postAsync(`https://${cognitoDomainPrefixParam()}.auth.${awsRegionParam()}.amazoncognito.com/oauth2/token`, {
304
- code,
305
- client_id: cognitoUserPoolClientIdParam(),
306
- grant_type: 'authorization_code',
307
- redirect_uri: this.getOAuthRedirectUri(),
308
- }, {
309
- urlEncodeBody: true,
310
- noAuth: true,
311
- });
312
- return yield this.signInWithTokenAsync(token);
273
+ async signInWithCodeAsync(code) {
274
+ const token = await httpClient().postAsync(`https://${cognitoDomainPrefixParam()}.auth.${awsRegionParam()}.amazoncognito.com/oauth2/token`, {
275
+ code,
276
+ client_id: cognitoUserPoolClientIdParam(),
277
+ grant_type: 'authorization_code',
278
+ redirect_uri: this.getOAuthRedirectUri(),
279
+ }, {
280
+ urlEncodeBody: true,
281
+ noAuth: true,
313
282
  });
283
+ return await this.signInWithTokenAsync(token);
314
284
  }
315
285
  getOAuthSignInLinkUrl(provider, options) {
316
286
  const prefix = cognitoDomainPrefixParam.get();
@@ -318,109 +288,104 @@ export class CognitoAuthProvider {
318
288
  return undefined;
319
289
  }
320
290
  const scopes = (typeof options['scopes'] === 'string') ? options['scopes'] : undefined;
321
- return (`https://${prefix}.auth.${awsRegionParam()}.amazoncognito.com/oauth2/authorize?client_id=${cognitoUserPoolClientIdParam()}&response_type=code&scope=${encodeURIComponent((scopes !== null && scopes !== void 0 ? scopes : cognitoOAuthScopesParams()).split(',').map(s => s.trim()).join(' '))}&redirect_uri=${encodeURIComponent(this.getOAuthRedirectUri())}`);
291
+ return (`https://${prefix}.auth.${awsRegionParam()}.amazoncognito.com/oauth2/authorize?client_id=${cognitoUserPoolClientIdParam()}&response_type=code&scope=${encodeURIComponent((scopes ?? cognitoOAuthScopesParams()).split(',').map(s => s.trim()).join(' '))}&redirect_uri=${encodeURIComponent(this.getOAuthRedirectUri())}`);
322
292
  }
323
- signInEmailPasswordAsync(email, password, newPassword) {
324
- return __awaiter(this, void 0, void 0, function* () {
325
- return new Promise((resolve) => {
326
- const details = new AuthenticationDetails({
327
- Username: email,
328
- Password: password
329
- });
330
- const cognitoUser = new CognitoUser({
331
- Username: email,
332
- Pool: this.userPool,
333
- });
334
- const callbacks = {
335
- onSuccess: (session, confirmationNeeded) => __awaiter(this, void 0, void 0, function* () {
336
- if (confirmationNeeded) {
337
- resolve({
338
- success: false,
339
- message: 'Confirmation required'
340
- });
341
- return;
342
- }
343
- const user = yield this.convertCognitoUserAsync(cognitoUser);
293
+ async signInEmailPasswordAsync(email, password, newPassword) {
294
+ return new Promise((resolve) => {
295
+ const details = new AuthenticationDetails({
296
+ Username: email,
297
+ Password: password
298
+ });
299
+ const cognitoUser = new CognitoUser({
300
+ Username: email,
301
+ Pool: this.userPool,
302
+ });
303
+ const callbacks = {
304
+ onSuccess: async (session, confirmationNeeded) => {
305
+ if (confirmationNeeded) {
344
306
  resolve({
345
- success: true,
346
- user
307
+ success: false,
308
+ message: 'Confirmation required'
347
309
  });
348
- }),
349
- onFailure: (err) => {
310
+ return;
311
+ }
312
+ const user = await this.convertCognitoUserAsync(cognitoUser);
313
+ resolve({
314
+ success: true,
315
+ user
316
+ });
317
+ },
318
+ onFailure: (err) => {
319
+ resolve({
320
+ success: false,
321
+ message: 'Sign-in failed',
322
+ error: err
323
+ });
324
+ },
325
+ newPasswordRequired: () => {
326
+ if (newPassword) {
327
+ cognitoUser.completeNewPasswordChallenge(newPassword, {}, callbacks);
328
+ }
329
+ else {
350
330
  resolve({
351
331
  success: false,
352
- message: 'Sign-in failed',
353
- error: err
332
+ message: 'New password required'
354
333
  });
355
- },
356
- newPasswordRequired: () => {
357
- if (newPassword) {
358
- cognitoUser.completeNewPasswordChallenge(newPassword, {}, callbacks);
359
- }
360
- else {
361
- resolve({
362
- success: false,
363
- message: 'New password required'
364
- });
365
- }
366
334
  }
367
- };
368
- cognitoUser.authenticateUser(details, callbacks);
369
- });
335
+ }
336
+ };
337
+ cognitoUser.authenticateUser(details, callbacks);
370
338
  });
371
339
  }
372
- registerEmailPasswordAsync(email, password, userData) {
373
- return __awaiter(this, void 0, void 0, function* () {
374
- return new Promise((resolve) => {
375
- var _a, _b;
376
- const atts = [
377
- new CognitoUserAttribute({
378
- Name: 'email',
379
- Value: email
380
- })
381
- ];
382
- if (userData) {
383
- for (const e in userData) {
384
- if (!atts.find(a => a.Name === e)) {
385
- atts.push(new CognitoUserAttribute({
386
- Name: e,
387
- Value: (_b = (_a = userData[e]) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '',
388
- }));
389
- }
340
+ async registerEmailPasswordAsync(email, password, userData) {
341
+ return new Promise((resolve) => {
342
+ const atts = [
343
+ new CognitoUserAttribute({
344
+ Name: 'email',
345
+ Value: email
346
+ })
347
+ ];
348
+ if (userData) {
349
+ for (const e in userData) {
350
+ if (!atts.find(a => a.Name === e)) {
351
+ atts.push(new CognitoUserAttribute({
352
+ Name: e,
353
+ Value: userData[e]?.toString() ?? '',
354
+ }));
390
355
  }
391
356
  }
392
- this.userPool.signUp(email, password, atts, [], (err, result) => __awaiter(this, void 0, void 0, function* () {
393
- if (err || !(result === null || result === void 0 ? void 0 : result.user)) {
357
+ }
358
+ this.userPool.signUp(email, password, atts, [], async (err, result) => {
359
+ if (err || !result?.user) {
360
+ resolve({
361
+ status: 'error',
362
+ message: 'Register failed',
363
+ error: err
364
+ });
365
+ }
366
+ else if (result.userConfirmed) {
367
+ const result = await this.signInEmailPasswordAsync(email, password);
368
+ if (result.success) {
394
369
  resolve({
395
- status: 'error',
396
- message: 'Register failed',
397
- error: err
370
+ status: 'success',
371
+ user: result.user
398
372
  });
399
373
  }
400
- else if (result.userConfirmed) {
401
- const result = yield this.signInEmailPasswordAsync(email, password);
402
- if (result.success) {
403
- resolve({
404
- status: 'success',
405
- user: result.user
406
- });
407
- }
408
- else {
409
- resolve({
410
- status: 'error',
411
- message: result.success === false ? result.message : 'error',
412
- error: result.success === false ? result.error : null
413
- });
414
- }
415
- }
416
374
  else {
417
375
  resolve({
418
- status: 'verificationRequired',
419
- message: `A verification code has been sent to ${email}`,
420
- verificationDestination: email
376
+ status: 'error',
377
+ message: result.success === false ? result.message : 'error',
378
+ error: result.success === false ? result.error : null
421
379
  });
422
380
  }
423
- }));
381
+ }
382
+ else {
383
+ resolve({
384
+ status: 'verificationRequired',
385
+ message: `A verification code has been sent to ${email}`,
386
+ verificationDestination: email
387
+ });
388
+ }
424
389
  });
425
390
  });
426
391
  }
@@ -461,90 +426,79 @@ export class CognitoAuthProvider {
461
426
  });
462
427
  });
463
428
  }
464
- updateAsync(user, update) {
465
- return __awaiter(this, void 0, void 0, function* () {
466
- var _a;
467
- const cUser = (_a = user.providerData.providerData) === null || _a === void 0 ? void 0 : _a[userKey];
468
- if (!cUser) {
469
- return false;
470
- }
471
- const atts = [];
472
- const add = (name, value) => {
473
- if (!atts.some(a => a.Name === name)) {
474
- atts.push({ Name: name, Value: value });
475
- }
476
- };
477
- if (update.name) {
478
- add('nickname', update.name);
479
- }
480
- if (update.data) {
481
- for (const e in update.data) {
482
- add(e, update.data[e]);
483
- }
484
- }
485
- if (!atts.length) {
486
- return false;
487
- }
488
- yield promiseFromErrorResultCallback(cb => cUser.updateAttributes(atts, cb));
489
- return true;
490
- });
491
- }
492
- resetPasswordAsync(identity) {
493
- return __awaiter(this, void 0, void 0, function* () {
494
- try {
495
- const cognitoUser = new CognitoUser({
496
- Username: identity,
497
- Pool: this.userPool,
498
- });
499
- const { codeSentTo } = yield promiseFromErrorResultCallback(cb => cognitoUser.forgotPassword({
500
- onSuccess: () => { },
501
- onFailure: err => cb(err, undefined),
502
- inputVerificationCode: code => {
503
- var _a;
504
- cb(null, {
505
- codeSentTo: (_a = code === null || code === void 0 ? void 0 : code.CodeDeliveryDetails) === null || _a === void 0 ? void 0 : _a.Destination
506
- });
507
- }
508
- }));
509
- return {
510
- codeSent: true,
511
- codeSentTo
512
- };
429
+ async updateAsync(user, update) {
430
+ const cUser = user.providerData.providerData?.[userKey];
431
+ if (!cUser) {
432
+ return false;
433
+ }
434
+ const atts = [];
435
+ const add = (name, value) => {
436
+ if (!atts.some(a => a.Name === name)) {
437
+ atts.push({ Name: name, Value: value });
513
438
  }
514
- catch (ex) {
515
- return {
516
- error: ex,
517
- codeSent: false
518
- };
439
+ };
440
+ if (update.name) {
441
+ add('nickname', update.name);
442
+ }
443
+ if (update.data) {
444
+ for (const e in update.data) {
445
+ add(e, update.data[e]);
519
446
  }
520
- });
447
+ }
448
+ if (!atts.length) {
449
+ return false;
450
+ }
451
+ await promiseFromErrorResultCallback(cb => cUser.updateAttributes(atts, cb));
452
+ return true;
521
453
  }
522
- setNewPasswordAsync(identity, code, newPassword) {
523
- return __awaiter(this, void 0, void 0, function* () {
454
+ async resetPasswordAsync(identity) {
455
+ try {
524
456
  const cognitoUser = new CognitoUser({
525
457
  Username: identity,
526
458
  Pool: this.userPool,
527
459
  });
528
- return yield promiseFromErrorResultCallback(cb => cognitoUser.confirmPassword(code, newPassword, {
529
- onSuccess: () => cb(null, true),
460
+ const { codeSentTo } = await promiseFromErrorResultCallback(cb => cognitoUser.forgotPassword({
461
+ onSuccess: () => { },
530
462
  onFailure: err => cb(err, undefined),
463
+ inputVerificationCode: code => {
464
+ cb(null, {
465
+ codeSentTo: code?.CodeDeliveryDetails?.Destination
466
+ });
467
+ }
531
468
  }));
532
- });
469
+ return {
470
+ codeSent: true,
471
+ codeSentTo
472
+ };
473
+ }
474
+ catch (ex) {
475
+ return {
476
+ error: ex,
477
+ codeSent: false
478
+ };
479
+ }
533
480
  }
534
- refreshTokenAsync(user) {
535
- return __awaiter(this, void 0, void 0, function* () {
536
- var _a;
537
- const cUser = (_a = user.providerData.providerData) === null || _a === void 0 ? void 0 : _a[userKey];
538
- if (!cUser) {
539
- return false;
540
- }
541
- const session = yield promiseFromErrorResultCallback(cb => cUser.getSession(cb));
542
- if (!session) {
543
- return false;
544
- }
545
- yield promiseFromErrorResultCallback(cb => cUser.refreshSession(session.getRefreshToken(), cb));
546
- return true;
481
+ async setNewPasswordAsync(identity, code, newPassword) {
482
+ const cognitoUser = new CognitoUser({
483
+ Username: identity,
484
+ Pool: this.userPool,
547
485
  });
486
+ return await promiseFromErrorResultCallback(cb => cognitoUser.confirmPassword(code, newPassword, {
487
+ onSuccess: () => cb(null, true),
488
+ onFailure: err => cb(err, undefined),
489
+ }));
490
+ }
491
+ async refreshTokenAsync(user) {
492
+ const cUser = user.providerData.providerData?.[userKey];
493
+ if (!cUser) {
494
+ return false;
495
+ }
496
+ const session = await promiseFromErrorResultCallback(cb => cUser.getSession(cb));
497
+ if (!session) {
498
+ return false;
499
+ }
500
+ await promiseFromErrorResultCallback(cb => cUser.refreshSession(session.getRefreshToken(), cb));
501
+ return true;
548
502
  }
549
503
  }
550
504
  //# sourceMappingURL=CognitoAuthProvider.js.map