UNPKG

14.3 kBJavaScriptView Raw
1!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/core"),require("class-transformer"),require("@angular/router"),require("@ubud/storage"),require("rxjs"),require("rxjs/operators"),require("@angular/common/http"),require("@angular/common"),require("rxjs-compat/observable/fromPromise"),require("@nguniversal/express-engine/tokens"),require("rxjs/internal/operators")):"function"==typeof define&&define.amd?define("@naker/naco",["exports","@angular/core","class-transformer","@angular/router","@ubud/storage","rxjs","rxjs/operators","@angular/common/http","@angular/common","rxjs-compat/observable/fromPromise","@nguniversal/express-engine/tokens","rxjs/internal/operators"],t):t((e.naker=e.naker||{},e.naker.naco={}),e.ng.core,null,e.ng.router,null,e.rxjs,e.rxjs.operators,e.ng.common.http,e.ng.common,null,null,e.rxjs["internal/operators"])}(this,function(e,r,o,n,i,s,a,u,p,t,f,c){"use strict";var l=function(e,t){return(l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function g(r,o){var i,s,a,e,c={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return e={next:t(0),"throw":t(1),"return":t(2)},"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(n){return function(e){return function t(e){if(i)throw new TypeError("Generator is already executing.");for(;c;)try{if(i=1,s&&(a=2&e[0]?s["return"]:e[0]?s["throw"]||((a=s["return"])&&a.call(s),0):s.next)&&!(a=a.call(s,e[1])).done)return a;switch(s=0,a&&(e=[2&e[0],a.value]),e[0]){case 0:case 1:a=e;break;case 4:return c.label++,{value:e[1],done:!1};case 5:c.label++,s=e[1],e=[0];continue;case 7:e=c.ops.pop(),c.trys.pop();continue;default:if(!(a=0<(a=c.trys).length&&a[a.length-1])&&(6===e[0]||2===e[0])){c=0;continue}if(3===e[0]&&(!a||e[1]>a[0]&&e[1]<a[3])){c.label=e[1];break}if(6===e[0]&&c.label<a[1]){c.label=a[1],a=e;break}if(a&&c.label<a[2]){c.label=a[2],c.ops.push(e);break}a[2]&&c.ops.pop(),c.trys.pop();continue}e=o.call(r,c)}catch(t){e=[6,t],s=0}finally{i=a=0}if(5&e[0])throw e[1];return{value:e[0]?e[1]:void 0,done:!0}}([n,e])}}}var h=function d(e){this.endpoint="https://account.kemnaker.go.id",this.scopes="basic email",this.responseType="token",Object.assign(this,e)},y=function(){function e(){}return function t(e,t,n,r){var o,i=arguments.length,s=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;0<=a;a--)(o=e[a])&&(s=(i<3?o(s):3<i?o(t,n,s):o(t,n))||s);return 3<i&&s&&Object.defineProperty(t,n,s),s}([o.Type(r.forwardRef(function(){return Date})),function n(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}("design:type",Date)],e.prototype,"updatedAt",void 0),e}(),m=function(){function e(e,t,n,r,o){this.config=e,this.router=t,this.storage=n,this.http=r,this.location=o,this.VERSION="v1",this.signature=null,this.user=null,this.refreshToken=null,this.clientSecret=null,this.config.clientSecret&&this.setClientSecret(this.config.clientSecret)}return e.prototype.setUser=function(e){this.user=e},e.prototype.getUser=function(){var n=this;if(null!==this.user)return s.of(this.user);var r=this.getUri("/users/me");return s.from(this.getSignature()).pipe(a.switchMap(function(t){if(!t)return n.refreshUser(n.config.scopes);var e={headers:{Authorization:t.type+" "+t.token}};return n.http.get(r,e).pipe(a.map(function(e){if(e.data)return e.data;throw new Error("There are no body to be transformed")}),a.map(function(e){var t=o.plainToClass(y,e);return n.setUser(t),t}),a.catchError(function(e){return 401===e.status?n.refreshUser(t.scopes):s.of(null)}))}))},e.prototype.getProfilePicture=function(e){return this.config.endpoint+"/users/"+e+"/picture"},e.prototype.getSignature=function(){return this.signature?Promise.resolve(this.signature):this.storage.get("signature")},e.prototype.setSignature=function(e){this.signature=e,this.storage.set("signature",e)},e.prototype.setClientSecret=function(e){this.clientSecret=e},e.prototype.setRefreshToken=function(e){this.refreshToken=e,this.storage.set("refresh_token",e)},e.prototype.refreshUser=function(r){var o=this;return this.setUser(null),this.setSignature(null),s.forkJoin(this.getRefreshToken(),this.getClientSecret()).pipe(a.switchMap(function(e){var t=e[0],n=e[1];return t&&n?o.refreshWithRefreshToken(n,t.token,r):o.refreshWithSilentAuth(r)}))},e.prototype.refreshWithRefreshToken=function(e,t,n){var r=this;return this.http.post(this.getUri("/tokens"),{grant_type:"refresh_token",scopes:n||this.config.scopes,client_id:this.config.clientId,client_secret:e,refresh_token:t}).pipe(a.tap(function(e){e&&e.data&&(r.setSignature({expiresIn:e.data.expires_in||e.data.expiresIn,type:e.data.token_type||e.data.tokenType,token:e.data.access_token||e.data.accessToken,scopes:decodeURIComponent(e.data.scopes||r.config.scopes)}),r.setRefreshToken({type:e.data.token_type||e.data.tokenType,token:e.data.refresh_token||e.data.refreshToken}))}),a.map(function(e){return e&&e.data}),a.switchMap(function(e){return e?r.getUser():s.of(null)}))},e.prototype.refreshWithSilentAuth=function(n){var r=this;return new s.Observable(function(h){var e=r.getCurrentOrigin("auth/silent"),t=r.login(n||r.config.scopes,e,!0,"token",!1),d=document.createElement("iframe");d.setAttribute("src",t),d.style.display="none",d.addEventListener("load",function(){return function e(t,a,c,u){return new(c||(c=Promise))(function(e,n){function r(e){try{i(u.next(e))}catch(t){n(t)}}function o(e){try{i(u["throw"](e))}catch(t){n(t)}}function i(t){t.done?e(t.value):new c(function(e){e(t.value)}).then(r,o)}i((u=u.apply(t,a||[])).next())})}(r,void 0,void 0,function(){var r,o,i,s,a,c,u,p,f,l;return g(this,function(e){switch(e.label){case 0:if(e.trys.push([0,5,,6]),i=d.contentWindow.location.search.substring(1),d.parentNode.removeChild(d),!i)return[3,4];s=i.split("&"),a={};try{for(c=function t(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}}}}(s),u=c.next();!u.done;u=c.next())p=u.value,f=p.split("="),a[f[0]]=f[1]}catch(n){r={error:n}}finally{try{u&&!u.done&&(o=c["return"])&&o.call(c)}finally{if(r)throw r.error}}return a.hasOwnProperty("access_token")?(this.setSignature({token:a.access_token,type:a.token_type,expiresIn:a.expires_in,scopes:decodeURIComponent(a.scopes||this.config.scopes)}),[4,this.getUser().toPromise()]):[3,2];case 1:return(l=e.sent())&&this.setUser(l),h.next(l),[3,3];case 2:h.next(null),e.label=3;case 3:return[2];case 4:return h.next(null),[3,6];case 5:return e.sent(),h.next(null),[3,6];case 6:return[2]}})})},!1),document.body.appendChild(d)})},e.prototype.getAccessTokenFromAuthCode=function(n,r,o){var i=this;return t.fromPromise(this.getState()).pipe(a.switchMap(function(e){var t={code:n,grant_type:"authorization_code",scopes:o||i.config.scopes,client_id:i.config.clientId,client_secret:i.config.clientSecret,redirect_uri:r};return e&&(t.state=e),i.http.post(i.getUri("/tokens"),t)}),a.map(function(e){if(e.data)return e.data;throw new Error("There are no body to be transformed")}))},e.prototype.login=function(e,t,n,r,o){void 0===n&&(n=!1),void 0===r&&(r="token"),void 0===o&&(o=!0),t||(t=this.router.url);var i={response_type:r,scopes:e,client:this.config.clientId,silent:n,"continue":encodeURIComponent(t)};if(o){var s=this.generateState();this.storage.set("state",s),i.state=s}var a=this.buildQueryString(i);return this.config.endpoint+"/auth?"+a},e.prototype.logout=function(n){var r=this;return this.signature=null,this.user=null,this.refreshToken=null,new Promise(function(t){var e=[r.storage.remove("signature"),r.storage.remove("user"),r.storage.remove("refresh_token")];Promise.all(e).then(function(){var e=r.config.endpoint+"/auth/logout";n&&(e+="?continue="+encodeURIComponent(n)),t(e)})})},e.prototype.getState=function(){return this.storage.get("state")},e.prototype.buildNestedUri=function(e){var t=this,n="";if(e.routeConfig&&e.routeConfig.path){var r=e.routeConfig.path;for(var o in e.params)if(o){var i=new RegExp(":"+o);r=r.replace(i,e.params[o])}n+="/"+r}return e.children&&e.children.forEach(function(e){n+=t.buildNestedUri(e)}),n},e.prototype.getRefreshToken=function(){return null!==this.refreshToken?Promise.resolve(this.refreshToken):this.storage.get("refresh_token")},e.prototype.getClientSecret=function(){return null!==this.clientSecret?Promise.resolve(this.clientSecret):this.storage.get("client_secret")},e.prototype.getUri=function(e){return this.config.endpoint+"/api/"+this.VERSION+e},e.prototype.getCurrentOrigin=function(e){return window.location.origin+this.location.prepareExternalUrl(e||"")},e.prototype.generateState=function(){for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="",n=0;n<5;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return t},e.prototype.buildQueryString=function(t){return Object.keys(t).map(function(e){return encodeURIComponent(e)+"="+encodeURIComponent(t[e])}).join("&")},e.prototype.goToAccountEndpoint=function(e,t){var n=this,r=this.getCurrentOrigin("/"+this.buildNestedUri(e.root).replace(/^\/+/,""));this.storage.set("naco_intended_url",r).then(function(){n.redirect(n.login(n.config.scopes,n.getCurrentOrigin("/auth"),!1,t||n.config.responseType,!0))})},e.prototype.goToIntendedUrl=function(){var t=this;this.storage.get("naco_intended_url").then(function(e){t.storage.remove("naco_intended_url"),t.redirect(e||"/")})},e.prototype.redirect=function(e){window.location.href=e},e.decorators=[{type:r.Injectable}],e.ctorParameters=function(){return[{type:h},{type:n.Router},{type:i.Storage},{type:u.HttpClient},{type:p.Location}]},e}(),v=function(c){function e(e,t,n,r,o,i,s){var a=c.call(this,e,t,n,r,o)||this;return a.request=i,a.response=s,a}return function t(e,t){function n(){this.constructor=e}l(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}(e,c),e.prototype.refreshWithSilentAuth=function(){return s.of(null)},e.prototype.getCurrentOrigin=function(e){return void 0===e&&(e=""),this.request.protocol+"://"+this.request.headers.host+this.location.prepareExternalUrl(e||"")},e.prototype.redirect=function(e){this.response.redirect(302,e),this.response.end()},e.decorators=[{type:r.Injectable}],e.ctorParameters=function(){return[{type:h},{type:n.Router},{type:i.Storage},{type:u.HttpClient},{type:p.Location},{type:undefined,decorators:[{type:r.Inject,args:[f.REQUEST]}]},{type:undefined,decorators:[{type:r.Inject,args:[f.RESPONSE]}]}]},e}(m),k=function b(){},_=function(){function e(e,t,n){this.naco=e,this.storage=t,this.location=n}return e.prototype.canActivate=function(t){var n=this;return this.naco.getUser().pipe(c.first(),c.map(function(e){return null===e&&n.naco.goToAccountEndpoint(t.root),!!e}))},e.prototype.canActivateChild=function(e){return this.canActivate(e)},e.decorators=[{type:r.Injectable}],e.ctorParameters=function(){return[{type:m},{type:i.Storage},{type:p.Location}]},e}(),w=function(){function e(e){this.naco=e}return e.prototype.intercept=function(t,n){var r=this,o=!0;return s.from(this.naco.getSignature()).pipe(a.switchMap(function(e){return e?n.handle(t.clone({setHeaders:{Authorization:e.type+" "+e.token}})):(o=!1,n.handle(t))}),a.retryWhen(function(e){return e.pipe(a.switchMap(function(t){return 401===t.status&&o?(o=!1,r.naco.refreshUser().pipe(a.switchMap(function(e){return e?s.throwError(t):s.of(null)}))):s.throwError(t)}))}))},e.decorators=[{type:r.Injectable}],e.ctorParameters=function(){return[{type:m}]},e}(),S=function(){function e(e,t,n,r){this.route=e,this.naco=t,this.storage=n,this.location=r,this.message$=s.concat(s.of("Authenticating..."),this.handle())}return e.prototype.handle=function(){var n=this;return s.from(this.naco.getState()).pipe(a.switchMap(function(t){return n.route.queryParams.pipe(a.switchMap(function(e){return t&&e.state!==t?s.throwError("Invalid CSRF Token"):s.of(e)}))}),a.switchMap(function(e){return n.naco.setUser(null),e.access_token?(n.naco.setSignature({expiresIn:e.expires_in,type:e.token_type,token:e.access_token,scopes:decodeURIComponent(e.scopes)}),n.naco.getUser()):e.code?n.naco.getAccessTokenFromAuthCode(e.code,n.naco.getCurrentOrigin("/auth")).pipe(a.tap(function(e){n.naco.setSignature({expiresIn:e.expires_in||e.expiresIn,type:e.token_type||e.tokenType,token:e.access_token||e.accessToken,scopes:decodeURIComponent(e.scopes)}),n.naco.setRefreshToken({expiresIn:e.expires_in||e.expiresIn,type:e.token_type||e.tokenType,token:e.refresh_token||e.refreshToken,scopes:decodeURIComponent(e.scopes)})}),a.switchMap(function(){return n.naco.getUser()})):s.of(null)}),a.switchMap(function(e){return null===e?s.throwError(new Error("Unauthenticated!")):(n.naco.goToIntendedUrl(),s.of("Success, please wait for redirecting..."))}),a.catchError(function(e){return s.of(e.message)}))},e.decorators=[{type:r.Component,args:[{selector:"naker-auth-page",template:"{{ message$ | async }}"}]}],e.ctorParameters=function(){return[{type:n.ActivatedRoute},{type:m},{type:i.Storage},{type:p.Location}]},e}(),x=function(){function e(e){this.naco=e}return e.prototype.ngOnInit=function(){var e=this,t=setTimeout(function(){clearTimeout(t),e.naco.redirect("/")},2e3)},e.decorators=[{type:r.Component,args:[{selector:"naker-auth-silent",template:"Please wait..."}]}],e.ctorParameters=function(){return[{type:m}]},e}(),C=[{path:"auth",component:S},{path:"auth/silent",component:x}],T=n.RouterModule.forChild(C),U=function(){function e(){}return e.decorators=[{type:r.NgModule,args:[{imports:[p.CommonModule,T],declarations:[S,x]}]}],e}(),I=new r.InjectionToken("NACO_ROOT_CONFIG");function R(e){return new h(e)}var j=function(){function t(){}return t.forRoot=function(e){return{ngModule:t,providers:[{provide:I,useValue:e},{provide:h,useFactory:R,deps:[I]},m,_]}},t.decorators=[{type:r.NgModule,args:[{imports:[U]}]}],t}();e.NacoService=m,e.NacoExpressService=v,e.User=y,e.Signature=k,e.Config=h,e.AuthenticatedGuard=_,e.AuthInterceptor=w,e.nacoConfigFactory=R,e.NacoModule=j,e.ɵa=U,e.ɵd=x,e.ɵc=S,e.ɵb=T,Object.defineProperty(e,"__esModule",{value:!0})});
2//# sourceMappingURL=naker-naco.umd.min.js.map
\No newline at end of file