@vardario/cognito-client 0.1.2 → 0.1.4

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,623 +0,0 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __importDefault = (this && this.__importDefault) || function (mod) {
50
- return (mod && mod.__esModule) ? mod : { "default": mod };
51
- };
52
- Object.defineProperty(exports, "__esModule", { value: true });
53
- exports.CognitoClient = exports.CognitoIdentityProvider = exports.CognitoServiceTarget = void 0;
54
- var addSeconds_1 = __importDefault(require("date-fns/addSeconds"));
55
- var hash_js_1 = require("hash.js");
56
- var jsbn_1 = require("jsbn");
57
- var randombytes_1 = __importDefault(require("randombytes"));
58
- var error_1 = require("./error");
59
- var utils_1 = require("./utils");
60
- /**
61
- * List of used and supported Cognito API calls.
62
- * @see https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_Operations.html for more details
63
- */
64
- var CognitoServiceTarget;
65
- (function (CognitoServiceTarget) {
66
- CognitoServiceTarget["InitiateAuth"] = "InitiateAuth";
67
- CognitoServiceTarget["RespondToAuthChallenge"] = "RespondToAuthChallenge";
68
- CognitoServiceTarget["SignUp"] = "SignUp";
69
- CognitoServiceTarget["ConfirmSignUp"] = "ConfirmSignUp";
70
- CognitoServiceTarget["ChangePassword"] = "ChangePassword";
71
- CognitoServiceTarget["RevokeToken"] = "RevokeToken";
72
- CognitoServiceTarget["ForgotPassword"] = "ForgotPassword";
73
- CognitoServiceTarget["ConfirmForgotPassword"] = "ConfirmForgotPassword";
74
- CognitoServiceTarget["ResendConfirmationCode"] = "ResendConfirmationCode";
75
- CognitoServiceTarget["UpdateUserAttributes"] = "UpdateUserAttributes";
76
- CognitoServiceTarget["VerifyUserAttribute"] = "VerifyUserAttribute";
77
- })(CognitoServiceTarget = exports.CognitoServiceTarget || (exports.CognitoServiceTarget = {}));
78
- /**
79
- * Cognito supported federated identities public providers.
80
- * @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html for more information.
81
- */
82
- var CognitoIdentityProvider;
83
- (function (CognitoIdentityProvider) {
84
- CognitoIdentityProvider["Cognito"] = "COGNITO";
85
- CognitoIdentityProvider["Google"] = "Google";
86
- CognitoIdentityProvider["Facebook"] = "Facebook";
87
- CognitoIdentityProvider["Amazon"] = "LoginWithAmazon";
88
- CognitoIdentityProvider["Apple"] = "SignInWithApple";
89
- })(CognitoIdentityProvider = exports.CognitoIdentityProvider || (exports.CognitoIdentityProvider = {}));
90
- /**
91
- * Lightweight AWS Cogito client without any AWS SDK dependencies.
92
- */
93
- var CognitoClient = /** @class */ (function () {
94
- function CognitoClient(_a) {
95
- var userPoolId = _a.userPoolId, userPoolClientId = _a.userPoolClientId, endpoint = _a.endpoint, sessionStorage = _a.sessionStorage, oAuth = _a.oAuth2;
96
- var _b = userPoolId.split('_'), cognitoPoolRegion = _b[0], cognitoPoolName = _b[1];
97
- this.cognitoEndpoint = (endpoint || "https://cognito-idp.".concat(cognitoPoolRegion, ".amazonaws.com")).replace(/\/$/, '');
98
- this.cognitoPoolName = cognitoPoolName;
99
- this.userPoolClientId = userPoolClientId;
100
- this.sessionStorage = sessionStorage;
101
- this.oAuth = oAuth;
102
- }
103
- CognitoClient.getDecodedTokenFromSession = function (session) {
104
- var idToken = (0, utils_1.decodeJwt)(session.idToken).payload;
105
- var accessToken = (0, utils_1.decodeJwt)(session.accessToken).payload;
106
- return {
107
- idToken: idToken,
108
- accessToken: accessToken,
109
- };
110
- };
111
- CognitoClient.prototype.cognitoRequest = function (body, serviceTarget) {
112
- return __awaiter(this, void 0, void 0, function () {
113
- var respondToAuthChallenge, errorMessage;
114
- return __generator(this, function (_a) {
115
- switch (_a.label) {
116
- case 0: return [4 /*yield*/, fetch(this.cognitoEndpoint, {
117
- headers: {
118
- 'x-amz-target': "AWSCognitoIdentityProviderService.".concat(serviceTarget),
119
- 'content-type': 'application/x-amz-json-1.1',
120
- },
121
- method: 'POST',
122
- body: JSON.stringify(body),
123
- })];
124
- case 1:
125
- respondToAuthChallenge = _a.sent();
126
- if (!(respondToAuthChallenge.status < 200 || respondToAuthChallenge.status > 299)) return [3 /*break*/, 3];
127
- return [4 /*yield*/, respondToAuthChallenge.json()];
128
- case 2:
129
- errorMessage = (_a.sent());
130
- throw (0, error_1.getAuthError)(errorMessage);
131
- case 3: return [2 /*return*/, respondToAuthChallenge.json()];
132
- }
133
- });
134
- });
135
- };
136
- CognitoClient.authResultToSession = function (authenticationResult) {
137
- return {
138
- accessToken: authenticationResult.AccessToken,
139
- idToken: authenticationResult.IdToken,
140
- expiresIn: (0, addSeconds_1.default)(new Date(), authenticationResult.ExpiresIn).getTime(),
141
- refreshToken: authenticationResult.RefreshToken,
142
- };
143
- };
144
- /**
145
- *
146
- * Performs user authentication with username and password through ALLOW_USER_SRP_AUTH .
147
- * @see https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html for more details
148
- *
149
- * @param username Username
150
- * @param password Password
151
- * @throws {AuthException}
152
- */
153
- CognitoClient.prototype.authenticateUserSrp = function (username, password) {
154
- return __awaiter(this, void 0, void 0, function () {
155
- var smallA, A, initiateAuthPayload, challenge, B, salt, U, hkdf, _a, signature, timeStamp, respondToAuthChallengePayload, AuthenticationResult, session;
156
- return __generator(this, function (_b) {
157
- switch (_b.label) {
158
- case 0:
159
- smallA = (0, utils_1.generateSmallA)();
160
- A = (0, utils_1.generateA)(smallA);
161
- initiateAuthPayload = {
162
- AuthFlow: 'USER_SRP_AUTH',
163
- ClientId: this.userPoolClientId,
164
- AuthParameters: {
165
- USERNAME: username,
166
- SRP_A: A.toString(16),
167
- },
168
- ClientMetadata: {},
169
- };
170
- return [4 /*yield*/, this.cognitoRequest(initiateAuthPayload, CognitoServiceTarget.InitiateAuth)];
171
- case 1:
172
- challenge = (_b.sent());
173
- B = new jsbn_1.BigInteger(challenge.ChallengeParameters.SRP_B, 16);
174
- salt = new jsbn_1.BigInteger(challenge.ChallengeParameters.SALT, 16);
175
- U = (0, utils_1.calculateU)(A, B);
176
- hkdf = (0, utils_1.getPasswordAuthenticationKey)(this.cognitoPoolName, challenge.ChallengeParameters.USER_ID_FOR_SRP, password, B, U, smallA, salt);
177
- _a = (0, utils_1.calculateSignature)(this.cognitoPoolName, challenge.ChallengeParameters.USER_ID_FOR_SRP, challenge.ChallengeParameters.SECRET_BLOCK, hkdf), signature = _a.signature, timeStamp = _a.timeStamp;
178
- respondToAuthChallengePayload = {
179
- ChallengeName: 'PASSWORD_VERIFIER',
180
- ClientId: this.userPoolClientId,
181
- ChallengeResponses: {
182
- PASSWORD_CLAIM_SECRET_BLOCK: challenge.ChallengeParameters.SECRET_BLOCK,
183
- PASSWORD_CLAIM_SIGNATURE: signature,
184
- USERNAME: challenge.ChallengeParameters.USER_ID_FOR_SRP,
185
- TIMESTAMP: timeStamp,
186
- },
187
- ClientMetadata: {},
188
- };
189
- return [4 /*yield*/, this.cognitoRequest(respondToAuthChallengePayload, CognitoServiceTarget.RespondToAuthChallenge)];
190
- case 2:
191
- AuthenticationResult = (_b.sent()).AuthenticationResult;
192
- session = CognitoClient.authResultToSession(AuthenticationResult);
193
- this.sessionStorage.setSession(session);
194
- return [2 /*return*/, session];
195
- }
196
- });
197
- });
198
- };
199
- /**
200
- *
201
- * Performs user authentication with username and password through USER_PASSWORD_AUTH .
202
- * @see https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html for more details
203
- *
204
- * @param username Username
205
- * @param password Password
206
- * @throws {AuthException}
207
- */
208
- CognitoClient.prototype.authenticateUser = function (username, password) {
209
- return __awaiter(this, void 0, void 0, function () {
210
- var initiateAuthPayload, AuthenticationResult, session;
211
- return __generator(this, function (_a) {
212
- switch (_a.label) {
213
- case 0:
214
- initiateAuthPayload = {
215
- AuthFlow: 'USER_PASSWORD_AUTH',
216
- ClientId: this.userPoolClientId,
217
- AuthParameters: {
218
- USERNAME: username,
219
- PASSWORD: password,
220
- },
221
- ClientMetadata: {},
222
- };
223
- return [4 /*yield*/, this.cognitoRequest(initiateAuthPayload, CognitoServiceTarget.InitiateAuth)];
224
- case 1:
225
- AuthenticationResult = (_a.sent()).AuthenticationResult;
226
- session = CognitoClient.authResultToSession(AuthenticationResult);
227
- this.sessionStorage.setSession(session);
228
- return [2 /*return*/, session];
229
- }
230
- });
231
- });
232
- };
233
- CognitoClient.prototype.refreshSession = function (session) {
234
- return __awaiter(this, void 0, void 0, function () {
235
- var refreshTokenPayload, AuthenticationResult, newSession;
236
- return __generator(this, function (_a) {
237
- switch (_a.label) {
238
- case 0:
239
- refreshTokenPayload = {
240
- AuthFlow: 'REFRESH_TOKEN_AUTH',
241
- ClientId: this.userPoolClientId,
242
- AuthParameters: {
243
- REFRESH_TOKEN: session.refreshToken,
244
- },
245
- ClientMetadata: {},
246
- };
247
- return [4 /*yield*/, this.cognitoRequest(refreshTokenPayload, CognitoServiceTarget.InitiateAuth)];
248
- case 1:
249
- AuthenticationResult = (_a.sent()).AuthenticationResult;
250
- newSession = CognitoClient.authResultToSession(__assign(__assign({}, AuthenticationResult), { RefreshToken: session.refreshToken }));
251
- this.sessionStorage.setSession(newSession);
252
- return [2 /*return*/, newSession];
253
- }
254
- });
255
- });
256
- };
257
- /**
258
- * Returns the current auth session.
259
- * The auth session is only defined when we previously had a successful user authentication.
260
- * This function will also take care to refresh the session with the refresh token in case
261
- * the current session has expired.
262
- *
263
- * @throws {AuthException}
264
- */
265
- CognitoClient.prototype.getSession = function () {
266
- return __awaiter(this, void 0, void 0, function () {
267
- var session;
268
- return __generator(this, function (_a) {
269
- session = this.sessionStorage.getSession();
270
- if (session) {
271
- if (new Date().getTime() >= session.expiresIn) {
272
- return [2 /*return*/, this.refreshSession(session)];
273
- }
274
- }
275
- return [2 /*return*/, session];
276
- });
277
- });
278
- };
279
- /**
280
- *
281
- * @param username Username
282
- * @param password Password
283
- *
284
- * @throws {AuthException}
285
- */
286
- CognitoClient.prototype.signUp = function (username, password, userAttributes) {
287
- return __awaiter(this, void 0, void 0, function () {
288
- var signUpPayload, data;
289
- return __generator(this, function (_a) {
290
- switch (_a.label) {
291
- case 0:
292
- signUpPayload = {
293
- ClientId: this.userPoolClientId,
294
- Username: username,
295
- Password: password,
296
- UserAttributes: userAttributes,
297
- };
298
- return [4 /*yield*/, this.cognitoRequest(signUpPayload, CognitoServiceTarget.SignUp)];
299
- case 1:
300
- data = _a.sent();
301
- return [2 /*return*/, {
302
- id: data.UserSub,
303
- confirmed: data.UserConfirmed,
304
- }];
305
- }
306
- });
307
- });
308
- };
309
- /**
310
- * Confirms the user registration via verification code.
311
- *
312
- * @param username Username
313
- * @param code Confirmation code the user gets through the registration E-Mail
314
- *
315
- * @throws {AuthException}
316
- */
317
- CognitoClient.prototype.confirmSignUp = function (username, code) {
318
- return __awaiter(this, void 0, void 0, function () {
319
- var confirmSignUpPayload, result;
320
- return __generator(this, function (_a) {
321
- switch (_a.label) {
322
- case 0:
323
- confirmSignUpPayload = {
324
- ClientId: this.userPoolClientId,
325
- ConfirmationCode: code,
326
- Username: username,
327
- };
328
- return [4 /*yield*/, this.cognitoRequest(confirmSignUpPayload, CognitoServiceTarget.ConfirmSignUp)];
329
- case 1:
330
- result = _a.sent();
331
- return [2 /*return*/];
332
- }
333
- });
334
- });
335
- };
336
- /**
337
- *
338
- * @param currentPassword Current user password.
339
- * @param newPassword New user password.
340
- *
341
- * @throws {AuthException}
342
- */
343
- CognitoClient.prototype.changePassword = function (currentPassword, newPassword) {
344
- return __awaiter(this, void 0, void 0, function () {
345
- var session, changePasswordPayload, result;
346
- return __generator(this, function (_a) {
347
- switch (_a.label) {
348
- case 0: return [4 /*yield*/, this.getSession()];
349
- case 1:
350
- session = _a.sent();
351
- if (session === undefined) {
352
- throw new error_1.AuthException('User must be authenticated', error_1.AuthError.UserNotAuthenticated);
353
- }
354
- changePasswordPayload = {
355
- PreviousPassword: currentPassword,
356
- ProposedPassword: newPassword,
357
- AccessToken: session.accessToken,
358
- };
359
- return [4 /*yield*/, this.cognitoRequest(changePasswordPayload, CognitoServiceTarget.ChangePassword)];
360
- case 2:
361
- result = _a.sent();
362
- return [2 /*return*/];
363
- }
364
- });
365
- });
366
- };
367
- CognitoClient.prototype.updateUserAttributes = function (userAttributes) {
368
- return __awaiter(this, void 0, void 0, function () {
369
- var session, updateUserAttributesPayload, result;
370
- return __generator(this, function (_a) {
371
- switch (_a.label) {
372
- case 0: return [4 /*yield*/, this.getSession()];
373
- case 1:
374
- session = _a.sent();
375
- if (session === undefined) {
376
- throw new error_1.AuthException('User must be authenticated', error_1.AuthError.UserNotAuthenticated);
377
- }
378
- updateUserAttributesPayload = {
379
- UserAttributes: userAttributes,
380
- AccessToken: session.accessToken,
381
- };
382
- return [4 /*yield*/, this.cognitoRequest(updateUserAttributesPayload, CognitoServiceTarget.UpdateUserAttributes)];
383
- case 2:
384
- result = _a.sent();
385
- return [2 /*return*/];
386
- }
387
- });
388
- });
389
- };
390
- CognitoClient.prototype.verifyUserAttribute = function (attributeName, code) {
391
- return __awaiter(this, void 0, void 0, function () {
392
- var session, verifyUserAttributePayload, result;
393
- return __generator(this, function (_a) {
394
- switch (_a.label) {
395
- case 0: return [4 /*yield*/, this.getSession()];
396
- case 1:
397
- session = _a.sent();
398
- if (session === undefined) {
399
- throw new error_1.AuthException('User must be authenticated', error_1.AuthError.UserNotAuthenticated);
400
- }
401
- verifyUserAttributePayload = {
402
- AttributeName: attributeName,
403
- Code: code,
404
- AccessToken: session.accessToken,
405
- };
406
- return [4 /*yield*/, this.cognitoRequest(verifyUserAttributePayload, CognitoServiceTarget.VerifyUserAttribute)];
407
- case 2:
408
- result = _a.sent();
409
- return [2 /*return*/];
410
- }
411
- });
412
- });
413
- };
414
- /**
415
- * Sign out the user and remove the current user session.
416
- *
417
- * @throws {AuthException}
418
- */
419
- CognitoClient.prototype.signOut = function () {
420
- return __awaiter(this, void 0, void 0, function () {
421
- var session, revokeTokenPayload;
422
- return __generator(this, function (_a) {
423
- switch (_a.label) {
424
- case 0: return [4 /*yield*/, this.getSession()];
425
- case 1:
426
- session = _a.sent();
427
- if (session === undefined) {
428
- throw new error_1.AuthException('User must be authenticated', error_1.AuthError.UserNotAuthenticated);
429
- }
430
- revokeTokenPayload = {
431
- Token: session.refreshToken,
432
- ClientId: this.userPoolClientId,
433
- };
434
- this.sessionStorage.setSession(undefined);
435
- return [4 /*yield*/, this.cognitoRequest(revokeTokenPayload, CognitoServiceTarget.RevokeToken)];
436
- case 2:
437
- _a.sent();
438
- return [2 /*return*/];
439
- }
440
- });
441
- });
442
- };
443
- /**
444
- * Request forgot password.
445
- * @param username Username
446
- *
447
- * @throws {AuthException}
448
- */
449
- CognitoClient.prototype.forgotPassword = function (username) {
450
- return __awaiter(this, void 0, void 0, function () {
451
- var forgotPasswordPayload;
452
- return __generator(this, function (_a) {
453
- switch (_a.label) {
454
- case 0:
455
- forgotPasswordPayload = {
456
- ClientId: this.userPoolClientId,
457
- Username: username,
458
- };
459
- return [4 /*yield*/, this.cognitoRequest(forgotPasswordPayload, CognitoServiceTarget.ForgotPassword)];
460
- case 1:
461
- _a.sent();
462
- return [2 /*return*/];
463
- }
464
- });
465
- });
466
- };
467
- /**
468
- * Confirms the new password via the given code send via cognito triggered by @see forgotPassword .
469
- *
470
- * @param username Username
471
- * @param newPassword New password
472
- * @param confirmationCode Confirmation code which the user got through E-mail
473
- *
474
- * @throws {AuthException}
475
- */
476
- CognitoClient.prototype.confirmForgotPassword = function (username, newPassword, confirmationCode) {
477
- return __awaiter(this, void 0, void 0, function () {
478
- var confirmForgotPasswordPayload;
479
- return __generator(this, function (_a) {
480
- switch (_a.label) {
481
- case 0:
482
- confirmForgotPasswordPayload = {
483
- ClientId: this.userPoolClientId,
484
- Username: username,
485
- ConfirmationCode: confirmationCode,
486
- Password: newPassword,
487
- };
488
- return [4 /*yield*/, this.cognitoRequest(confirmForgotPasswordPayload, CognitoServiceTarget.ConfirmForgotPassword)];
489
- case 1:
490
- _a.sent();
491
- return [2 /*return*/];
492
- }
493
- });
494
- });
495
- };
496
- /**
497
- * Triggers cognito to resend the confirmation code
498
- * @param username Username
499
- */
500
- CognitoClient.prototype.resendConfirmationCode = function (username) {
501
- return __awaiter(this, void 0, void 0, function () {
502
- var resendConfirmationCodePayLoad;
503
- return __generator(this, function (_a) {
504
- switch (_a.label) {
505
- case 0:
506
- resendConfirmationCodePayLoad = {
507
- ClientId: this.userPoolClientId,
508
- Username: username,
509
- };
510
- return [4 /*yield*/, this.cognitoRequest(resendConfirmationCodePayLoad, CognitoServiceTarget.ResendConfirmationCode)];
511
- case 1:
512
- _a.sent();
513
- return [2 /*return*/];
514
- }
515
- });
516
- });
517
- };
518
- /**
519
- * Returns a link to Cognito`s Hosted UI for OAuth2 authentication.
520
- * This method works in conjunction with @see handleCodeFlow .
521
- *
522
- * @param identityProvider When provided, this will generate a link which
523
- * tells Cognito`s Hosted UI to redirect to the given federated identity provider.
524
- *
525
- * @throws {Error}
526
- */
527
- CognitoClient.prototype.generateOAuthSignInUrl = function (identityProvider) {
528
- if (this.oAuth === undefined) {
529
- throw Error('You have to define oAuth options to use generateFederatedSignUrl');
530
- }
531
- var state = (0, randombytes_1.default)(32).toString('hex');
532
- var pkce = (0, randombytes_1.default)(128).toString('hex');
533
- var code_challenge = Buffer.from((0, hash_js_1.sha256)().update(pkce).digest())
534
- .toString('base64')
535
- .replace(/\+/g, '-')
536
- .replace(/\//g, '_')
537
- .replace(/=+$/, '');
538
- var queryParams = new URLSearchParams();
539
- queryParams.append('redirect_uri', this.oAuth.redirectUrl);
540
- queryParams.append('response_type', this.oAuth.responseType);
541
- queryParams.append('client_id', this.userPoolClientId);
542
- identityProvider && queryParams.append('identity_provider', identityProvider);
543
- queryParams.append('scope', this.oAuth.scopes.join(' '));
544
- queryParams.append('state', state);
545
- queryParams.append('code_challenge', code_challenge);
546
- queryParams.append('code_challenge_method', 'S256');
547
- this.sessionStorage.setOauthVerificationParams({
548
- state: state,
549
- pkce: pkce,
550
- });
551
- return "".concat(this.oAuth.cognitoDomain, "/oauth2/authorize?").concat(queryParams.toString());
552
- };
553
- /**
554
- *
555
- * Handles Cognito`s OAuth2 code flow after redirection from Cognito`s Hosted UI.
556
- * The method call assumes that @see generateOAuthSignInUrl was used to
557
- * generated the link to the Hosted UI.
558
- *
559
- * @param returnUrl The full return URL from redirection after a successful OAuth2
560
- * authentication.
561
- *
562
- * @throws {Error}
563
- */
564
- CognitoClient.prototype.handleCodeFlow = function (returnUrl) {
565
- return __awaiter(this, void 0, void 0, function () {
566
- var url, code, state, oAuthVerificationParams, urlParams, tokenEndpoint, response, _a, access_token, refresh_token, id_token, expires_in, token_type, error, session;
567
- return __generator(this, function (_b) {
568
- switch (_b.label) {
569
- case 0:
570
- if (this.oAuth === undefined) {
571
- throw Error('You have to define oAuth options to use handleCodeFlow');
572
- }
573
- url = new URL(returnUrl);
574
- code = url.searchParams.get('code');
575
- state = url.searchParams.get('state');
576
- if (code === null || state === null) {
577
- throw Error('code or state parameter is missing from return url.');
578
- }
579
- oAuthVerificationParams = this.sessionStorage.getOauthVerificationParams();
580
- if (oAuthVerificationParams === undefined) {
581
- throw new Error('OAuth verification parameters are missing, did you forgot to call generateOAuthSignInUrl ?');
582
- }
583
- if (oAuthVerificationParams.state !== state) {
584
- throw new Error('state parameter does not match with previous value generated by previous call of generateOAuthSignInUrl .');
585
- }
586
- urlParams = new URLSearchParams();
587
- urlParams.append('grant_type', 'authorization_code');
588
- urlParams.append('code', code);
589
- urlParams.append('client_id', this.userPoolClientId);
590
- urlParams.append('redirect_uri', this.oAuth.redirectUrl);
591
- urlParams.append('code_verifier', oAuthVerificationParams.pkce);
592
- tokenEndpoint = "".concat(this.oAuth.cognitoDomain, "/oauth2/token");
593
- return [4 /*yield*/, fetch(tokenEndpoint, {
594
- method: 'POST',
595
- headers: {
596
- 'Content-Type': 'application/x-www-form-urlencoded',
597
- },
598
- body: urlParams.toString(),
599
- })];
600
- case 1:
601
- response = _b.sent();
602
- return [4 /*yield*/, response.json()];
603
- case 2:
604
- _a = _b.sent(), access_token = _a.access_token, refresh_token = _a.refresh_token, id_token = _a.id_token, expires_in = _a.expires_in, token_type = _a.token_type, error = _a.error;
605
- if (error) {
606
- throw new Error(error);
607
- }
608
- session = CognitoClient.authResultToSession({
609
- AccessToken: access_token,
610
- RefreshToken: refresh_token,
611
- IdToken: id_token,
612
- ExpiresIn: expires_in,
613
- TokenType: token_type,
614
- });
615
- this.sessionStorage.setSession(session);
616
- return [2 /*return*/, session];
617
- }
618
- });
619
- });
620
- };
621
- return CognitoClient;
622
- }());
623
- exports.CognitoClient = CognitoClient;
@@ -1 +0,0 @@
1
- import 'isomorphic-fetch';