ngx-amplify
Version:
An angular library for integration AWS cloud services (cognito, s3)
1,285 lines (1,255 loc) • 77.3 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('aws-sdk'), require('amazon-cognito-identity-js'), require('rxjs'), require('aws-sdk/clients/s3'), require('moment'), require('@angular/common/http')) :
typeof define === 'function' && define.amd ? define('ngx-amplify', ['exports', '@angular/core', '@angular/common', 'aws-sdk', 'amazon-cognito-identity-js', 'rxjs', 'aws-sdk/clients/s3', 'moment', '@angular/common/http'], factory) :
(global = global || self, factory(global['ngx-amplify'] = {}, global.ng.core, global.ng.common, global.awsSdk, global.amazonCognitoIdentityJs, global.rxjs, global.S3, global.moment, global.ng.common.http));
}(this, (function (exports, core, common, awsSdk, amazonCognitoIdentityJs, rxjs, S3, moment, http) { 'use strict';
moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment;
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
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;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @record
*/
function NgxAmplifyStorageConfig() { }
if (false) {
/** @type {?} */
NgxAmplifyStorageConfig.prototype.bucketName;
/** @type {?} */
NgxAmplifyStorageConfig.prototype.bucketRegion;
/** @type {?|undefined} */
NgxAmplifyStorageConfig.prototype.endpoint;
/** @type {?} */
NgxAmplifyStorageConfig.prototype.folderLevel;
/** @type {?} */
NgxAmplifyStorageConfig.prototype.defaultLevel;
}
/**
* @record
*/
function NgxAmplifyConfig() { }
if (false) {
/** @type {?} */
NgxAmplifyConfig.prototype.region;
/** @type {?} */
NgxAmplifyConfig.prototype.userPoolId;
/** @type {?} */
NgxAmplifyConfig.prototype.appId;
/** @type {?|undefined} */
NgxAmplifyConfig.prototype.idpUrl;
/** @type {?|undefined} */
NgxAmplifyConfig.prototype.identityPoolId;
/** @type {?|undefined} */
NgxAmplifyConfig.prototype.storage;
}
/**
* @record
*/
function NgxAmplifyToken() { }
if (false) {
/** @type {?} */
NgxAmplifyToken.prototype.config;
}
/** @type {?} */
var NGX_AMPLIFY_CONFIG = new core.InjectionToken('NgxAmplifyConfig');
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var NgxAmplifyModule = /** @class */ (function () {
function NgxAmplifyModule() {
}
/**
* @param {?} config
* @return {?}
*/
NgxAmplifyModule.forRoot = /**
* @param {?} config
* @return {?}
*/
function (config) {
return {
ngModule: NgxAmplifyModule,
providers: [
{
provide: NGX_AMPLIFY_CONFIG,
useValue: config
}
]
};
};
NgxAmplifyModule.decorators = [
{ type: core.NgModule, args: [{
declarations: [],
imports: [
common.CommonModule
],
exports: [],
providers: []
},] }
];
return NgxAmplifyModule;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @record
*/
function IAuthCredentials() { }
if (false) {
/** @type {?} */
IAuthCredentials.prototype.accessKeyId;
/** @type {?} */
IAuthCredentials.prototype.secretAccessKey;
/** @type {?} */
IAuthCredentials.prototype.sessionToken;
}
/**
* @record
*/
function IAuthUser() { }
if (false) {
/** @type {?} */
IAuthUser.prototype.identityId;
/** @type {?} */
IAuthUser.prototype.authenticated;
/** @type {?|undefined} */
IAuthUser.prototype.authCredentials;
/** @type {?|undefined} */
IAuthUser.prototype.cognitoProfile;
/** @type {?|undefined} */
IAuthUser.prototype.cognitoUser;
}
/**
* @record
*/
function IAuthState() { }
if (false) {
/** @type {?} */
IAuthState.prototype.state;
/** @type {?} */
IAuthState.prototype.user;
}
/**
* @record
*/
function IAuthUserState() { }
if (false) {
/** @type {?} */
IAuthUserState.prototype.state;
/** @type {?} */
IAuthUserState.prototype.user;
}
/**
* @record
*/
function IAuthResponse() { }
if (false) {
/** @type {?} */
IAuthResponse.prototype.session_key;
/** @type {?} */
IAuthResponse.prototype.accessToken;
/** @type {?} */
IAuthResponse.prototype.expiresIn;
/** @type {?} */
IAuthResponse.prototype.sig;
/** @type {?} */
IAuthResponse.prototype.secret;
/** @type {?} */
IAuthResponse.prototype.userID;
}
/**
* @record
*/
function ICognitoConfigOptions() { }
if (false) {
/** @type {?} */
ICognitoConfigOptions.prototype.region;
/** @type {?} */
ICognitoConfigOptions.prototype.userPoolId;
/** @type {?} */
ICognitoConfigOptions.prototype.appId;
/** @type {?|undefined} */
ICognitoConfigOptions.prototype.idpUrl;
/** @type {?|undefined} */
ICognitoConfigOptions.prototype.identityPoolId;
}
/**
* @record
*/
function ICognitoException() { }
if (false) {
/** @type {?} */
ICognitoException.prototype.code;
/** @type {?|undefined} */
ICognitoException.prototype.columnNumber;
/** @type {?|undefined} */
ICognitoException.prototype.fileName;
/** @type {?|undefined} */
ICognitoException.prototype.lineNumber;
/** @type {?} */
ICognitoException.prototype.message;
/** @type {?|undefined} */
ICognitoException.prototype.name;
/** @type {?|undefined} */
ICognitoException.prototype.originalError;
/** @type {?} */
ICognitoException.prototype.requestId;
/** @type {?} */
ICognitoException.prototype.retryDelay;
/** @type {?} */
ICognitoException.prototype.retryable;
/** @type {?} */
ICognitoException.prototype.statusCode;
/** @type {?} */
ICognitoException.prototype.time;
}
/**
* @record
*/
function ICognitoCredentials() { }
if (false) {
/** @type {?|undefined} */
ICognitoCredentials.prototype.email;
/** @type {?} */
ICognitoCredentials.prototype.username;
/** @type {?} */
ICognitoCredentials.prototype.password;
}
/**
* @record
*/
function ICognitoChangePassword() { }
if (false) {
/** @type {?} */
ICognitoChangePassword.prototype.oldPassword;
/** @type {?} */
ICognitoChangePassword.prototype.newPassword;
}
/**
* @record
*/
function ICognitoSignUpCredentials() { }
/**
* @record
*/
function ICognitoAddress() { }
if (false) {
/** @type {?|undefined} */
ICognitoAddress.prototype.fomatted;
/** @type {?|undefined} */
ICognitoAddress.prototype.street_address;
/** @type {?|undefined} */
ICognitoAddress.prototype.locality;
/** @type {?|undefined} */
ICognitoAddress.prototype.region;
/** @type {?|undefined} */
ICognitoAddress.prototype.postal_code;
/** @type {?|undefined} */
ICognitoAddress.prototype.country;
}
/**
* @record
*/
function ICognitoProfile() { }
if (false) {
/** @type {?} */
ICognitoProfile.prototype.sub;
/** @type {?|undefined} */
ICognitoProfile.prototype.name;
/** @type {?|undefined} */
ICognitoProfile.prototype.given_name;
/** @type {?|undefined} */
ICognitoProfile.prototype.family_name;
/** @type {?|undefined} */
ICognitoProfile.prototype.middle_name;
/** @type {?|undefined} */
ICognitoProfile.prototype.nickname;
/** @type {?|undefined} */
ICognitoProfile.prototype.preferred_username;
/** @type {?|undefined} */
ICognitoProfile.prototype.profile;
/** @type {?|undefined} */
ICognitoProfile.prototype.picture;
/** @type {?|undefined} */
ICognitoProfile.prototype.website;
/** @type {?|undefined} */
ICognitoProfile.prototype.email;
/** @type {?|undefined} */
ICognitoProfile.prototype.email_verified;
/** @type {?|undefined} */
ICognitoProfile.prototype.gender;
/** @type {?|undefined} */
ICognitoProfile.prototype.birthdate;
/** @type {?|undefined} */
ICognitoProfile.prototype.zoneinfo;
/** @type {?|undefined} */
ICognitoProfile.prototype.locale;
/** @type {?|undefined} */
ICognitoProfile.prototype.phone_number;
/** @type {?|undefined} */
ICognitoProfile.prototype.phone_number_verified;
/** @type {?|undefined} */
ICognitoProfile.prototype.address;
/** @type {?|undefined} */
ICognitoProfile.prototype.updated_at;
/** @type {?|undefined} */
ICognitoProfile.prototype.member_since__c;
/** @type {?|undefined} */
ICognitoProfile.prototype.country_code__c;
/** @type {?|undefined} */
ICognitoProfile.prototype.lead_id__c;
/** @type {?|undefined} */
ICognitoProfile.prototype.contact_id__c;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var AuthUser = /** @class */ (function () {
function AuthUser(values) {
if (values) {
this.set(values);
}
else {
this.init();
}
}
/**
* @return {?}
*/
AuthUser.Factory = /**
* @return {?}
*/
function () {
return new AuthUser();
};
/**
* @return {?}
*/
AuthUser.prototype.init = /**
* @return {?}
*/
function () {
this.identityId = '';
this.authenticated = false;
};
/**
* @param {?=} values
* @return {?}
*/
AuthUser.prototype.set = /**
* @param {?=} values
* @return {?}
*/
function (values) {
if (values === void 0) { values = {}; }
Object.assign(this, values);
};
return AuthUser;
}());
if (false) {
/** @type {?} */
AuthUser.prototype.identityId;
/** @type {?} */
AuthUser.prototype.authenticated;
/** @type {?} */
AuthUser.prototype.authCredentials;
/** @type {?} */
AuthUser.prototype.cognitoProfile;
/** @type {?} */
AuthUser.prototype.cognitoUser;
}
var CognitoException = /** @class */ (function () {
function CognitoException(values) {
if (values === void 0) { values = {}; }
Object.assign(this, values);
}
return CognitoException;
}());
if (false) {
/** @type {?} */
CognitoException.prototype.code;
/** @type {?} */
CognitoException.prototype.columnNumber;
/** @type {?} */
CognitoException.prototype.fileName;
/** @type {?} */
CognitoException.prototype.lineNumber;
/** @type {?} */
CognitoException.prototype.message;
/** @type {?} */
CognitoException.prototype.name;
/** @type {?} */
CognitoException.prototype.originalError;
/** @type {?} */
CognitoException.prototype.requestId;
/** @type {?} */
CognitoException.prototype.retryDelay;
/** @type {?} */
CognitoException.prototype.retryable;
/** @type {?} */
CognitoException.prototype.statusCode;
/** @type {?} */
CognitoException.prototype.time;
}
var CognitoProfile = /** @class */ (function () {
function CognitoProfile(values) {
if (values === void 0) { values = {}; }
Object.assign(this, values);
}
/**
* @return {?}
*/
CognitoProfile.Factory = /**
* @return {?}
*/
function () {
/** @type {?} */
var init = { sub: '' };
return new CognitoProfile(init);
};
return CognitoProfile;
}());
if (false) {
/** @type {?} */
CognitoProfile.prototype.sub;
/** @type {?} */
CognitoProfile.prototype.name;
/** @type {?} */
CognitoProfile.prototype.given_name;
/** @type {?} */
CognitoProfile.prototype.family_name;
/** @type {?} */
CognitoProfile.prototype.middle_name;
/** @type {?} */
CognitoProfile.prototype.nickname;
/** @type {?} */
CognitoProfile.prototype.preferred_username;
/** @type {?} */
CognitoProfile.prototype.profile;
/** @type {?} */
CognitoProfile.prototype.picture;
/** @type {?} */
CognitoProfile.prototype.website;
/** @type {?} */
CognitoProfile.prototype.email;
/** @type {?} */
CognitoProfile.prototype.email_verified;
/** @type {?} */
CognitoProfile.prototype.gender;
/** @type {?} */
CognitoProfile.prototype.birthdate;
/** @type {?} */
CognitoProfile.prototype.zoneinfo;
/** @type {?} */
CognitoProfile.prototype.locale;
/** @type {?} */
CognitoProfile.prototype.phone_number;
/** @type {?} */
CognitoProfile.prototype.phone_number_verified;
/** @type {?} */
CognitoProfile.prototype.address;
/** @type {?} */
CognitoProfile.prototype.updated_at;
/** @type {?} */
CognitoProfile.prototype.member_since__c;
/** @type {?} */
CognitoProfile.prototype.country_code__c;
/** @type {?} */
CognitoProfile.prototype.lead_id__c;
/** @type {?} */
CognitoProfile.prototype.contact_id__c;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var AuthService = /** @class */ (function () {
function AuthService(config$1) {
this.config = config$1;
this.resetting = false;
this.authState = new rxjs.BehaviorSubject({ state: 'signedOut', user: null });
this.authState$ = this.authState.asObservable();
this.authUserState = new rxjs.BehaviorSubject({ state: 'signedOut', user: null });
this.authUserState$ = this.authUserState.asObservable();
this.cognitoUserSub = new rxjs.BehaviorSubject(this.cognitoUser);
this.cognitoUser$ = this.cognitoUserSub.asObservable();
awsSdk.config.region = this.config.region;
awsSdk.config.credentials = new awsSdk.CognitoIdentityCredentials({
IdentityPoolId: this.config.identityPoolId
});
this.poolData = { UserPoolId: config$1.userPoolId, ClientId: this.config.appId };
this.userPool = new amazonCognitoIdentityJs.CognitoUserPool(this.poolData);
this.user = AuthUser.Factory();
// this.authUserState.next({ state: 'signedOut', user: this.user });
// this.refreshOrResetCreds();
// this.currentAuthUser = this.currentAuthUser.bind(this);
}
/**
* @private
* @param {?} creds
* @return {?}
*/
AuthService.prototype.authDetails = /**
* @private
* @param {?} creds
* @return {?}
*/
function (creds) {
return new amazonCognitoIdentityJs.AuthenticationDetails({ Username: creds.username, Password: creds.password });
};
/**
* @private
* @return {?}
*/
AuthService.prototype.buildCreds = /**
* @private
* @return {?}
*/
function () {
/** @type {?} */
var self = this;
/** @type {?} */
var json = self.buildLogins(self.session.getIdToken().getJwtToken());
return new awsSdk.CognitoIdentityCredentials(json);
};
/**
* @private
* @param {?} token
* @return {?}
*/
AuthService.prototype.buildLogins = /**
* @private
* @param {?} token
* @return {?}
*/
function (token) {
/** @type {?} */
var self = this;
/** @type {?} */
var key = self.config.idpUrl + "/" + self.config.userPoolId;
/** @type {?} */
var json = { IdentityPoolId: self.config.identityPoolId, Logins: {} };
json.Logins[key] = token;
return json;
};
/**
* @private
* @param {?} error
* @param {?} caller
* @return {?}
*/
AuthService.prototype.handleError = /**
* @private
* @param {?} error
* @param {?} caller
* @return {?}
*/
function (error, caller) {
/** @type {?} */
var exception = new CognitoException(error);
console.error("AWS Cognito Service::handleError callerMethod::" + caller, exception);
return exception;
};
/**
* @private
* @return {?}
*/
AuthService.prototype.getCurrentUser = /**
* @private
* @return {?}
*/
function () {
return this.userPool.getCurrentUser();
};
/**
* @private
* @param {?} profile
* @return {?}
*/
AuthService.prototype.getCognitoAttributes = /**
* @private
* @param {?} profile
* @return {?}
*/
function (profile) {
/** @type {?} */
var cognitoAttributes = [];
for (var key in profile) {
if (!key.includes("password") && !key.includes("confirmPassword")) {
/** @type {?} */
var attribute = void 0;
if (key.includes("username")) {
attribute = new amazonCognitoIdentityJs.CognitoUserAttribute({
Name: "preferred_username",
Value: profile[key]
});
}
else if (key.endsWith("__c")) {
/** @type {?} */
var k = key.substring(0, key.length - 3);
/** @type {?} */
var name_1 = "custom:" + k;
attribute = new amazonCognitoIdentityJs.CognitoUserAttribute({
Name: name_1,
Value: profile[key]
});
}
else {
attribute = new amazonCognitoIdentityJs.CognitoUserAttribute({
Name: key,
Value: profile[key]
});
}
cognitoAttributes.push(attribute);
}
}
return cognitoAttributes;
};
/**
* @private
* @param {?} creds
* @return {?}
*/
AuthService.prototype.getCognitoUser = /**
* @private
* @param {?} creds
* @return {?}
*/
function (creds) {
/** @type {?} */
var self = this;
/** @type {?} */
var result = new amazonCognitoIdentityJs.CognitoUser({ Username: creds.username, Pool: self.userPool });
return result;
};
/**
* @return {?}
*/
AuthService.prototype.getJwtToken = /**
* @return {?}
*/
function () {
/** @type {?} */
var self = this;
/** @type {?} */
var user = self.getCurrentUser();
/** @type {?} */
var token;
if (user !== null) {
token = user.getSignInUserSession().getAccessToken().getJwtToken();
}
return token;
};
/**
* @param {?} attributes
* @return {?}
*/
AuthService.prototype.getCognitoProfile = /**
* @param {?} attributes
* @return {?}
*/
function (attributes) {
/** @type {?} */
var dynObj = CognitoProfile.Factory();
/** @type {?} */
var values = attributes;
((/** @type {?} */ (values))).forEach((/**
* @param {?} attr
* @return {?}
*/
function (attr) {
if (attr.Name.startsWith('custom:')) {
/** @type {?} */
var attributeName = attr.Name.substring(7);
dynObj[attributeName + '__c'] = attr.Value;
}
else {
dynObj[attr.Name] = attr.Value;
}
}));
/** @type {?} */
var result = new CognitoProfile(dynObj);
return result;
};
/**
* @private
* @param {?} cognitoUser
* @return {?}
*/
AuthService.prototype.setCognitoProfile = /**
* @private
* @param {?} cognitoUser
* @return {?}
*/
function (cognitoUser) {
/** @type {?} */
var self = this;
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) {
if (cognitoUser === null) {
reject(null);
}
else {
cognitoUser.getUserData((/**
* @param {?} err
* @param {?} result
* @return {?}
*/
function (err, result) {
if (err) {
reject(self.handleError(err, 'setCognitoProfile'));
}
/** @type {?} */
var dynObj = self.getCognitoProfile(result.UserAttributes);
if (dynObj.sub) {
self.user.identityId = dynObj.sub;
}
self.user.cognitoProfile = dynObj;
resolve(dynObj);
}));
}
}));
};
/**
* @param {?} attributes
* @return {?}
*/
AuthService.prototype.updateCognitoProfile = /**
* @param {?} attributes
* @return {?}
*/
function (attributes) {
var _this = this;
/** @type {?} */
var self = this;
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
try {
self.cognitoUser.updateAttributes(attributes, (/**
* @param {?} err
* @param {?} result
* @return {?}
*/
function (err, result) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (err) {
reject(self.handleError(err, 'updateAttributes'));
}
self.setCognitoProfile(self.cognitoUser)
.then((/**
* @param {?} profile
* @return {?}
*/
function (profile) {
resolve(profile);
}))
.catch((/**
* @param {?} error
* @return {?}
*/
function (error) {
reject(self.handleError(error, 'setCognitoProfile'));
}));
return [2 /*return*/];
});
}); }));
}
catch (error) {
reject(self.handleError(error, 'try/catch updateCognitoProfile'));
}
return [2 /*return*/];
});
}); }));
};
/**
* @private
* @param {?=} clearCache
* @return {?}
*/
AuthService.prototype.resetCreds = /**
* @private
* @param {?=} clearCache
* @return {?}
*/
function (clearCache) {
if (clearCache === void 0) { clearCache = false; }
// console.log('Resetting credentials for unauth access');
this.resetting = true;
awsSdk.config.region = this.config.region;
this.cognitoUser = null;
this.cognitoUserSub.next(null);
this.unauthCreds = this.unauthCreds || new awsSdk.CognitoIdentityCredentials({ IdentityPoolId: this.config.identityPoolId });
if (clearCache) {
this.unauthCreds.clearCachedId();
}
this.setCredentials(this.unauthCreds);
this.resetting = false;
};
/**
* @return {?}
*/
AuthService.prototype.currentAuthUser = /**
* @return {?}
*/
function () {
return __awaiter(this, void 0, void 0, function () {
var self, user;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this;
user = this.userPool.getCurrentUser();
if (!(user !== null)) return [3 /*break*/, 2];
return [4 /*yield*/, this.refreshSession(user)];
case 1:
_a.sent();
_a.label = 2;
case 2: /* else {
self.authState.next({state: 'signedOut', user: user });
self.cognitoUserSub.next(user);
self.authUserState.next({ state: 'signedOut', user: self.user });
} */ return [2 /*return*/, self.user];
}
});
});
};
/**
* @return {?}
*/
AuthService.prototype.refreshOrResetCreds = /**
* @return {?}
*/
function () {
return __awaiter(this, void 0, void 0, function () {
var session;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.cognitoUser = this.userPool.getCurrentUser();
if (!(this.cognitoUser !== null)) return [3 /*break*/, 3];
if (!(this.cognitoUser.getSignInUserSession() === null)) return [3 /*break*/, 2];
return [4 /*yield*/, this.refreshSession()];
case 1:
session = _a.sent();
_a.label = 2;
case 2: return [3 /*break*/, 4];
case 3:
this.resetCreds();
_a.label = 4;
case 4: return [2 /*return*/];
}
});
});
};
/**
* @private
* @param {?=} user
* @return {?}
*/
AuthService.prototype.refreshSession = /**
* @private
* @param {?=} user
* @return {?}
*/
function (user) {
var _this = this;
/** @type {?} */
var self = this;
if (user === undefined) {
user = this.userPool.getCurrentUser();
}
self.cognitoUser = user; // Object.assign({},user, self.cognitoUser);
// console.log('self.user on refresh', self.cognitoUser);
// self.session = user.;
if (self.session && self.session.isValid) {
// console.log('using the current session already refreshed..');
self.cognitoUser.setSignInUserSession(self.session);
return new Promise((/**
* @param {?} resolve
* @return {?}
*/
function (resolve) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, self.saveCreds(self.cognitoUser, self.session)];
case 1:
_a.sent();
resolve(self.session);
return [2 /*return*/];
}
});
}); }));
}
else {
/* return self.cognitoUser.getSession(async (err, session: CognitoUserSession) => {
if (err) { console.log('Error refreshing user session', err); return err; }
console.log(`${new Date()} - Refreshed session for ${self.cognitoUser.getUsername()}. Valid?: `, session.isValid());
self.session = session;
self.cognitoUser.setSignInUserSession(session);
await self.saveCreds(self.cognitoUser, session);
return session;
}) */
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
self.cognitoUser.getSession((/**
* @param {?} err
* @param {?} session
* @return {?}
*/
function (err, session) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (err) {
console.log('Error refreshing user session', err);
reject(err);
}
// console.log(`${new Date()} - Refreshed session for ${self.cognitoUser.getUsername()}. Valid?: `, session.isValid());
self.session = session;
self.cognitoUser.setSignInUserSession(session);
return [4 /*yield*/, self.saveCreds(self.cognitoUser, session)];
case 1:
_a.sent();
resolve(session);
return [2 /*return*/];
}
});
}); }));
return [2 /*return*/];
});
}); }));
}
};
/**
* @param {?=} cognitoUser
* @param {?=} session
* @return {?}
*/
AuthService.prototype.saveCreds = /**
* @param {?=} cognitoUser
* @param {?=} session
* @return {?}
*/
function (cognitoUser, session) {
return __awaiter(this, void 0, void 0, function () {
var self;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this;
if (session) {
self.session = session;
self.user.authenticated = session.isValid();
self.authState.next({ state: 'signedIn', user: cognitoUser });
}
if (!cognitoUser) return [3 /*break*/, 2];
self.cognitoUser = cognitoUser;
self.user.cognitoUser = cognitoUser;
self.authState.next({ state: 'signedIn', user: cognitoUser });
self.cognitoUserSub.next(cognitoUser);
self.user.cognitoProfile = CognitoProfile.Factory();
return [4 /*yield*/, self.setCognitoProfile(cognitoUser)];
case 1:
_a.sent();
self.authUserState.next({ state: 'signedIn', user: self.user });
_a.label = 2;
case 2:
self.setCredentials(self.buildCreds());
return [2 /*return*/, self.user];
}
});
});
};
/**
* @private
* @param {?} creds
* @return {?}
*/
AuthService.prototype.setCredentials = /**
* @private
* @param {?} creds
* @return {?}
*/
function (creds) {
awsSdk.config.credentials = creds;
};
/**
* @param {?} creds
* @return {?}
*/
AuthService.prototype.signIn = /**
* @param {?} creds
* @return {?}
*/
function (creds) {
var _this = this;
/** @type {?} */
var self = this;
/** @type {?} */
var cognitoUser = self.getCognitoUser(creds);
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) {
try {
cognitoUser.authenticateUser(self.authDetails(creds), {
onSuccess: (/**
* @param {?} session
* @return {?}
*/
function (session) { return __awaiter(_this, void 0, void 0, function () {
var user;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// console.log(`Signed in user ${cognitoUser.getUsername()}. Sessiong valid?: `, session.isValid());
return [4 /*yield*/, self.saveCreds(cognitoUser, session)];
case 1:
user = _a.sent();
resolve(user);
return [2 /*return*/];
}
});
}); }),
onFailure: (/**
* @param {?} err
* @return {?}
*/
function (err) {
reject(self.handleError(err, 'signIn'));
}),
newPasswordRequired: (/**
* @param {?} userAttributes
* @param {?} requiredAttributes
* @return {?}
*/
function (userAttributes, requiredAttributes) {
cognitoUser.completeNewPasswordChallenge(creds.password, requiredAttributes, {
onSuccess: (/**
* @param {?} session
* @return {?}
*/
function (session) { return __awaiter(_this, void 0, void 0, function () {
var aws_creds, user;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
aws_creds = new awsSdk.CognitoIdentityCredentials(self.buildLogins(session.getIdToken().getJwtToken()));
return [4 /*yield*/, self.saveCreds(cognitoUser, session)];
case 1:
user = _a.sent();
resolve(user);
return [2 /*return*/];
}
});
}); }),
onFailure: (/**
* @param {?} err
* @return {?}
*/
function (err) {
reject(self.handleError(err, 'completeNewPasswordChallenge'));
})
});
}),
mfaRequired: (/**
* @param {?} challengeName
* @param {?} challengeParameters
* @return {?}
*/
function (challengeName, challengeParameters) {