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 | Object.defineProperty(exports, "__esModule", { value: true });
|
50 | exports.Credentials = exports.CredentialsClass = void 0;
|
51 |
|
52 |
|
53 | var Logger_1 = require("./Logger");
|
54 | var StorageHelper_1 = require("./StorageHelper");
|
55 | var JS_1 = require("./JS");
|
56 | var OAuthHelper_1 = require("./OAuthHelper");
|
57 | var Util_1 = require("./Util");
|
58 | var Amplify_1 = require("./Amplify");
|
59 | var CognitoIdentity_1 = require("./AwsClients/CognitoIdentity");
|
60 | var parseAWSExports_1 = require("./parseAWSExports");
|
61 | var Hub_1 = require("./Hub");
|
62 | var logger = new Logger_1.ConsoleLogger('Credentials');
|
63 | var CREDENTIALS_TTL = 50 * 60 * 1000;
|
64 | var COGNITO_IDENTITY_KEY_PREFIX = 'CognitoIdentityId-';
|
65 | var AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function'
|
66 | ? Symbol.for('amplify_default')
|
67 | : '@@amplify_default');
|
68 | var dispatchCredentialsEvent = function (event, data, message) {
|
69 | Hub_1.Hub.dispatch('core', { event: event, data: data, message: message }, 'Credentials', AMPLIFY_SYMBOL);
|
70 | };
|
71 | var CredentialsClass = (function () {
|
72 | function CredentialsClass(config) {
|
73 | this._gettingCredPromise = null;
|
74 | this._refreshHandlers = {};
|
75 |
|
76 | this.Auth = undefined;
|
77 | this.configure(config);
|
78 | this._refreshHandlers['google'] = OAuthHelper_1.GoogleOAuth.refreshGoogleToken;
|
79 | this._refreshHandlers['facebook'] = OAuthHelper_1.FacebookOAuth.refreshFacebookToken;
|
80 | }
|
81 | CredentialsClass.prototype.getModuleName = function () {
|
82 | return 'Credentials';
|
83 | };
|
84 | CredentialsClass.prototype.getCredSource = function () {
|
85 | return this._credentials_source;
|
86 | };
|
87 | CredentialsClass.prototype.configure = function (config) {
|
88 | if (!config)
|
89 | return this._config || {};
|
90 | this._config = Object.assign({}, this._config, config);
|
91 | var refreshHandlers = this._config.refreshHandlers;
|
92 |
|
93 |
|
94 | if (refreshHandlers) {
|
95 | this._refreshHandlers = __assign(__assign({}, this._refreshHandlers), refreshHandlers);
|
96 | }
|
97 | this._storage = this._config.storage;
|
98 | if (!this._storage) {
|
99 | this._storage = new StorageHelper_1.StorageHelper().getStorage();
|
100 | }
|
101 | this._storageSync = Promise.resolve();
|
102 | if (typeof this._storage['sync'] === 'function') {
|
103 | this._storageSync = this._storage['sync']();
|
104 | }
|
105 | dispatchCredentialsEvent('credentials_configured', null, "Credentials has been configured successfully");
|
106 | return this._config;
|
107 | };
|
108 | CredentialsClass.prototype.get = function () {
|
109 | logger.debug('getting credentials');
|
110 | return this._pickupCredentials();
|
111 | };
|
112 |
|
113 | CredentialsClass.prototype._getCognitoIdentityIdStorageKey = function (identityPoolId) {
|
114 | return "".concat(COGNITO_IDENTITY_KEY_PREFIX).concat(identityPoolId);
|
115 | };
|
116 | CredentialsClass.prototype._pickupCredentials = function () {
|
117 | logger.debug('picking up credentials');
|
118 | if (!this._gettingCredPromise || !this._gettingCredPromise.isPending()) {
|
119 | logger.debug('getting new cred promise');
|
120 | this._gettingCredPromise = (0, JS_1.makeQuerablePromise)(this._keepAlive());
|
121 | }
|
122 | else {
|
123 | logger.debug('getting old cred promise');
|
124 | }
|
125 | return this._gettingCredPromise;
|
126 | };
|
127 | CredentialsClass.prototype._keepAlive = function () {
|
128 | return __awaiter(this, void 0, void 0, function () {
|
129 | var cred, _a, Auth, user_1, session, refreshToken_1, refreshRequest, err_1;
|
130 | return __generator(this, function (_b) {
|
131 | switch (_b.label) {
|
132 | case 0:
|
133 | logger.debug('checking if credentials exists and not expired');
|
134 | cred = this._credentials;
|
135 | if (cred && !this._isExpired(cred) && !this._isPastTTL()) {
|
136 | logger.debug('credentials not changed and not expired, directly return');
|
137 | return [2 , Promise.resolve(cred)];
|
138 | }
|
139 | logger.debug('need to get a new credential or refresh the existing one');
|
140 | _a = this.Auth, Auth = _a === void 0 ? Amplify_1.Amplify.Auth : _a;
|
141 | if (!Auth || typeof Auth.currentUserCredentials !== 'function') {
|
142 |
|
143 | return [2 , this._setCredentialsForGuest()];
|
144 | }
|
145 | if (!(!this._isExpired(cred) && this._isPastTTL())) return [3 , 6];
|
146 | logger.debug('ttl has passed but token is not yet expired');
|
147 | _b.label = 1;
|
148 | case 1:
|
149 | _b.trys.push([1, 5, , 6]);
|
150 | return [4 , Auth.currentUserPoolUser()];
|
151 | case 2:
|
152 | user_1 = _b.sent();
|
153 | return [4 , Auth.currentSession()];
|
154 | case 3:
|
155 | session = _b.sent();
|
156 | refreshToken_1 = session.refreshToken;
|
157 | refreshRequest = new Promise(function (res, rej) {
|
158 | user_1.refreshSession(refreshToken_1, function (err, data) {
|
159 | return err ? rej(err) : res(data);
|
160 | });
|
161 | });
|
162 | return [4 , refreshRequest];
|
163 | case 4:
|
164 | _b.sent();
|
165 | return [3 , 6];
|
166 | case 5:
|
167 | err_1 = _b.sent();
|
168 |
|
169 | logger.debug('Error attempting to refreshing the session', err_1);
|
170 | return [3 , 6];
|
171 | case 6: return [2 , Auth.currentUserCredentials()];
|
172 | }
|
173 | });
|
174 | });
|
175 | };
|
176 | CredentialsClass.prototype.refreshFederatedToken = function (federatedInfo) {
|
177 | logger.debug('Getting federated credentials');
|
178 | var provider = federatedInfo.provider, user = federatedInfo.user, token = federatedInfo.token, identity_id = federatedInfo.identity_id;
|
179 | var expires_at = federatedInfo.expires_at;
|
180 |
|
181 | expires_at =
|
182 | new Date(expires_at).getFullYear() === 1970
|
183 | ? expires_at * 1000
|
184 | : expires_at;
|
185 | var that = this;
|
186 | logger.debug('checking if federated jwt token expired');
|
187 | if (expires_at > new Date().getTime()) {
|
188 |
|
189 | logger.debug('token not expired');
|
190 | return this._setCredentialsFromFederation({
|
191 | provider: provider,
|
192 | token: token,
|
193 | user: user,
|
194 | identity_id: identity_id,
|
195 | expires_at: expires_at,
|
196 | });
|
197 | }
|
198 | else {
|
199 |
|
200 | if (that._refreshHandlers[provider] &&
|
201 | typeof that._refreshHandlers[provider] === 'function') {
|
202 | logger.debug('getting refreshed jwt token from federation provider');
|
203 | return this._providerRefreshWithRetry({
|
204 | refreshHandler: that._refreshHandlers[provider],
|
205 | provider: provider,
|
206 | user: user,
|
207 | });
|
208 | }
|
209 | else {
|
210 | logger.debug('no refresh handler for provider:', provider);
|
211 | this.clear();
|
212 | return Promise.reject('no refresh handler for provider');
|
213 | }
|
214 | }
|
215 | };
|
216 | CredentialsClass.prototype._providerRefreshWithRetry = function (_a) {
|
217 | var _this = this;
|
218 | var refreshHandler = _a.refreshHandler, provider = _a.provider, user = _a.user;
|
219 | var MAX_DELAY_MS = 10 * 1000;
|
220 |
|
221 |
|
222 | return (0, Util_1.jitteredExponentialRetry)(refreshHandler, [], MAX_DELAY_MS)
|
223 | .then(function (data) {
|
224 | logger.debug('refresh federated token sucessfully', data);
|
225 | return _this._setCredentialsFromFederation({
|
226 | provider: provider,
|
227 | token: data.token,
|
228 | user: user,
|
229 | identity_id: data.identity_id,
|
230 | expires_at: data.expires_at,
|
231 | });
|
232 | })
|
233 | .catch(function (e) {
|
234 | var isNetworkError = typeof e === 'string' &&
|
235 | e.toLowerCase().lastIndexOf('network error', e.length) === 0;
|
236 | if (!isNetworkError) {
|
237 | _this.clear();
|
238 | }
|
239 | logger.debug('refresh federated token failed', e);
|
240 | return Promise.reject('refreshing federation token failed: ' + e);
|
241 | });
|
242 | };
|
243 | CredentialsClass.prototype._isExpired = function (credentials) {
|
244 | if (!credentials) {
|
245 | logger.debug('no credentials for expiration check');
|
246 | return true;
|
247 | }
|
248 | logger.debug('are these credentials expired?', credentials);
|
249 | var ts = Date.now();
|
250 | |
251 |
|
252 |
|
253 | var expiration = credentials.expiration;
|
254 | return expiration.getTime() <= ts;
|
255 | };
|
256 | CredentialsClass.prototype._isPastTTL = function () {
|
257 | return this._nextCredentialsRefresh <= Date.now();
|
258 | };
|
259 | CredentialsClass.prototype._setCredentialsForGuest = function () {
|
260 | var _a;
|
261 | return __awaiter(this, void 0, void 0, function () {
|
262 | var _b, identityPoolId, region, mandatorySignIn, identityPoolRegion, identityId, _c, cognitoConfig, guestCredentialsProvider, credentials;
|
263 | var _this = this;
|
264 | return __generator(this, function (_d) {
|
265 | switch (_d.label) {
|
266 | case 0:
|
267 | logger.debug('setting credentials for guest');
|
268 | if (!((_a = this._config) === null || _a === void 0 ? void 0 : _a.identityPoolId)) {
|
269 |
|
270 |
|
271 | this._config = Object.assign({}, this._config, (0, parseAWSExports_1.parseAWSExports)(this._config || {}).Auth);
|
272 | }
|
273 | _b = this._config, identityPoolId = _b.identityPoolId, region = _b.region, mandatorySignIn = _b.mandatorySignIn, identityPoolRegion = _b.identityPoolRegion;
|
274 | if (mandatorySignIn) {
|
275 | return [2 , Promise.reject('cannot get guest credentials when mandatory signin enabled')];
|
276 | }
|
277 | if (!identityPoolId) {
|
278 | logger.debug('No Cognito Identity pool provided for unauthenticated access');
|
279 | return [2 , Promise.reject('No Cognito Identity pool provided for unauthenticated access')];
|
280 | }
|
281 | if (!identityPoolRegion && !region) {
|
282 | logger.debug('region is not configured for getting the credentials');
|
283 | return [2 , Promise.reject('region is not configured for getting the credentials')];
|
284 | }
|
285 | _c = this;
|
286 | return [4 , this._getGuestIdentityId()];
|
287 | case 1:
|
288 | identityId = (_c._identityId = _d.sent());
|
289 | cognitoConfig = { region: identityPoolRegion !== null && identityPoolRegion !== void 0 ? identityPoolRegion : region };
|
290 | guestCredentialsProvider = function () { return __awaiter(_this, void 0, void 0, function () {
|
291 | var IdentityId, Credentials;
|
292 | return __generator(this, function (_a) {
|
293 | switch (_a.label) {
|
294 | case 0:
|
295 | if (!!identityId) return [3 , 2];
|
296 | return [4 , (0, CognitoIdentity_1.getId)(cognitoConfig, {
|
297 | IdentityPoolId: identityPoolId,
|
298 | })];
|
299 | case 1:
|
300 | IdentityId = (_a.sent()).IdentityId;
|
301 | this._identityId = IdentityId;
|
302 | _a.label = 2;
|
303 | case 2: return [4 , (0, CognitoIdentity_1.getCredentialsForIdentity)(cognitoConfig, {
|
304 | IdentityId: this._identityId,
|
305 | })];
|
306 | case 3:
|
307 | Credentials = (_a.sent()).Credentials;
|
308 | return [2 , {
|
309 | identityId: this._identityId,
|
310 | accessKeyId: Credentials.AccessKeyId,
|
311 | secretAccessKey: Credentials.SecretKey,
|
312 | sessionToken: Credentials.SessionToken,
|
313 | expiration: Credentials.Expiration,
|
314 | }];
|
315 | }
|
316 | });
|
317 | }); };
|
318 | credentials = guestCredentialsProvider().catch(function (err) { return __awaiter(_this, void 0, void 0, function () {
|
319 | return __generator(this, function (_a) {
|
320 | throw err;
|
321 | });
|
322 | }); });
|
323 | return [2 , this._loadCredentials(credentials, 'guest', false, null)
|
324 | .then(function (res) {
|
325 | return res;
|
326 | })
|
327 | .catch(function (e) { return __awaiter(_this, void 0, void 0, function () {
|
328 | var guestCredentialsProvider_1;
|
329 | var _this = this;
|
330 | return __generator(this, function (_a) {
|
331 | switch (_a.label) {
|
332 | case 0:
|
333 | if (!(e.name === 'ResourceNotFoundException' &&
|
334 | e.message === "Identity '".concat(identityId, "' not found."))) return [3 , 2];
|
335 | logger.debug('Failed to load guest credentials');
|
336 | return [4 , this._removeGuestIdentityId()];
|
337 | case 1:
|
338 | _a.sent();
|
339 | guestCredentialsProvider_1 = function () { return __awaiter(_this, void 0, void 0, function () {
|
340 | var IdentityId, Credentials;
|
341 | return __generator(this, function (_a) {
|
342 | switch (_a.label) {
|
343 | case 0: return [4 , (0, CognitoIdentity_1.getId)(cognitoConfig, {
|
344 | IdentityPoolId: identityPoolId,
|
345 | })];
|
346 | case 1:
|
347 | IdentityId = (_a.sent()).IdentityId;
|
348 | this._identityId = IdentityId;
|
349 | return [4 , (0, CognitoIdentity_1.getCredentialsForIdentity)(cognitoConfig, {
|
350 | IdentityId: IdentityId,
|
351 | })];
|
352 | case 2:
|
353 | Credentials = (_a.sent()).Credentials;
|
354 | return [2 , {
|
355 | identityId: IdentityId,
|
356 | accessKeyId: Credentials.AccessKeyId,
|
357 | secretAccessKey: Credentials.SecretKey,
|
358 | sessionToken: Credentials.SessionToken,
|
359 | expiration: Credentials.Expiration,
|
360 | }];
|
361 | }
|
362 | });
|
363 | }); };
|
364 | credentials = guestCredentialsProvider_1().catch(function (err) { return __awaiter(_this, void 0, void 0, function () {
|
365 | return __generator(this, function (_a) {
|
366 | throw err;
|
367 | });
|
368 | }); });
|
369 | return [2 , this._loadCredentials(credentials, 'guest', false, null)];
|
370 | case 2: return [2 , e];
|
371 | }
|
372 | });
|
373 | }); })];
|
374 | }
|
375 | });
|
376 | });
|
377 | };
|
378 | CredentialsClass.prototype._setCredentialsFromFederation = function (params) {
|
379 | var _this = this;
|
380 | var provider = params.provider, token = params.token;
|
381 | var identity_id = params.identity_id;
|
382 | var domains = {
|
383 | google: 'accounts.google.com',
|
384 | facebook: 'graph.facebook.com',
|
385 | amazon: 'www.amazon.com',
|
386 | developer: 'cognito-identity.amazonaws.com',
|
387 | };
|
388 |
|
389 | var domain = domains[provider] || provider;
|
390 | if (!domain) {
|
391 | return Promise.reject('You must specify a federated provider');
|
392 | }
|
393 | var logins = {};
|
394 | logins[domain] = token;
|
395 | var _a = this._config, identityPoolId = _a.identityPoolId, region = _a.region, identityPoolRegion = _a.identityPoolRegion;
|
396 | if (!identityPoolId) {
|
397 | logger.debug('No Cognito Federated Identity pool provided');
|
398 | return Promise.reject('No Cognito Federated Identity pool provided');
|
399 | }
|
400 | if (!identityPoolRegion && !region) {
|
401 | logger.debug('region is not configured for getting the credentials');
|
402 | return Promise.reject('region is not configured for getting the credentials');
|
403 | }
|
404 | var cognitoConfig = { region: identityPoolRegion !== null && identityPoolRegion !== void 0 ? identityPoolRegion : region };
|
405 | var authenticatedCredentialsProvider = function () { return __awaiter(_this, void 0, void 0, function () {
|
406 | var IdentityId, Credentials;
|
407 | return __generator(this, function (_a) {
|
408 | switch (_a.label) {
|
409 | case 0:
|
410 | if (!!identity_id) return [3 , 2];
|
411 | return [4 , (0, CognitoIdentity_1.getId)(cognitoConfig, {
|
412 | IdentityPoolId: identityPoolId,
|
413 | Logins: logins,
|
414 | })];
|
415 | case 1:
|
416 | IdentityId = (_a.sent()).IdentityId;
|
417 | identity_id = IdentityId;
|
418 | _a.label = 2;
|
419 | case 2: return [4 , (0, CognitoIdentity_1.getCredentialsForIdentity)(cognitoConfig, {
|
420 | IdentityId: identity_id,
|
421 | Logins: logins,
|
422 | })];
|
423 | case 3:
|
424 | Credentials = (_a.sent()).Credentials;
|
425 | return [2 , {
|
426 | identityId: identity_id,
|
427 | accessKeyId: Credentials.AccessKeyId,
|
428 | secretAccessKey: Credentials.SecretKey,
|
429 | sessionToken: Credentials.SessionToken,
|
430 | expiration: Credentials.Expiration,
|
431 | }];
|
432 | }
|
433 | });
|
434 | }); };
|
435 | var credentials = authenticatedCredentialsProvider().catch(function (err) { return __awaiter(_this, void 0, void 0, function () {
|
436 | return __generator(this, function (_a) {
|
437 | throw err;
|
438 | });
|
439 | }); });
|
440 | return this._loadCredentials(credentials, 'federated', true, params);
|
441 | };
|
442 | CredentialsClass.prototype._setCredentialsFromSession = function (session) {
|
443 | var _this = this;
|
444 | logger.debug('set credentials from session');
|
445 | var idToken = session.getIdToken().getJwtToken();
|
446 | var _a = this._config, region = _a.region, userPoolId = _a.userPoolId, identityPoolId = _a.identityPoolId, identityPoolRegion = _a.identityPoolRegion;
|
447 | if (!identityPoolId) {
|
448 | logger.debug('No Cognito Federated Identity pool provided');
|
449 | return Promise.reject('No Cognito Federated Identity pool provided');
|
450 | }
|
451 | if (!identityPoolRegion && !region) {
|
452 | logger.debug('region is not configured for getting the credentials');
|
453 | return Promise.reject('region is not configured for getting the credentials');
|
454 | }
|
455 | var key = 'cognito-idp.' + region + '.amazonaws.com/' + userPoolId;
|
456 | var logins = {};
|
457 | logins[key] = idToken;
|
458 | var cognitoConfig = { region: identityPoolRegion !== null && identityPoolRegion !== void 0 ? identityPoolRegion : region };
|
459 | |
460 |
|
461 |
|
462 |
|
463 |
|
464 |
|
465 | var credentialsProvider = function () { return __awaiter(_this, void 0, void 0, function () {
|
466 | var guestIdentityId, generatedOrRetrievedIdentityId, IdentityId, _a, _b, AccessKeyId, Expiration, SecretKey, SessionToken, primaryIdentityId;
|
467 | return __generator(this, function (_c) {
|
468 | switch (_c.label) {
|
469 | case 0: return [4 , this._getGuestIdentityId()];
|
470 | case 1:
|
471 | guestIdentityId = _c.sent();
|
472 | if (!!guestIdentityId) return [3 , 3];
|
473 | return [4 , (0, CognitoIdentity_1.getId)(cognitoConfig, {
|
474 | IdentityPoolId: identityPoolId,
|
475 | Logins: logins,
|
476 | })];
|
477 | case 2:
|
478 | IdentityId = (_c.sent()).IdentityId;
|
479 | generatedOrRetrievedIdentityId = IdentityId;
|
480 | _c.label = 3;
|
481 | case 3: return [4 , (0, CognitoIdentity_1.getCredentialsForIdentity)(cognitoConfig, {
|
482 | IdentityId: guestIdentityId || generatedOrRetrievedIdentityId,
|
483 | Logins: logins,
|
484 | })];
|
485 | case 4:
|
486 | _a = _c.sent(), _b = _a.Credentials, AccessKeyId = _b.AccessKeyId, Expiration = _b.Expiration, SecretKey = _b.SecretKey, SessionToken = _b.SessionToken, primaryIdentityId = _a.IdentityId;
|
487 | this._identityId = primaryIdentityId;
|
488 | if (!guestIdentityId) return [3 , 6];
|
489 |
|
490 |
|
491 | logger.debug("The guest identity ".concat(guestIdentityId, " has been successfully linked to the logins"));
|
492 | if (guestIdentityId === primaryIdentityId) {
|
493 | logger.debug("The guest identity ".concat(guestIdentityId, " has become the primary identity"));
|
494 | }
|
495 |
|
496 | return [4 , this._removeGuestIdentityId()];
|
497 | case 5:
|
498 |
|
499 | _c.sent();
|
500 | _c.label = 6;
|
501 | case 6:
|
502 |
|
503 | return [2 , {
|
504 | accessKeyId: AccessKeyId,
|
505 | secretAccessKey: SecretKey,
|
506 | sessionToken: SessionToken,
|
507 | expiration: Expiration,
|
508 | identityId: primaryIdentityId,
|
509 | }];
|
510 | }
|
511 | });
|
512 | }); };
|
513 | var credentials = credentialsProvider().catch(function (err) { return __awaiter(_this, void 0, void 0, function () {
|
514 | return __generator(this, function (_a) {
|
515 | throw err;
|
516 | });
|
517 | }); });
|
518 | return this._loadCredentials(credentials, 'userPool', true, null);
|
519 | };
|
520 | CredentialsClass.prototype._loadCredentials = function (credentials, source, authenticated, info) {
|
521 | var _this = this;
|
522 | var that = this;
|
523 | return new Promise(function (res, rej) {
|
524 | credentials
|
525 | .then(function (credentials) { return __awaiter(_this, void 0, void 0, function () {
|
526 | var user, provider, token, expires_at, identity_id;
|
527 | return __generator(this, function (_a) {
|
528 | switch (_a.label) {
|
529 | case 0:
|
530 | logger.debug('Load credentials successfully', credentials);
|
531 | if (this._identityId && !credentials.identityId) {
|
532 | credentials['identityId'] = this._identityId;
|
533 | }
|
534 | that._credentials = credentials;
|
535 | that._credentials.authenticated = authenticated;
|
536 | that._credentials_source = source;
|
537 | that._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;
|
538 | if (source === 'federated') {
|
539 | user = Object.assign({ id: this._credentials.identityId }, info.user);
|
540 | provider = info.provider, token = info.token, expires_at = info.expires_at, identity_id = info.identity_id;
|
541 | try {
|
542 | this._storage.setItem('aws-amplify-federatedInfo', JSON.stringify({
|
543 | provider: provider,
|
544 | token: token,
|
545 | user: user,
|
546 | expires_at: expires_at,
|
547 | identity_id: identity_id,
|
548 | }));
|
549 | }
|
550 | catch (e) {
|
551 | logger.debug('Failed to put federated info into auth storage', e);
|
552 | }
|
553 | }
|
554 | if (!(source === 'guest')) return [3 , 2];
|
555 | return [4 , this._setGuestIdentityId(credentials.identityId)];
|
556 | case 1:
|
557 | _a.sent();
|
558 | _a.label = 2;
|
559 | case 2:
|
560 | res(that._credentials);
|
561 | return [2 ];
|
562 | }
|
563 | });
|
564 | }); })
|
565 | .catch(function (err) {
|
566 | if (err) {
|
567 | logger.debug('Failed to load credentials', credentials);
|
568 | logger.debug('Error loading credentials', err);
|
569 | rej(err);
|
570 | return;
|
571 | }
|
572 | });
|
573 | });
|
574 | };
|
575 | CredentialsClass.prototype.set = function (params, source) {
|
576 | if (source === 'session') {
|
577 | return this._setCredentialsFromSession(params);
|
578 | }
|
579 | else if (source === 'federation') {
|
580 | return this._setCredentialsFromFederation(params);
|
581 | }
|
582 | else if (source === 'guest') {
|
583 | return this._setCredentialsForGuest();
|
584 | }
|
585 | else {
|
586 | logger.debug('no source specified for setting credentials');
|
587 | return Promise.reject('invalid source');
|
588 | }
|
589 | };
|
590 | CredentialsClass.prototype.clear = function () {
|
591 | return __awaiter(this, void 0, void 0, function () {
|
592 | return __generator(this, function (_a) {
|
593 | this._credentials = null;
|
594 | this._credentials_source = null;
|
595 | logger.debug('removing aws-amplify-federatedInfo from storage');
|
596 | this._storage.removeItem('aws-amplify-federatedInfo');
|
597 | return [2 ];
|
598 | });
|
599 | });
|
600 | };
|
601 |
|
602 | CredentialsClass.prototype._getGuestIdentityId = function () {
|
603 | return __awaiter(this, void 0, void 0, function () {
|
604 | var identityPoolId, e_1;
|
605 | return __generator(this, function (_a) {
|
606 | switch (_a.label) {
|
607 | case 0:
|
608 | identityPoolId = this._config.identityPoolId;
|
609 | _a.label = 1;
|
610 | case 1:
|
611 | _a.trys.push([1, 3, , 4]);
|
612 | return [4 , this._storageSync];
|
613 | case 2:
|
614 | _a.sent();
|
615 | return [2 , this._storage.getItem(this._getCognitoIdentityIdStorageKey(identityPoolId))];
|
616 | case 3:
|
617 | e_1 = _a.sent();
|
618 | logger.debug('Failed to get the cached guest identityId', e_1);
|
619 | return [3 , 4];
|
620 | case 4: return [2 ];
|
621 | }
|
622 | });
|
623 | });
|
624 | };
|
625 | CredentialsClass.prototype._setGuestIdentityId = function (identityId) {
|
626 | return __awaiter(this, void 0, void 0, function () {
|
627 | var identityPoolId, e_2;
|
628 | return __generator(this, function (_a) {
|
629 | switch (_a.label) {
|
630 | case 0:
|
631 | identityPoolId = this._config.identityPoolId;
|
632 | _a.label = 1;
|
633 | case 1:
|
634 | _a.trys.push([1, 3, , 4]);
|
635 | return [4 , this._storageSync];
|
636 | case 2:
|
637 | _a.sent();
|
638 | this._storage.setItem(this._getCognitoIdentityIdStorageKey(identityPoolId), identityId);
|
639 | return [3 , 4];
|
640 | case 3:
|
641 | e_2 = _a.sent();
|
642 | logger.debug('Failed to cache guest identityId', e_2);
|
643 | return [3 , 4];
|
644 | case 4: return [2 ];
|
645 | }
|
646 | });
|
647 | });
|
648 | };
|
649 | CredentialsClass.prototype._removeGuestIdentityId = function () {
|
650 | return __awaiter(this, void 0, void 0, function () {
|
651 | var identityPoolId;
|
652 | return __generator(this, function (_a) {
|
653 | identityPoolId = this._config.identityPoolId;
|
654 | logger.debug("removing ".concat(this._getCognitoIdentityIdStorageKey(identityPoolId), " from storage"));
|
655 | this._storage.removeItem(this._getCognitoIdentityIdStorageKey(identityPoolId));
|
656 | return [2 ];
|
657 | });
|
658 | });
|
659 | };
|
660 | |
661 |
|
662 |
|
663 |
|
664 |
|
665 | CredentialsClass.prototype.shear = function (credentials) {
|
666 | return {
|
667 | accessKeyId: credentials.accessKeyId,
|
668 | sessionToken: credentials.sessionToken,
|
669 | secretAccessKey: credentials.secretAccessKey,
|
670 | identityId: credentials.identityId,
|
671 | authenticated: credentials.authenticated,
|
672 | };
|
673 | };
|
674 | return CredentialsClass;
|
675 | }());
|
676 | exports.CredentialsClass = CredentialsClass;
|
677 | exports.Credentials = new CredentialsClass(null);
|
678 | Amplify_1.Amplify.register(exports.Credentials);
|