UNPKG

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