ngx-amplify
Version:
An angular library for integration AWS cloud services (cognito, s3)
1,593 lines (1,587 loc) • 59.1 kB
JavaScript
import { InjectionToken, NgModule, Injectable, Inject, ɵɵdefineInjectable, ɵɵinject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { __awaiter, __generator, __values } from 'tslib';
import { config, CognitoIdentityCredentials } from 'aws-sdk';
import { CognitoUserPool, AuthenticationDetails, CognitoUserAttribute, CognitoUser } from 'amazon-cognito-identity-js';
import { BehaviorSubject } from 'rxjs';
import * as S3 from 'aws-sdk/clients/s3';
import moment from 'moment';
import { HttpHeaders } from '@angular/common/http';
/**
* @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 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: NgModule, args: [{
declarations: [],
imports: [
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 BehaviorSubject({ state: 'signedOut', user: null });
this.authState$ = this.authState.asObservable();
this.authUserState = new BehaviorSubject({ state: 'signedOut', user: null });
this.authUserState$ = this.authUserState.asObservable();
this.cognitoUserSub = new BehaviorSubject(this.cognitoUser);
this.cognitoUser$ = this.cognitoUserSub.asObservable();
config.region = this.config.region;
config.credentials = new CognitoIdentityCredentials({
IdentityPoolId: this.config.identityPoolId
});
this.poolData = { UserPoolId: config$1.userPoolId, ClientId: this.config.appId };
this.userPool = new 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 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 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 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 CognitoUserAttribute({
Name: name_1,
Value: profile[key]
});
}
else {
attribute = new 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 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;
config.region = this.config.region;
this.cognitoUser = null;
this.cognitoUserSub.next(null);
this.unauthCreds = this.unauthCreds || new 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) {
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 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) { }),
customChallenge: (/**
* @param {?} challengeParameters
* @return {?}
*/
function (challengeParameters) { }),
});
}
catch (error) {
reject(error);
}
}));
};
/**
* @param {?} creds
* @return {?}
*/
AuthService.prototype.signUp = /**
* @param {?} creds
* @return {?}
*/
function (creds) {
/** @type {?} */
var self = this;
// creds.member_since__c = moment().year().toString();
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) {
try {
/** @type {?} */
var attributes = [];
attributes = self.getCognitoAttributes(creds);
return self.userPool.signUp(creds.username, creds.password, attributes, null, (/**
* @param {?} err
* @param {?} result
* @return {?}
*/
function (err, result) {
if (err) {
reject(self.handleError(err, 'signUp'));
}
else {
// console.log('signUp registration successful', result);
resolve(result);
}
}));
}
catch (error) {
reject(self.handleError(error, 'try/catch signUp'));
}
}));
};
/**
* @param {?} username
* @param {?} code
* @return {?}
*/
AuthService.prototype.confirmSignUp = /**
* @param {?} username
* @param {?} code
* @return {?}
*/
function (username, code) {
var _this = this;
/** @type {?} */
var self = this;
/** @type {?} */
var userData = {
Username: username,
Pool: self.userPool
};
/** @type {?} */
var cognitoUser = new CognitoUser(userData);
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) {
try {
cognitoUser.confirmRegistration(code, true, ((/**
* @param {?} err
* @param {?} result
* @return {?}
*/
function (err, result) {
if (err) {
reject(self.handleError(err, 'confirmRegistration'));
}
else {
// console.log('confirm registration successful', result);
resolve(result);
}
})));
}
catch (error) {
reject(_this.handleError(error, 'try/catch confirm signUp'));
}
}));
};
/**
* @param {?} username
* @param {?} verificationCode
* @param {?} password
* @return {?}
*/
AuthService.prototype.confirmPassword = /**
* @param {?} username
* @param {?} verificationCode
* @param {?} password
* @return {?}
*/
function (username, verificationCode, password) {
/** @type {?} */
var self = this;
/** @type {?} */
var userData = {
Username: username,
Pool: this.userPool
};
/** @type {?} */
var cognitoUser = new CognitoUser(userData);
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) {
try {
cognitoUser.confirmPassword(verificationCode, password, {
onFailure: (/**
* @param {?} err
* @return {?}
*/
function (err) {
reject(self.handleError(err, 'confirmPassword'));
}),
onSuccess: (/**
* @return {?}
*/
function () {
resolve('Confirm Password SUCCESS');
})
});
}
catch (error) {
reject(self.handleError(error, 'try/catch confirmPassword'));
}
}));
};
/**
* @param {?} username
* @return {?}
*/
AuthService.prototype.forgotPassword = /**
* @param {?} username
* @return {?}
*/
function (username) {
/** @type {?} */
var self = this;
/** @type {?} */
var userData = {
Username: username,
Pool: this.userPool
};
/** @type {?} */
var cognitoUser = new CognitoUser(userData);
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) {
try {
cognitoUser.forgotPassword({
onFailure: (/**
* @param {?} err
* @return {?}
*/
function (err) {
reject(self.handleError(err, 'forgotPassword'));
}),
onSuccess: (/**
* @return {?}
*/
function () {
resolve('Verification Code Sent');
}),
inputVerificationCode: (/**
* @return {?}
*/
function () {
resolve('Verification Code Sent');
})
});
}
catch (err) {
reject(self.handleError(err, 'try/catch forgotPassword'));
}
}));
};
/**
* @param {?} username
* @return {?}
*/
AuthService.prototype.resendConfirmationCode = /**
* @param {?} username
* @return {?}
*/
function (username) {
/** @type {?} */
var self = this;
/** @type {?} */
var userData = {
Username: username,
Pool: this.userPool
};
/** @type {?} */
var cognitoUser = new CognitoUser(userData);
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) {
try {
cognitoUser.resendConfirmationCode((/**
* @param {?} err
* @param {?} result
* @return {?}
*/
function (err, result) {
if (err) {
// let exception: ICognitoException = self.handleError(err,'resendConfirmationCode');
// console.log('error occurred while confirming registration code', exception);
reject(self.handleError(err, 'resendConfirmationCode'));
}
else {
// console.log('confirm registration successful', result);
resolve(result);
}
}));
}
catch (error) {
// let exception: ICognitoException = self.handleError(error,'try/catch resendConfirmationCode');//new CognitoException(error);
reject(self.handleError(error, 'try/catch resendConfirmationCode'));
}
}));
};
/**
* @return {?}
*/
AuthService.prototype.signOut = /**
* @return {?}
*/
function () {
/** @type {?} */
var self = this;
if (self.cognitoUser) {
/** @type {?} */
var username = self.cognitoUser.getUsername();
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) {
try {
self.cognitoUser.signOut();
self.cognitoUserSub.next(null);
self.authState.next({ state: 'signedOut', user: null });
self.resetCreds(true);
self.user = AuthUser.Factory();
self.authUserState.next({ state: 'signedOut', user: null });
resolve('signOut successful');
}
catch (error) {
reject(self.handleError(error, 'try/catch signOut'));
}
}));
}
};
AuthService.decorators = [
{ type: Injectable, args: [{
providedIn: 'root'
},] }
];
/** @nocollapse */
AuthService.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: Inject, args: [NGX_AMPLIFY_CONFIG,] }] }
]; };
/** @nocollapse */ AuthService.ngInjectableDef = ɵɵdefineInjectable({ factory: function AuthService_Factory() { return new AuthService(ɵɵinject(NGX_AMPLIFY_CONFIG)); }, token: AuthService, providedIn: "root" });
return AuthService;
}());
if (false) {
/**
* @type {?}
* @private
*/
AuthService.prototype.poolData;
/**
* @type {?}
* @private
*/
AuthService.prototype.session;
/**
* @type {?}
* @private
*/
AuthService.prototype.userPool;
/**
* @type {?}
* @private
*/
AuthService.prototype.unauthCreds;
/**
* @type {?}
* @private
*/
AuthService.prototype.resetting;
/**
* @type {?}
* @private
*/
AuthService.prototype.authState;
/** @type {?} */
AuthService.prototype.authState$;
/**
* @type {?}
* @private
*/
AuthService.prototype.authUserState;
/** @type {?} */
AuthService.prototype.authUserState$;
/** @type {?} */
AuthService.prototype.cognitoUser;
/**
* @type {?}
* @private
*/
AuthService.prototype.cognitoUserSub;
/** @type {?} */
AuthService.prototype.cognitoUser$;
/** @type {?} */
AuthService.prototype.user;
/**
* @type {?}
* @private
*/
AuthService.prototype.config;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
var StorageService = /** @class */ (function () {
function StorageService(config, auth) {
this.config = config;
this.auth = auth;
if (!config.storage) {
throw new TypeError('NgxAmplify:Storage options are not found. Please refer to the README for usage.');
}
}
Object.defineProperty(StorageService.prototype, "storage", {
get: /**
* @private
* @return {?}
*/
function () {
config.update({
region: this.config.storage.bucketRegion
});
return new S3({
params: {
'Bucket': this.config.storage.bucketName,
},
region: this.config.storage.bucketRegion
});
},
enumerable: true,
configurable: true
});
/**
* @private
* @param {?} url
* @return {?}
*/
StorageService.prototype.isExpired = /**
* @private
* @param {?} url
* @return {?}
*/
function (url) {
/** @type {?} */
var result;
/** @type {?} */
var _url = new URL(url);
if (_url.search === '') {
result = true;
}
else {
/** @type {?} */
var param = _url.searchParams.get('Expires');
if (param) {
result = moment().isAfter(moment.unix(parseInt(param)));
}
else {
result = false;
}
}
return result;
};
/**
* @param {?} url
* @return {?}
*/
StorageService.prototype.getFileByUrl = /**
* @param {?} url
* @return {?}
*/
function (url) {
/** @type {?} */
var self = this;
/** @type {?} */
var baseUrl = "https://" + self.config.storage.bucketName + ".s3.amazonaws.com/";
/** @type {?} */
var fileKey = url.replace(baseUrl, '');
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) {
try {
if (fileKey === '') {
resolve(url);
}
else if (self.isExpired(url)) {
self.storage.getSignedUrl('getObject', { Key: fileKey }, (/**
* @param {?} err
* @param {?} url
* @return {?}
*/
function (err, url) {
if (err) {
reject(self.handleError(err, 'getSignedUrl'));
}
else {
resolve(url);
}
}));
}
else {
resolve(url);
}
}
catch (error) {
reject(self.handleError(error, 'try/catch getSignedUrl'));
}
}));
};
/**
* @param {?} filename
* @param {?=} folder
* @return {?}
*/
StorageService.prototype.getFile = /**
* @param {?} filename
* @param {?=} folder
* @return {?}
*/
function (filename, folder) {
/** @type {?} */
var self = this;
// File Access Level = "protected" - this prevents unautheticated access to the file.
/** @type {?} */
var directory = self.config.storage.folderLevel + "/";
if (folder) {
directory += folder + "/";
}
/** @type {?} */
var fileKey = "" + directory + filename;
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
function (resolve, reject) {
try {
self.storage.getSignedUrl('getObject', { Key: fileKey }, (/**
* @param {?} err
* @param {?} url
* @return {?}
*/
function (err, url) {
if (err) {
reject(self.handleError(err, 'getSignedUrl'));
}
els