UNPKG

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