ngx-amplify
Version:
An angular library for integration AWS cloud services (cognito, s3)
1,647 lines (1,637 loc) • 50.1 kB
JavaScript
import { InjectionToken, NgModule, Injectable, Inject, ɵɵdefineInjectable, ɵɵinject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { __awaiter } 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 {?} */
const NGX_AMPLIFY_CONFIG = new InjectionToken('NgxAmplifyConfig');
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class NgxAmplifyModule {
/**
* @param {?} config
* @return {?}
*/
static forRoot(config) {
return {
ngModule: NgxAmplifyModule,
providers: [
{
provide: NGX_AMPLIFY_CONFIG,
useValue: config
}
]
};
}
}
NgxAmplifyModule.decorators = [
{ type: NgModule, args: [{
declarations: [],
imports: [
CommonModule
],
exports: [],
providers: []
},] }
];
/**
* @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
*/
class AuthUser {
/**
* @param {?=} values
*/
constructor(values) {
if (values) {
this.set(values);
}
else {
this.init();
}
}
/**
* @return {?}
*/
static Factory() {
return new AuthUser();
}
/**
* @return {?}
*/
init() {
this.identityId = '';
this.authenticated = false;
}
/**
* @param {?=} values
* @return {?}
*/
set(values = {}) {
Object.assign(this, values);
}
}
if (false) {
/** @type {?} */
AuthUser.prototype.identityId;
/** @type {?} */
AuthUser.prototype.authenticated;
/** @type {?} */
AuthUser.prototype.authCredentials;
/** @type {?} */
AuthUser.prototype.cognitoProfile;
/** @type {?} */
AuthUser.prototype.cognitoUser;
}
class CognitoException {
/**
* @param {?=} values
*/
constructor(values = {}) {
Object.assign(this, values);
}
}
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;
}
class CognitoProfile {
/**
* @param {?=} values
*/
constructor(values = {}) {
Object.assign(this, values);
}
/**
* @return {?}
*/
static Factory() {
/** @type {?} */
let init = { sub: '' };
return new CognitoProfile(init);
}
}
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
*/
class AuthService {
/**
* @param {?} config
*/
constructor(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 {?}
*/
authDetails(creds) {
return new AuthenticationDetails({ Username: creds.username, Password: creds.password });
}
/**
* @private
* @return {?}
*/
buildCreds() {
/** @type {?} */
let self = this;
/** @type {?} */
let json = self.buildLogins(self.session.getIdToken().getJwtToken());
return new CognitoIdentityCredentials(json);
}
/**
* @private
* @param {?} token
* @return {?}
*/
buildLogins(token) {
/** @type {?} */
let self = this;
/** @type {?} */
let key = `${self.config.idpUrl}/${self.config.userPoolId}`;
/** @type {?} */
let json = { IdentityPoolId: self.config.identityPoolId, Logins: {} };
json.Logins[key] = token;
return json;
}
/**
* @private
* @param {?} error
* @param {?} caller
* @return {?}
*/
handleError(error, caller) {
/** @type {?} */
let exception = new CognitoException(error);
console.error(`AWS Cognito Service::handleError callerMethod::${caller}`, exception);
return exception;
}
/**
* @private
* @return {?}
*/
getCurrentUser() {
return this.userPool.getCurrentUser();
}
/**
* @private
* @param {?} profile
* @return {?}
*/
getCognitoAttributes(profile) {
/** @type {?} */
let cognitoAttributes = [];
for (let key in profile) {
if (!key.includes("password") && !key.includes("confirmPassword")) {
/** @type {?} */
let attribute;
if (key.includes("username")) {
attribute = new CognitoUserAttribute({
Name: "preferred_username",
Value: profile[key]
});
}
else if (key.endsWith("__c")) {
/** @type {?} */
let k = key.substring(0, key.length - 3);
/** @type {?} */
let name = `custom:${k}`;
attribute = new CognitoUserAttribute({
Name: name,
Value: profile[key]
});
}
else {
attribute = new CognitoUserAttribute({
Name: key,
Value: profile[key]
});
}
cognitoAttributes.push(attribute);
}
}
return cognitoAttributes;
}
/**
* @private
* @param {?} creds
* @return {?}
*/
getCognitoUser(creds) {
/** @type {?} */
let self = this;
/** @type {?} */
let result = new CognitoUser({ Username: creds.username, Pool: self.userPool });
return result;
}
/**
* @return {?}
*/
getJwtToken() {
/** @type {?} */
let self = this;
/** @type {?} */
let user = self.getCurrentUser();
/** @type {?} */
let token;
if (user !== null) {
token = user.getSignInUserSession().getAccessToken().getJwtToken();
}
return token;
}
/**
* @param {?} attributes
* @return {?}
*/
getCognitoProfile(attributes) {
/** @type {?} */
let dynObj = CognitoProfile.Factory();
/** @type {?} */
let values = attributes;
((/** @type {?} */ (values))).forEach((/**
* @param {?} attr
* @return {?}
*/
attr => {
if (attr.Name.startsWith('custom:')) {
/** @type {?} */
let attributeName = attr.Name.substring(7);
dynObj[attributeName + '__c'] = attr.Value;
}
else {
dynObj[attr.Name] = attr.Value;
}
}));
/** @type {?} */
let result = new CognitoProfile(dynObj);
return result;
}
/**
* @private
* @param {?} cognitoUser
* @return {?}
*/
setCognitoProfile(cognitoUser) {
/** @type {?} */
let self = this;
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
if (cognitoUser === null) {
reject(null);
}
else {
cognitoUser.getUserData((/**
* @param {?} err
* @param {?} result
* @return {?}
*/
(err, result) => {
if (err) {
reject(self.handleError(err, 'setCognitoProfile'));
}
/** @type {?} */
let dynObj = self.getCognitoProfile(result.UserAttributes);
if (dynObj.sub) {
self.user.identityId = dynObj.sub;
}
self.user.cognitoProfile = dynObj;
resolve(dynObj);
}));
}
}));
}
/**
* @param {?} attributes
* @return {?}
*/
updateCognitoProfile(attributes) {
/** @type {?} */
let self = this;
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => __awaiter(this, void 0, void 0, function* () {
try {
self.cognitoUser.updateAttributes(attributes, (/**
* @param {?} err
* @param {?} result
* @return {?}
*/
(err, result) => __awaiter(this, void 0, void 0, function* () {
if (err) {
reject(self.handleError(err, 'updateAttributes'));
}
self.setCognitoProfile(self.cognitoUser)
.then((/**
* @param {?} profile
* @return {?}
*/
(profile) => {
resolve(profile);
}))
.catch((/**
* @param {?} error
* @return {?}
*/
(error) => {
reject(self.handleError(error, 'setCognitoProfile'));
}));
})));
}
catch (error) {
reject(self.handleError(error, 'try/catch updateCognitoProfile'));
}
})));
}
/**
* @private
* @param {?=} clearCache
* @return {?}
*/
resetCreds(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 {?}
*/
currentAuthUser() {
return __awaiter(this, void 0, void 0, /** @this {!AuthService} */ function* () {
/** @type {?} */
let self = this;
/** @type {?} */
let user = this.userPool.getCurrentUser();
// console.log('auth:currentAuthUser', user);
if (user !== null) {
yield this.refreshSession(user);
} /* else {
self.authState.next({state: 'signedOut', user: user });
self.cognitoUserSub.next(user);
self.authUserState.next({ state: 'signedOut', user: self.user });
} */
return self.user;
});
}
/**
* @return {?}
*/
refreshOrResetCreds() {
return __awaiter(this, void 0, void 0, /** @this {!AuthService} */ function* () {
this.cognitoUser = this.userPool.getCurrentUser();
if (this.cognitoUser !== null) {
if (this.cognitoUser.getSignInUserSession() === null) {
/** @type {?} */
let session = yield this.refreshSession();
}
}
else {
this.resetCreds();
}
});
}
/**
* @private
* @param {?=} user
* @return {?}
*/
refreshSession(user) {
/** @type {?} */
let 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 {?}
*/
(resolve) => __awaiter(this, void 0, void 0, function* () {
yield self.saveCreds(self.cognitoUser, self.session);
resolve(self.session);
})));
}
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 {?}
*/
(resolve, reject) => __awaiter(this, void 0, void 0, function* () {
self.cognitoUser.getSession((/**
* @param {?} err
* @param {?} session
* @return {?}
*/
(err, session) => __awaiter(this, void 0, void 0, function* () {
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);
yield self.saveCreds(self.cognitoUser, session);
resolve(session);
})));
})));
}
}
/**
* @param {?=} cognitoUser
* @param {?=} session
* @return {?}
*/
saveCreds(cognitoUser, session) {
return __awaiter(this, void 0, void 0, /** @this {!AuthService} */ function* () {
/** @type {?} */
let self = this;
if (session) {
self.session = session;
self.user.authenticated = session.isValid();
self.authState.next({ state: 'signedIn', user: cognitoUser });
}
if (cognitoUser) {
self.cognitoUser = cognitoUser;
self.user.cognitoUser = cognitoUser;
self.authState.next({ state: 'signedIn', user: cognitoUser });
self.cognitoUserSub.next(cognitoUser);
self.user.cognitoProfile = CognitoProfile.Factory();
yield self.setCognitoProfile(cognitoUser);
self.authUserState.next({ state: 'signedIn', user: self.user });
}
self.setCredentials(self.buildCreds());
return self.user;
});
}
/**
* @private
* @param {?} creds
* @return {?}
*/
setCredentials(creds) {
config.credentials = creds;
}
/**
* @param {?} creds
* @return {?}
*/
signIn(creds) {
/** @type {?} */
let self = this;
/** @type {?} */
let cognitoUser = self.getCognitoUser(creds);
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
try {
cognitoUser.authenticateUser(self.authDetails(creds), {
onSuccess: (/**
* @param {?} session
* @return {?}
*/
(session) => __awaiter(this, void 0, void 0, function* () {
// console.log(`Signed in user ${cognitoUser.getUsername()}. Sessiong valid?: `, session.isValid());
/** @type {?} */
let user = yield self.saveCreds(cognitoUser, session);
resolve(user);
})),
onFailure: (/**
* @param {?} err
* @return {?}
*/
(err) => {
reject(self.handleError(err, 'signIn'));
}),
newPasswordRequired: (/**
* @param {?} userAttributes
* @param {?} requiredAttributes
* @return {?}
*/
(userAttributes, requiredAttributes) => {
cognitoUser.completeNewPasswordChallenge(creds.password, requiredAttributes, {
onSuccess: (/**
* @param {?} session
* @return {?}
*/
(session) => __awaiter(this, void 0, void 0, function* () {
/** @type {?} */
let aws_creds;
aws_creds = new CognitoIdentityCredentials(self.buildLogins(session.getIdToken().getJwtToken()));
/** @type {?} */
let user = yield self.saveCreds(cognitoUser, session);
resolve(user);
})),
onFailure: (/**
* @param {?} err
* @return {?}
*/
(err) => {
reject(self.handleError(err, 'completeNewPasswordChallenge'));
})
});
}),
mfaRequired: (/**
* @param {?} challengeName
* @param {?} challengeParameters
* @return {?}
*/
(challengeName, challengeParameters) => { }),
customChallenge: (/**
* @param {?} challengeParameters
* @return {?}
*/
(challengeParameters) => { }),
});
}
catch (error) {
reject(error);
}
}));
}
/**
* @param {?} creds
* @return {?}
*/
signUp(creds) {
/** @type {?} */
let self = this;
// creds.member_since__c = moment().year().toString();
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
try {
/** @type {?} */
let attributes = [];
attributes = self.getCognitoAttributes(creds);
return self.userPool.signUp(creds.username, creds.password, attributes, null, (/**
* @param {?} err
* @param {?} result
* @return {?}
*/
(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 {?}
*/
confirmSignUp(username, code) {
/** @type {?} */
let self = this;
/** @type {?} */
let userData = {
Username: username,
Pool: self.userPool
};
/** @type {?} */
let cognitoUser = new CognitoUser(userData);
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
try {
cognitoUser.confirmRegistration(code, true, ((/**
* @param {?} err
* @param {?} result
* @return {?}
*/
(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 {?}
*/
confirmPassword(username, verificationCode, password) {
/** @type {?} */
let self = this;
/** @type {?} */
let userData = {
Username: username,
Pool: this.userPool
};
/** @type {?} */
let cognitoUser = new CognitoUser(userData);
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
try {
cognitoUser.confirmPassword(verificationCode, password, {
onFailure: (/**
* @param {?} err
* @return {?}
*/
(err) => {
reject(self.handleError(err, 'confirmPassword'));
}),
onSuccess: (/**
* @return {?}
*/
() => {
resolve('Confirm Password SUCCESS');
})
});
}
catch (error) {
reject(self.handleError(error, 'try/catch confirmPassword'));
}
}));
}
/**
* @param {?} username
* @return {?}
*/
forgotPassword(username) {
/** @type {?} */
let self = this;
/** @type {?} */
let userData = {
Username: username,
Pool: this.userPool
};
/** @type {?} */
let cognitoUser = new CognitoUser(userData);
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
try {
cognitoUser.forgotPassword({
onFailure: (/**
* @param {?} err
* @return {?}
*/
(err) => {
reject(self.handleError(err, 'forgotPassword'));
}),
onSuccess: (/**
* @return {?}
*/
() => {
resolve('Verification Code Sent');
}),
inputVerificationCode: (/**
* @return {?}
*/
() => {
resolve('Verification Code Sent');
})
});
}
catch (err) {
reject(self.handleError(err, 'try/catch forgotPassword'));
}
}));
}
/**
* @param {?} username
* @return {?}
*/
resendConfirmationCode(username) {
/** @type {?} */
let self = this;
/** @type {?} */
let userData = {
Username: username,
Pool: this.userPool
};
/** @type {?} */
let cognitoUser = new CognitoUser(userData);
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
try {
cognitoUser.resendConfirmationCode((/**
* @param {?} err
* @param {?} result
* @return {?}
*/
(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 {?}
*/
signOut() {
/** @type {?} */
let self = this;
if (self.cognitoUser) {
/** @type {?} */
let username = self.cognitoUser.getUsername();
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(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 = () => [
{ 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" });
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
*/
class StorageService {
/**
* @param {?} config
* @param {?} auth
*/
constructor(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.');
}
}
/**
* @private
* @return {?}
*/
get storage() {
config.update({
region: this.config.storage.bucketRegion
});
return new S3({
params: {
'Bucket': this.config.storage.bucketName,
},
region: this.config.storage.bucketRegion
});
}
/**
* @private
* @param {?} url
* @return {?}
*/
isExpired(url) {
/** @type {?} */
let result;
/** @type {?} */
let _url = new URL(url);
if (_url.search === '') {
result = true;
}
else {
/** @type {?} */
let param = _url.searchParams.get('Expires');
if (param) {
result = moment().isAfter(moment.unix(parseInt(param)));
}
else {
result = false;
}
}
return result;
}
/**
* @param {?} url
* @return {?}
*/
getFileByUrl(url) {
/** @type {?} */
let self = this;
/** @type {?} */
let baseUrl = `https://${self.config.storage.bucketName}.s3.amazonaws.com/`;
/** @type {?} */
let fileKey = url.replace(baseUrl, '');
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
try {
if (fileKey === '') {
resolve(url);
}
else if (self.isExpired(url)) {
self.storage.getSignedUrl('getObject', { Key: fileKey }, (/**
* @param {?} err
* @param {?} url
* @return {?}
*/
(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 {?}
*/
getFile(filename, folder) {
/** @type {?} */
let self = this;
// File Access Level = "protected" - this prevents unautheticated access to the file.
/** @type {?} */
let directory = `${self.config.storage.folderLevel}/`;
if (folder) {
directory += `${folder}/`;
}
/** @type {?} */
let fileKey = `${directory}${filename}`;
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
try {
self.storage.getSignedUrl('getObject', { Key: fileKey }, (/**
* @param {?} err
* @param {?} url
* @return {?}
*/
(err, url) => {
if (err) {
reject(self.handleError(err, 'getSignedUrl'));
}
else {
// self.cognitoService.user.cognitoProfile.picture = url;
resolve(url);
}
}));
}
catch (error) {
reject(self.handleError(error, 'try/catch getSignedUrl'));
}
}));
}
/**
* @param {?} file
* @param {?} filename
* @param {?=} folder
* @param {?=} accessLevel
* @return {?}
*/
upload(file, filename, folder, accessLevel) {
/** @type {?} */
let self = this;
// self.config.folderLevel = "protected" - this prevents unautheticated access to the file.
/** @type {?} */
let directory = '';
if (accessLevel) {
directory = `${accessLevel}/`;
}
else {
directory = `${self.config.storage.defaultLevel}/`;
}
if (folder) {
directory += `${folder}/`;
}
filename = filename.toLowerCase().replace(/\s+/g, "-");
if (file.type === 'image/jpeg') {
filename += '.jpg';
}
if (file.type === 'image/png') {
filename += '.png';
}
if (file.type === 'image/tiff') {
filename += '.tiff';
}
/** @type {?} */
let fileKey = `${directory}${filename}`;
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
try {
self.storage.upload({
Bucket: self.config.storage.bucketName,
Key: fileKey,
ContentType: file.type,
ContentEncoding: 'base64',
Body: file,
StorageClass: 'STANDARD',
}, (/**
* @param {?} err
* @param {?} data
* @return {?}
*/
(err, data) => {
if (err) {
self.handleError(err, 'error during upload.');
reject(err);
}
else {
console.log('successful upload.');
resolve(data);
}
}));
}
catch (error) {
reject(self.handleError(error, 'try/catch upload'));
}
}));
}
/**
* @param {?=} directory
* @return {?}
*/
list(directory) {
/** @type {?} */
let self = this;
return new Promise((/**
* @param {?} resolve
* @param {?} reject
* @return {?}
*/
(resolve, reject) => {
if (directory) {
// let directoryKey = encodeURIComponent(directory);
/** @type {?} */
let param = { Prefix: directory, Delimiter: '/', Bucket: self.config.storage.bucketName };
self.storage.listObjectsV2(param, (/**
* @param {?} err
* @param {?} data
* @return {?}
*/
(err, data) => {
if (err) {
reject(self.handleError(err, 'list'));
}
resolve(data);
}));
}
else {
self.storage.listObjectsV2((/**
* @param {?} err
* @param {?} data
* @return {?}
*/
(err, data) => {
if (err) {
reject(self.handleError(err, 'list'));
}
resolve(data);
}));
}
}));
}
/**
* @param {?} dataURI
* @param {?} type
* @return {?}
*/
static dataURItoBlob(dataURI, type) {
/** @type {?} */
let binary = atob(dataURI.split(',')[1]);
/** @type {?} */
let array = [];
for (let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
/** @type {?} */
let blob = new Blob([new Uint8Array(array)], { type: type });
return blob;
}
/**
* @private
* @param {?} error
* @param {?} caller
* @return {?}
*/
handleError(error, caller) {
/** @type {?} */
let exception = new CognitoException(error);
console.error(`NgxAmplifyStorageSevice::handleError calledBy::${caller}`, exception);
return exception;
}
}
StorageService.decorators = [
{ type: Injectable, args: [{
providedIn: 'root'
},] }
];
/** @nocollapse */
StorageService.ctorParameters = () => [
{ type: undefined, decorators: [{ type: Inject, args: [NGX_AMPLIFY_CONFIG,] }] },
{ type: AuthService }
];
/** @nocollapse */ StorageService.ngInjectableDef = ɵɵdefineInjectable({ factory: function StorageService_Factory() { return new StorageService(ɵɵinject(NGX_AMPLIFY_CONFIG), ɵɵinject(AuthService)); }, token: StorageService, providedIn: "root" });
if (false) {
/**
* @type {?}
* @private
*/
StorageService.prototype.config;
/**
* @type {?}
* @private
*/
StorageService.prototype.auth;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class TokenInterceptor {
/**
* @param {?} auth
*/
constructor(auth) {
this.auth = auth;
}
/**
* @param {?} req
* @param {?} next
* @return {?}
*/
intercept(req, next) {
/** @type {?} */
let token = this.auth.getJwtToken();
return this.addToken(req, next, token);
}
/**
* @private
* @param {?} req
* @param {?} next
* @param {?} token
* @return {?}
*/
addToken(req, next, token) {
/** @type {?} */
let alteredReq = req;
// HttpHeader object is immutable
/** @type {?} */
const header = {};
for (let key of req.headers.keys()) {
header[key] = req.headers.getAll(key);
}
if (token !== '') {
header["Authorization"] = `Bearer ${token}`;
}
header["Content-Type"] = "application/json";
/** @type {?} */
let alterdHeader = new HttpHeaders(header);
alteredReq = req.clone({
headers: alterdHeader
});
return next.handle(alteredReq);
}
}
TokenInterceptor.decorators = [
{ type: Injectable, args: [{
providedIn: 'root'
},] }
];
/** @nocollapse */
TokenInterceptor.ctorParameters = () => [
{ type: AuthService }
];
/** @nocollapse */ TokenInterceptor.ngInjectableDef = ɵɵdefineInjectable({ factory: function TokenInterceptor_Factory() { return new TokenInterceptor(ɵɵinject(AuthService)); }, token: TokenInterceptor, providedIn: "root" });
if (false) {
/**
* @type {?}
* @private
*/
TokenInterceptor.prototype.auth;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
export { AuthService, AuthUser, CognitoException, CognitoProfile, NGX_AMPLIFY_CON