keycloak-angular
Version:
Easy Keycloak setup for Angular applications
16 lines (14 loc) • 12.3 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/core"),require("@angular/common/http"),require("rxjs"),require("keycloak-js"),require("rxjs/operators"),require("@angular/common")):"function"==typeof define&&define.amd?define("keycloak-angular",["exports","@angular/core","@angular/common/http","rxjs","keycloak-js","rxjs/operators","@angular/common"],t):t((e=e||self)["keycloak-angular"]={},e.ng.core,e.ng.common.http,e.rxjs,e.Keycloak,e.rxjs.operators,e.ng.common)}(this,(function(e,t,r,n,o,i,s){"use strict";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */function u(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{a(n.next(e))}catch(e){i(e)}}function u(e){try{a(n.throw(e))}catch(e){i(e)}}function a(e){e.done?o(e.value):new r((function(t){t(e.value)})).then(s,u)}a((n=n.apply(e,t||[])).next())}))}function a(e,t){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=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++,n=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],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}}function c(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}}}}function l(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}var h={OnAuthError:0,OnAuthLogout:1,OnAuthRefreshError:2,OnAuthRefreshSuccess:3,OnAuthSuccess:4,OnReady:5,OnTokenExpired:6};h[h.OnAuthError]="OnAuthError",h[h.OnAuthLogout]="OnAuthLogout",h[h.OnAuthRefreshError]="OnAuthRefreshError",h[h.OnAuthRefreshSuccess]="OnAuthRefreshSuccess",h[h.OnAuthSuccess]="OnAuthSuccess",h[h.OnReady]="OnReady",h[h.OnTokenExpired]="OnTokenExpired";var f=function(){function e(e,t){this.router=e,this.keycloakAngular=t}return e.prototype.canActivate=function(e,t){var r=this;return new Promise((function(n,o){return u(r,void 0,void 0,(function(){var r,i,s,u;return a(this,(function(a){switch(a.label){case 0:return a.trys.push([0,4,,5]),r=this,[4,this.keycloakAngular.isLoggedIn()];case 1:return r.authenticated=a.sent(),i=this,[4,this.keycloakAngular.getUserRoles(!0)];case 2:return i.roles=a.sent(),[4,this.isAccessAllowed(e,t)];case 3:return s=a.sent(),n(s),[3,5];case 4:return u=a.sent(),o("An error happened during access validation. Details:"+u),[3,5];case 5:return[2]}}))}))}))},e}();var d=o,p=function(){function e(){this._keycloakEvents$=new n.Subject}return e.prototype.bindsKeycloakEvents=function(){var e=this;this._instance.onAuthError=function(t){e._keycloakEvents$.next({args:t,type:h.OnAuthError})},this._instance.onAuthLogout=function(){e._keycloakEvents$.next({type:h.OnAuthLogout})},this._instance.onAuthRefreshSuccess=function(){e._keycloakEvents$.next({type:h.OnAuthRefreshSuccess})},this._instance.onAuthRefreshError=function(){e._keycloakEvents$.next({type:h.OnAuthRefreshError})},this._instance.onAuthSuccess=function(){e._keycloakEvents$.next({type:h.OnAuthSuccess})},this._instance.onTokenExpired=function(){e._keycloakEvents$.next({type:h.OnTokenExpired})},this._instance.onReady=function(t){e._keycloakEvents$.next({args:t,type:h.OnReady})}},e.prototype.loadExcludedUrls=function(e){var t,r,n=[];try{for(var o=c(e),i=o.next();!i.done;i=o.next()){var s=i.value,u=void 0;u="string"==typeof s?{urlPattern:new RegExp(s,"i"),httpMethods:[]}:{urlPattern:new RegExp(s.url,"i"),httpMethods:s.httpMethods},n.push(u)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return n},e.prototype.initServiceValues=function(e){var t=e.enableBearerInterceptor,r=void 0===t||t,n=e.loadUserProfileAtStartUp,o=void 0===n||n,i=e.bearerExcludedUrls,s=void 0===i?[]:i,u=e.authorizationHeaderName,a=void 0===u?"Authorization":u,c=e.bearerPrefix,l=void 0===c?"bearer":c,h=e.initOptions;this._enableBearerInterceptor=r,this._loadUserProfileAtStartUp=o,this._authorizationHeaderName=a,this._bearerPrefix=l.trim().concat(" "),this._excludedUrls=this.loadExcludedUrls(s),this._silentRefresh=!!h&&"implicit"===h.flow},e.prototype.init=function(e){var t=this;return void 0===e&&(e={}),new Promise((function(r,n){t.initServiceValues(e);var o=e.config,i=e.initOptions;t._instance=d(o),t.bindsKeycloakEvents(),t._instance.init(i).success((function(e){return u(t,void 0,void 0,(function(){return a(this,(function(t){switch(t.label){case 0:return e&&this._loadUserProfileAtStartUp?[4,this.loadUserProfile()]:[3,2];case 1:t.sent(),t.label=2;case 2:return r(e),[2]}}))}))})).error((function(e){var t="An error happened during Keycloak initialization.";if(e){var r=e.error,o=e.error_description;t=t.concat("\nAdapter error details:\nError: "+r+"\nDescription: "+o)}n(t)}))}))},e.prototype.login=function(e){var t=this;return void 0===e&&(e={}),new Promise((function(r,n){t._instance.login(e).success((function(){return u(t,void 0,void 0,(function(){return a(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(){return n("An error happened during the login.")}))}))},e.prototype.logout=function(e){var t=this;return new Promise((function(r,n){var o={redirectUri:e};t._instance.logout(o).success((function(){t._userProfile=void 0,r()})).error((function(){return n("An error happened during logout.")}))}))},e.prototype.register=function(e){var t=this;return void 0===e&&(e={action:"register"}),new Promise((function(r,n){t._instance.register(e).success((function(){r()})).error((function(){return n("An error happened during the register execution.")}))}))},e.prototype.isUserInRole=function(e,t){var r;return(r=this._instance.hasResourceRole(e,t))||(r=this._instance.hasRealmRole(e)),r},e.prototype.getUserRoles=function(e){void 0===e&&(e=!0);var t=[];if(this._instance.resourceAccess)for(var r in this._instance.resourceAccess)if(this._instance.resourceAccess.hasOwnProperty(r)){var n=this._instance.resourceAccess[r].roles||[];t=t.concat(n)}if(e&&this._instance.realmAccess){var o=this._instance.realmAccess.roles||[];t.push.apply(t,function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(l(arguments[t]));return e}(o))}return t},e.prototype.isLoggedIn=function(){return u(this,void 0,void 0,(function(){return a(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),this._instance.authenticated?[4,this.updateToken(20)]:[2,!1];case 1:return e.sent(),[2,!0];case 2:return e.sent(),[2,!1];case 3:return[2]}}))}))},e.prototype.isTokenExpired=function(e){return void 0===e&&(e=0),this._instance.isTokenExpired(e)},e.prototype.updateToken=function(e){var t=this;return void 0===e&&(e=5),new Promise((function(r,n){return u(t,void 0,void 0,(function(){return a(this,(function(t){return this._silentRefresh?(this.isTokenExpired()?n("Failed to refresh the token, or the session is expired"):r(!0),[2]):this._instance?(this._instance.updateToken(e).success((function(e){r(e)})).error((function(){return n("Failed to refresh the token, or the session is expired")})),[2]):(n("Keycloak Angular library is not initialized."),[2])}))}))}))},e.prototype.loadUserProfile=function(e){var t=this;return void 0===e&&(e=!1),new Promise((function(r,n){return u(t,void 0,void 0,(function(){var t=this;return a(this,(function(o){return this._userProfile&&!e?(r(this._userProfile),[2]):this._instance.authenticated?(this._instance.loadUserProfile().success((function(e){t._userProfile=e,r(t._userProfile)})).error((function(){return n("The user profile could not be loaded.")})),[2]):(n("The user profile was not loaded as the user is not logged in."),[2])}))}))}))},e.prototype.getToken=function(){var e=this;return new Promise((function(t,r){return u(e,void 0,void 0,(function(){return a(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.updateToken(10)];case 1:return e.sent(),t(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(e){var t=this;return void 0===e&&(e=new r.HttpHeaders),n.Observable.create((function(r){return u(t,void 0,void 0,(function(){var t,n;return a(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this.getToken()];case 1:return t=o.sent(),e=e.set(this._authorizationHeaderName,this._bearerPrefix+t),r.next(e),r.complete(),[3,3];case 2:return n=o.sent(),r.error(n),[3,3];case 3:return[2]}}))}))}))},e.prototype.getKeycloakInstance=function(){return this._instance},Object.defineProperty(e.prototype,"excludedUrls",{get:function(){return this._excludedUrls},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:t.Injectable}],e}();var y=function(){function e(e){this.keycloak=e}return e.prototype.isUrlExcluded=function(e,t){var r=e.method,n=e.url,o=t.urlPattern,i=t.httpMethods,s=0===i.length||i.join().indexOf(r.toUpperCase())>-1,u=o.test(n);return s&&u},e.prototype.intercept=function(e,t){var r=this,o=this.keycloak,s=o.enableBearerInterceptor,u=o.excludedUrls;return s?u.findIndex((function(t){return r.isUrlExcluded(e,t)}))>-1?t.handle(e):n.from(this.keycloak.isLoggedIn()).pipe(i.mergeMap((function(n){return n?r.handleRequestWithTokenHeader(e,t):t.handle(e)}))):t.handle(e)},e.prototype.handleRequestWithTokenHeader=function(e,t){return this.keycloak.addTokenToHeader(e.headers).pipe(i.mergeMap((function(r){var n=e.clone({headers:r});return t.handle(n)})))},e.decorators=[{type:t.Injectable}],e.ctorParameters=function(){return[{type:p}]},e}();var v=function(){function e(){}return e.decorators=[{type:t.NgModule,args:[{imports:[s.CommonModule],providers:[p,{provide:r.HTTP_INTERCEPTORS,useClass:y,multi:!0}]}]}],e}(),k=function(){function e(){}return e.decorators=[{type:t.NgModule,args:[{imports:[v]}]}],e}();e.CoreModule=v,e.KeycloakAngularModule=k,e.KeycloakAuthGuard=f,e.KeycloakBearerInterceptor=y,e.KeycloakEventType=h,e.KeycloakService=p,Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=keycloak-angular.umd.min.js.map