keycloak-angular
Version:
Easy Keycloak setup for Angular applications
9 lines • 10.9 kB
JavaScript
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@angular/core"),require("@angular/common/http"),require("keycloak-js"),require("rxjs"),require("rxjs/operators"),require("@angular/common")):"function"==typeof define&&define.amd?define("keycloak-angular",["exports","@angular/core","@angular/common/http","keycloak-js","rxjs","rxjs/operators","@angular/common"],r):r(e["keycloak-angular"]={},e.ng.core,e.ng.common.http,e.Keycloak,e.rxjs,e.rxjs.operators,e.ng.common)}(this,function(e,r,s,t,n,o,i){"use strict";
/**
* @license
* Copyright Mauricio Gemelli Vigolo and contributors.
*
* Use of this source code is governed by a MIT-style license that can be
* found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/LICENSE
*/var u={OnAuthError:0,OnAuthLogout:1,OnAuthRefreshError:2,OnAuthRefreshSuccess:3,OnAuthSuccess:4,OnReady:5,OnTokenExpired:6};function a(r,s,u,c){return new(u||(u=Promise))(function(e,t){function n(e){try{i(c.next(e))}catch(r){t(r)}}function o(e){try{i(c["throw"](e))}catch(r){t(r)}}function i(r){r.done?e(r.value):new u(function(e){e(r.value)}).then(n,o)}i((c=c.apply(r,s||[])).next())})}function l(t,n){var o,i,s,e,u={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return e={next:r(0),"throw":r(1),"return":r(2)},"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function r(r){return function(e){return function(e){if(o)throw new TypeError("Generator is already executing.");for(;u;)try{if(o=1,i&&(s=2&e[0]?i["return"]:e[0]?i["throw"]||((s=i["return"])&&s.call(i),0):i.next)&&!(s=s.call(i,e[1])).done)return s;switch(i=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++,i=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=n.call(t,u)}catch(r){e=[6,r],i=0}finally{o=s=0}if(5&e[0])throw e[1];return{value:e[0]?e[1]:void 0,done:!0}}([r,e])}}}function c(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var n,o,i=t.call(e),s=[];try{for(;(void 0===r||0<r--)&&!(n=i.next()).done;)s.push(n.value)}catch(u){o={error:u}}finally{try{n&&!n.done&&(t=i["return"])&&t.call(i)}finally{if(o)throw o.error}}return s}u[u.OnAuthError]="OnAuthError",u[u.OnAuthLogout]="OnAuthLogout",u[u.OnAuthRefreshError]="OnAuthRefreshError",u[u.OnAuthRefreshSuccess]="OnAuthRefreshSuccess",u[u.OnAuthSuccess]="OnAuthSuccess",u[u.OnReady]="OnReady",u[u.OnTokenExpired]="OnTokenExpired";var f=function(){function e(e,r){this.router=e,this.keycloakAngular=r}return e.prototype.canActivate=function(u,c){var e=this;return new Promise(function(i,s){return a(e,void 0,void 0,function(){var r,t,n,o;return l(this,function(e){switch(e.label){case 0:return e.trys.push([0,4,,5]),[4,(r=this).keycloakAngular.isLoggedIn()];case 1:return r.authenticated=e.sent(),[4,(t=this).keycloakAngular.getUserRoles(!0)];case 2:return t.roles=e.sent(),[4,this.isAccessAllowed(u,c)];case 3:return n=e.sent(),i(n),[3,5];case 4:return o=e.sent(),s("An error happened during access validation. Details:"+o),[3,5];case 5:return[2]}})})})},e}(),h=t,d=function(){function e(){this._keycloakEvents$=new n.Subject}return e.prototype.sanitizeBearerPrefix=function(e){return(e||"bearer").trim().concat(" ")},e.prototype.ifUndefinedIsTrue=function(e){var r=e;return r!==undefined&&null!==r||(r=!0),r},e.prototype.bindsKeycloakEvents=function(){var r=this;this._instance?(this._instance.onAuthError=function(e){r._keycloakEvents$.next({args:e,type:u.OnAuthError})},this._instance.onAuthLogout=function(){r._keycloakEvents$.next({type:u.OnAuthLogout})},this._instance.onAuthRefreshError=function(){r._keycloakEvents$.next({type:u.OnAuthRefreshError})},this._instance.onAuthSuccess=function(){r._keycloakEvents$.next({type:u.OnAuthSuccess})},this._instance.onTokenExpired=function(){r._keycloakEvents$.next({type:u.OnTokenExpired})},this._instance.onReady=function(e){r._keycloakEvents$.next({args:e,type:u.OnReady})}):console.warn("Keycloak Angular events could not be registered as the keycloak instance is undefined.")},e.prototype.init=function(e){var n=this;return void 0===e&&(e={}),new Promise(function(t,r){n._enableBearerInterceptor=n.ifUndefinedIsTrue(e.enableBearerInterceptor),n._loadUserProfileAtStartUp=n.ifUndefinedIsTrue(e.loadUserProfileAtStartUp),n._bearerExcludedUrls=e.bearerExcludedUrls||[],n._authorizationHeaderName=e.authorizationHeaderName||"Authorization",n._bearerPrefix=n.sanitizeBearerPrefix(e.bearerPrefix),n._silentRefresh=!!e.initOptions&&"implicit"===e.initOptions.flow,n._instance=h(e.config),n.bindsKeycloakEvents(),n._instance.init(e.initOptions).success(function(r){return a(n,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return r&&this._loadUserProfileAtStartUp?[4,this.loadUserProfile()]:[3,2];case 1:e.sent(),e.label=2;case 2:return t(r),[2]}})})}).error(function(e){r("An error happened during Keycloak initialization.")})})},e.prototype.login=function(e){var n=this;return void 0===e&&(e={}),new Promise(function(r,t){n._instance.login(e).success(function(){return a(n,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return this._loadUserProfileAtStartUp?[4,this.loadUserProfile()]:[3,2];case 1:e.sent(),e.label=2;case 2:return r(),[2]}})})}).error(function(e){t("An error happened during the login.")})})},e.prototype.logout=function(n){var o=this;return new Promise(function(e,r){var t={redirectUri:n};o._instance.logout(t).success(function(){o._userProfile=undefined,e()}).error(function(e){r("An error happened during logout.")})})},e.prototype.register=function(t){var n=this;return void 0===t&&(t={action:"register"}),new Promise(function(e,r){n._instance.register(t).success(function(){e()}).error(function(){r("An error happened during the register execution")})})},e.prototype.isUserInRole=function(e){var r;return(r=this._instance.hasResourceRole(e))||(r=this._instance.hasRealmRole(e)),r},e.prototype.getUserRoles=function(e){void 0===e&&(e=!0);var r=[];if(this._instance.resourceAccess)for(var t in this._instance.resourceAccess)if(this._instance.resourceAccess.hasOwnProperty(t)){var n=this._instance.resourceAccess[t].roles||[];r=r.concat(n)}if(e&&this._instance.realmAccess){var o=this._instance.realmAccess.roles||[];r.push.apply(r,function(){for(var e=[],r=0;r<arguments.length;r++)e=e.concat(c(arguments[r]));return e}(o))}return r},e.prototype.isLoggedIn=function(){var t=this;return new Promise(function(r,e){return a(t,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.updateToken(20)];case 1:return e.sent(),r(!0),[3,3];case 2:return e.sent(),r(!1),[3,3];case 3:return[2]}})})})},e.prototype.isTokenExpired=function(e){return void 0===e&&(e=0),this._instance.isTokenExpired(e)},e.prototype.updateToken=function(n){var e=this;return void 0===n&&(n=5),new Promise(function(r,t){return a(e,void 0,void 0,function(){return l(this,function(e){return this._silentRefresh?this.isTokenExpired()?t("Failed to refresh the token, or the session is expired"):r(!0):this._instance?this._instance.updateToken(n).success(function(e){r(e)}).error(function(e){t("Failed to refresh the token, or the session is expired")}):t(),[2]})})})},e.prototype.loadUserProfile=function(o){var e=this;return void 0===o&&(o=!1),new Promise(function(t,n){return a(e,void 0,void 0,function(){var r=this;return l(this,function(e){switch(e.label){case 0:return this._userProfile&&!o?(t(this._userProfile),[2]):[4,this.isLoggedIn()];case 1:return e.sent()?this._instance.loadUserProfile().success(function(e){r._userProfile=e,t(r._userProfile)}).error(function(e){n("The user profile could not be loaded.")}):n("The user profile was not loaded as the user is not logged in."),[2]}})})})},e.prototype.getToken=function(){var t=this;return new Promise(function(r,e){return a(t,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.updateToken(10)];case 1:return e.sent(),r(this._instance.token),[3,3];case 2:return e.sent(),this.login(),[3,3];case 3:return[2]}})})})},e.prototype.getUsername=function(){if(!this._userProfile)throw new Error("User not logged in or user profile was not loaded.");return this._userProfile.username},e.prototype.clearToken=function(){this._instance.clearToken()},e.prototype.addTokenToHeader=function(i){var e=this;return n.Observable.create(function(o){return a(e,void 0,void 0,function(){var r,t,n;return l(this,function(e){switch(e.label){case 0:(r=i)||(r=new s.HttpHeaders),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.getToken()];case 2:return t=e.sent(),r=r.set(this._authorizationHeaderName,this._bearerPrefix+t),o.next(r),o.complete(),[3,4];case 3:return n=e.sent(),o.error(n),[3,4];case 4:return[2]}})})})},e.prototype.getKeycloakInstance=function(){return this._instance},Object.defineProperty(e.prototype,"bearerExcludedUrls",{get:function(){return this._bearerExcludedUrls},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"enableBearerInterceptor",{get:function(){return this._enableBearerInterceptor},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"keycloakEvents$",{get:function(){return this._keycloakEvents$},enumerable:!0,configurable:!0}),e.decorators=[{type:r.Injectable}],e.ctorParameters=function(){return[]},e}(),p=function(){function e(e){this.keycloak=e}return e.prototype.loadExcludedUrlsRegex=function(){var e=this.keycloak.bearerExcludedUrls;this.excludedUrlsRegex=e.map(function(e){return new RegExp(e,"i")})||[]},e.prototype.intercept=function(t,n){if(!this.keycloak||!this.keycloak.enableBearerInterceptor)return n.handle(t);this.excludedUrlsRegex||this.loadExcludedUrlsRegex();var r=t.url;return!!this.excludedUrlsRegex.find(function(e){return e.test(r)})?n.handle(t):this.keycloak.addTokenToHeader(t.headers).pipe(o.mergeMap(function(e){var r=t.clone({headers:e});return n.handle(r)}))},e.decorators=[{type:r.Injectable}],e.ctorParameters=function(){return[{type:d}]},e}(),y=function(){function e(){}return e.decorators=[{type:r.NgModule,args:[{imports:[i.CommonModule],providers:[d,{provide:s.HTTP_INTERCEPTORS,useClass:p,multi:!0}]}]}],e}(),k=function(){function e(){}return e.decorators=[{type:r.NgModule,args:[{imports:[y]}]}],e}();e.KeycloakEventType=u,e.KeycloakAuthGuard=f,e.KeycloakService=d,e.Keycloak=h,e.KeycloakBearerInterceptor=p,e.CoreModule=y,e.KeycloakAngularModule=k,Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=keycloak-angular.umd.min.js.map