UNPKG

ngx-amplify

Version:

An angular library for integration AWS cloud services (cognito, s3)

2 lines 15.5 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(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")):"function"==typeof define&&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"],t):t((e=e||self)["ngx-amplify"]={},e.ng.core,e.ng.common,e.awsSdk,e.amazonCognitoIdentityJs,e.rxjs,e.S3,e.moment,e.ng.common.http)}(this,(function(e,t,n,r,o,i,s,a,u){"use strict";a=a&&a.hasOwnProperty("default")?a.default:a;function c(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{u(r.next(e))}catch(e){i(e)}}function a(e){try{u(r.throw(e))}catch(e){i(e)}}function u(e){e.done?o(e.value):new n((function(t){t(e.value)})).then(s,a)}u((r=r.apply(e,t||[])).next())}))}function l(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function f(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}var d=new t.InjectionToken("NgxAmplifyConfig"),g=function(){function e(){}return e.forRoot=function(t){return{ngModule:e,providers:[{provide:d,useValue:t}]}},e.decorators=[{type:t.NgModule,args:[{declarations:[],imports:[n.CommonModule],exports:[],providers:[]}]}],e}();var h=function(){function e(e){e?this.set(e):this.init()}return e.Factory=function(){return new e},e.prototype.init=function(){this.identityId="",this.authenticated=!1},e.prototype.set=function(e){void 0===e&&(e={}),Object.assign(this,e)},e}();var p=function(e){void 0===e&&(e={}),Object.assign(this,e)};var y=function(){function e(e){void 0===e&&(e={}),Object.assign(this,e)}return e.Factory=function(){return new e({sub:""})},e}();var v=function(){function e(e){this.config=e,this.resetting=!1,this.authState=new i.BehaviorSubject({state:"signedOut",user:null}),this.authState$=this.authState.asObservable(),this.authUserState=new i.BehaviorSubject({state:"signedOut",user:null}),this.authUserState$=this.authUserState.asObservable(),this.cognitoUserSub=new i.BehaviorSubject(this.cognitoUser),this.cognitoUser$=this.cognitoUserSub.asObservable(),r.config.region=this.config.region,r.config.credentials=new r.CognitoIdentityCredentials({IdentityPoolId:this.config.identityPoolId}),this.poolData={UserPoolId:e.userPoolId,ClientId:this.config.appId},this.userPool=new o.CognitoUserPool(this.poolData),this.user=h.Factory()}return e.prototype.authDetails=function(e){return new o.AuthenticationDetails({Username:e.username,Password:e.password})},e.prototype.buildCreds=function(){var e=this.buildLogins(this.session.getIdToken().getJwtToken());return new r.CognitoIdentityCredentials(e)},e.prototype.buildLogins=function(e){var t=this.config.idpUrl+"/"+this.config.userPoolId,n={IdentityPoolId:this.config.identityPoolId,Logins:{}};return n.Logins[t]=e,n},e.prototype.handleError=function(e,t){var n=new p(e);return console.error("AWS Cognito Service::handleError callerMethod::"+t,n),n},e.prototype.getCurrentUser=function(){return this.userPool.getCurrentUser()},e.prototype.getCognitoAttributes=function(e){var t=[];for(var n in e)if(!n.includes("password")&&!n.includes("confirmPassword")){var r=void 0;if(n.includes("username"))r=new o.CognitoUserAttribute({Name:"preferred_username",Value:e[n]});else if(n.endsWith("__c")){var i="custom:"+n.substring(0,n.length-3);r=new o.CognitoUserAttribute({Name:i,Value:e[n]})}else r=new o.CognitoUserAttribute({Name:n,Value:e[n]});t.push(r)}return t},e.prototype.getCognitoUser=function(e){return new o.CognitoUser({Username:e.username,Pool:this.userPool})},e.prototype.getJwtToken=function(){var e,t=this.getCurrentUser();return null!==t&&(e=t.getSignInUserSession().getAccessToken().getJwtToken()),e},e.prototype.getCognitoProfile=function(e){var t=y.Factory();return e.forEach((function(e){if(e.Name.startsWith("custom:")){var n=e.Name.substring(7);t[n+"__c"]=e.Value}else t[e.Name]=e.Value})),new y(t)},e.prototype.setCognitoProfile=function(e){var t=this;return new Promise((function(n,r){null===e?r(null):e.getUserData((function(e,o){e&&r(t.handleError(e,"setCognitoProfile"));var i=t.getCognitoProfile(o.UserAttributes);i.sub&&(t.user.identityId=i.sub),t.user.cognitoProfile=i,n(i)}))}))},e.prototype.updateCognitoProfile=function(e){var t=this,n=this;return new Promise((function(r,o){return c(t,void 0,void 0,(function(){var t=this;return l(this,(function(i){try{n.cognitoUser.updateAttributes(e,(function(e,i){return c(t,void 0,void 0,(function(){return l(this,(function(t){return e&&o(n.handleError(e,"updateAttributes")),n.setCognitoProfile(n.cognitoUser).then((function(e){r(e)})).catch((function(e){o(n.handleError(e,"setCognitoProfile"))})),[2]}))}))}))}catch(e){o(n.handleError(e,"try/catch updateCognitoProfile"))}return[2]}))}))}))},e.prototype.resetCreds=function(e){void 0===e&&(e=!1),this.resetting=!0,r.config.region=this.config.region,this.cognitoUser=null,this.cognitoUserSub.next(null),this.unauthCreds=this.unauthCreds||new r.CognitoIdentityCredentials({IdentityPoolId:this.config.identityPoolId}),e&&this.unauthCreds.clearCachedId(),this.setCredentials(this.unauthCreds),this.resetting=!1},e.prototype.currentAuthUser=function(){return c(this,void 0,void 0,(function(){var e,t;return l(this,(function(n){switch(n.label){case 0:return e=this,null===(t=this.userPool.getCurrentUser())?[3,2]:[4,this.refreshSession(t)];case 1:n.sent(),n.label=2;case 2:return[2,e.user]}}))}))},e.prototype.refreshOrResetCreds=function(){return c(this,void 0,void 0,(function(){return l(this,(function(e){switch(e.label){case 0:return this.cognitoUser=this.userPool.getCurrentUser(),null===this.cognitoUser?[3,3]:null!==this.cognitoUser.getSignInUserSession()?[3,2]:[4,this.refreshSession()];case 1:e.sent(),e.label=2;case 2:return[3,4];case 3:this.resetCreds(),e.label=4;case 4:return[2]}}))}))},e.prototype.refreshSession=function(e){var t=this,n=this;return void 0===e&&(e=this.userPool.getCurrentUser()),n.cognitoUser=e,n.session&&n.session.isValid?(n.cognitoUser.setSignInUserSession(n.session),new Promise((function(e){return c(t,void 0,void 0,(function(){return l(this,(function(t){switch(t.label){case 0:return[4,n.saveCreds(n.cognitoUser,n.session)];case 1:return t.sent(),e(n.session),[2]}}))}))}))):new Promise((function(e,r){return c(t,void 0,void 0,(function(){var t=this;return l(this,(function(o){return n.cognitoUser.getSession((function(o,i){return c(t,void 0,void 0,(function(){return l(this,(function(t){switch(t.label){case 0:return o&&(console.log("Error refreshing user session",o),r(o)),n.session=i,n.cognitoUser.setSignInUserSession(i),[4,n.saveCreds(n.cognitoUser,i)];case 1:return t.sent(),e(i),[2]}}))}))})),[2]}))}))}))},e.prototype.saveCreds=function(e,t){return c(this,void 0,void 0,(function(){var n;return l(this,(function(r){switch(r.label){case 0:return n=this,t&&(n.session=t,n.user.authenticated=t.isValid(),n.authState.next({state:"signedIn",user:e})),e?(n.cognitoUser=e,n.user.cognitoUser=e,n.authState.next({state:"signedIn",user:e}),n.cognitoUserSub.next(e),n.user.cognitoProfile=y.Factory(),[4,n.setCognitoProfile(e)]):[3,2];case 1:r.sent(),n.authUserState.next({state:"signedIn",user:n.user}),r.label=2;case 2:return n.setCredentials(n.buildCreds()),[2,n.user]}}))}))},e.prototype.setCredentials=function(e){r.config.credentials=e},e.prototype.signIn=function(e){var t=this,n=this,o=n.getCognitoUser(e);return new Promise((function(i,s){try{o.authenticateUser(n.authDetails(e),{onSuccess:function(e){return c(t,void 0,void 0,(function(){var t;return l(this,(function(r){switch(r.label){case 0:return[4,n.saveCreds(o,e)];case 1:return t=r.sent(),i(t),[2]}}))}))},onFailure:function(e){s(n.handleError(e,"signIn"))},newPasswordRequired:function(a,u){o.completeNewPasswordChallenge(e.password,u,{onSuccess:function(e){return c(t,void 0,void 0,(function(){var t;return l(this,(function(s){switch(s.label){case 0:return new r.CognitoIdentityCredentials(n.buildLogins(e.getIdToken().getJwtToken())),[4,n.saveCreds(o,e)];case 1:return t=s.sent(),i(t),[2]}}))}))},onFailure:function(e){s(n.handleError(e,"completeNewPasswordChallenge"))}})},mfaRequired:function(e,t){},customChallenge:function(e){}})}catch(e){s(e)}}))},e.prototype.signUp=function(e){var t=this;return new Promise((function(n,r){try{var o;return o=t.getCognitoAttributes(e),t.userPool.signUp(e.username,e.password,o,null,(function(e,o){e?r(t.handleError(e,"signUp")):n(o)}))}catch(e){r(t.handleError(e,"try/catch signUp"))}}))},e.prototype.confirmSignUp=function(e,t){var n=this,r=this,i={Username:e,Pool:r.userPool},s=new o.CognitoUser(i);return new Promise((function(e,o){try{s.confirmRegistration(t,!0,(function(t,n){t?o(r.handleError(t,"confirmRegistration")):e(n)}))}catch(e){o(n.handleError(e,"try/catch confirm signUp"))}}))},e.prototype.confirmPassword=function(e,t,n){var r=this,i={Username:e,Pool:this.userPool},s=new o.CognitoUser(i);return new Promise((function(e,o){try{s.confirmPassword(t,n,{onFailure:function(e){o(r.handleError(e,"confirmPassword"))},onSuccess:function(){e("Confirm Password SUCCESS")}})}catch(e){o(r.handleError(e,"try/catch confirmPassword"))}}))},e.prototype.forgotPassword=function(e){var t=this,n={Username:e,Pool:this.userPool},r=new o.CognitoUser(n);return new Promise((function(e,n){try{r.forgotPassword({onFailure:function(e){n(t.handleError(e,"forgotPassword"))},onSuccess:function(){e("Verification Code Sent")},inputVerificationCode:function(){e("Verification Code Sent")}})}catch(e){n(t.handleError(e,"try/catch forgotPassword"))}}))},e.prototype.resendConfirmationCode=function(e){var t=this,n={Username:e,Pool:this.userPool},r=new o.CognitoUser(n);return new Promise((function(e,n){try{r.resendConfirmationCode((function(r,o){r?n(t.handleError(r,"resendConfirmationCode")):e(o)}))}catch(e){n(t.handleError(e,"try/catch resendConfirmationCode"))}}))},e.prototype.signOut=function(){var e=this;if(e.cognitoUser){e.cognitoUser.getUsername();return new Promise((function(t,n){try{e.cognitoUser.signOut(),e.cognitoUserSub.next(null),e.authState.next({state:"signedOut",user:null}),e.resetCreds(!0),e.user=h.Factory(),e.authUserState.next({state:"signedOut",user:null}),t("signOut successful")}catch(t){n(e.handleError(t,"try/catch signOut"))}}))}},e.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}],e.ctorParameters=function(){return[{type:void 0,decorators:[{type:t.Inject,args:[d]}]}]},e.ngInjectableDef=t.ɵɵdefineInjectable({factory:function(){return new e(t.ɵɵinject(d))},token:e,providedIn:"root"}),e}();var m=function(){function e(e,t){if(this.config=e,this.auth=t,!e.storage)throw new TypeError("NgxAmplify:Storage options are not found. Please refer to the README for usage.")}return Object.defineProperty(e.prototype,"storage",{get:function(){return r.config.update({region:this.config.storage.bucketRegion}),new s({params:{Bucket:this.config.storage.bucketName},region:this.config.storage.bucketRegion})},enumerable:!0,configurable:!0}),e.prototype.isExpired=function(e){var t,n=new URL(e);if(""===n.search)t=!0;else{var r=n.searchParams.get("Expires");t=!!r&&a().isAfter(a.unix(parseInt(r)))}return t},e.prototype.getFileByUrl=function(e){var t=this,n="https://"+t.config.storage.bucketName+".s3.amazonaws.com/",r=e.replace(n,"");return new Promise((function(n,o){try{""===r?n(e):t.isExpired(e)?t.storage.getSignedUrl("getObject",{Key:r},(function(e,r){e?o(t.handleError(e,"getSignedUrl")):n(r)})):n(e)}catch(e){o(t.handleError(e,"try/catch getSignedUrl"))}}))},e.prototype.getFile=function(e,t){var n=this,r=n.config.storage.folderLevel+"/";t&&(r+=t+"/");var o=""+r+e;return new Promise((function(e,t){try{n.storage.getSignedUrl("getObject",{Key:o},(function(r,o){r?t(n.handleError(r,"getSignedUrl")):e(o)}))}catch(e){t(n.handleError(e,"try/catch getSignedUrl"))}}))},e.prototype.upload=function(e,t,n,r){var o=this,i="";i=r?r+"/":o.config.storage.defaultLevel+"/",n&&(i+=n+"/"),t=t.toLowerCase().replace(/\s+/g,"-"),"image/jpeg"===e.type&&(t+=".jpg"),"image/png"===e.type&&(t+=".png"),"image/tiff"===e.type&&(t+=".tiff");var s=""+i+t;return new Promise((function(t,n){try{o.storage.upload({Bucket:o.config.storage.bucketName,Key:s,ContentType:e.type,ContentEncoding:"base64",Body:e,StorageClass:"STANDARD"},(function(e,r){e?(o.handleError(e,"error during upload."),n(e)):(console.log("successful upload."),t(r))}))}catch(e){n(o.handleError(e,"try/catch upload"))}}))},e.prototype.list=function(e){var t=this;return new Promise((function(n,r){if(e){var o={Prefix:e,Delimiter:"/",Bucket:t.config.storage.bucketName};t.storage.listObjectsV2(o,(function(e,o){e&&r(t.handleError(e,"list")),n(o)}))}else t.storage.listObjectsV2((function(e,o){e&&r(t.handleError(e,"list")),n(o)}))}))},e.dataURItoBlob=function(e,t){for(var n=atob(e.split(",")[1]),r=[],o=0;o<n.length;o++)r.push(n.charCodeAt(o));return new Blob([new Uint8Array(r)],{type:t})},e.prototype.handleError=function(e,t){var n=new p(e);return console.error("NgxAmplifyStorageSevice::handleError calledBy::"+t,n),n},e.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}],e.ctorParameters=function(){return[{type:void 0,decorators:[{type:t.Inject,args:[d]}]},{type:v}]},e.ngInjectableDef=t.ɵɵdefineInjectable({factory:function(){return new e(t.ɵɵinject(d),t.ɵɵinject(v))},token:e,providedIn:"root"}),e}();var w=function(){function e(e){this.auth=e}return e.prototype.intercept=function(e,t){var n=this.auth.getJwtToken();return this.addToken(e,t,n)},e.prototype.addToken=function(e,t,n){var r,o,i,s={};try{for(var a=f(e.headers.keys()),c=a.next();!c.done;c=a.next()){var l=c.value;s[l]=e.headers.getAll(l)}}catch(e){r={error:e}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(r)throw r.error}}""!==n&&(s.Authorization="Bearer "+n),s["Content-Type"]="application/json";var d=new u.HttpHeaders(s);return i=e.clone({headers:d}),t.handle(i)},e.decorators=[{type:t.Injectable,args:[{providedIn:"root"}]}],e.ctorParameters=function(){return[{type:v}]},e.ngInjectableDef=t.ɵɵdefineInjectable({factory:function(){return new e(t.ɵɵinject(v))},token:e,providedIn:"root"}),e}();e.AuthService=v,e.AuthUser=h,e.CognitoException=p,e.CognitoProfile=y,e.NGX_AMPLIFY_CONFIG=d,e.NgxAmplifyModule=g,e.StorageService=m,e.TokenInterceptor=w,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=ngx-amplify.umd.min.js.map