UNPKG

adal-angular6-wrapper

Version:

Angular 6 ADAL Wrapper. This version is a fork of follwing library for some personal implementation. No Support is available for this version. Original: https://github.com/benbaran/adal-angular4

388 lines (381 loc) 12.1 kB
import { bindCallback, timer } from 'rxjs'; import { inject } from 'adal-angular'; import { Injectable } from '@angular/core'; import { map, mergeMap } from 'rxjs/operators'; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ class AdalService { constructor() { this.context = /** @type {?} */ (null); this.loginRefreshTimer = /** @type {?} */ (null); this.user = { authenticated: false, userName: '', error: '', token: '', profile: {}, loginCached: false }; } /** * @param {?} configOptions * @return {?} */ init(configOptions) { if (!configOptions) { throw new Error('You must set config, when calling init.'); } /** @type {?} */ const existingHash = window.location.hash; /** @type {?} */ let pathDefault = window.location.href; if (existingHash) { pathDefault = pathDefault.replace(existingHash, ''); } configOptions.redirectUri = configOptions.redirectUri || pathDefault; configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault; // create instance with given config this.context = inject(configOptions); window.AuthenticationContext = this.context.constructor; // loginresource is used to set authenticated status this.updateDataFromCache(); if (this.user.loginCached && !this.user.authenticated && window.self == window.top && !this.isInCallbackRedirectMode) { this.refreshLoginToken(); } else if (this.user.loginCached && this.user.authenticated && !this.loginRefreshTimer && window.self == window.top) { this.setupLoginTokenRefreshTimer(); } } /** * @return {?} */ get config() { return this.context.config; } /** * @return {?} */ get userInfo() { return this.user; } /** * @return {?} */ login() { this.context.login(); } /** * @return {?} */ loginInProgress() { return this.context.loginInProgress(); } /** * @return {?} */ logOut() { this.context.logOut(); } /** * @param {?=} removeHash * @return {?} */ handleWindowCallback(removeHash = true) { /** @type {?} */ const hash = window.location.hash; if (this.context.isCallback(hash)) { /** @type {?} */ const requestInfo = this.context.getRequestInfo(hash); this.context.saveTokenFromHash(requestInfo); if (requestInfo.requestType === this.context.REQUEST_TYPE.LOGIN) { this.updateDataFromCache(); this.setupLoginTokenRefreshTimer(); } else if (requestInfo.requestType === this.context.REQUEST_TYPE.RENEW_TOKEN) { this.context.callback = window.parent.callBackMappedToRenewStates[requestInfo.stateResponse]; } if (requestInfo.stateMatch) { if (typeof this.context.callback === 'function') { if (requestInfo.requestType === this.context.REQUEST_TYPE.RENEW_TOKEN) { // Idtoken or Accestoken can be renewed if (requestInfo.parameters['access_token']) { this.context.callback(this.context._getItem(this.context.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['access_token']); } else if (requestInfo.parameters['id_token']) { this.context.callback(this.context._getItem(this.context.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['id_token']); } else if (requestInfo.parameters['error']) { this.context.callback(this.context._getItem(this.context.CONSTANTS.STORAGE.ERROR_DESCRIPTION), null); this.context._renewFailed = true; } } } } } // Remove hash from url if (removeHash) { if (window.location.hash) { if (window.history.replaceState) { window.history.replaceState('', '/', window.location.pathname); } else { window.location.hash = ''; } } } } /** * @param {?} resource * @return {?} */ getCachedToken(resource) { return this.context.getCachedToken(resource); } /** * @param {?} resource * @return {?} */ acquireToken(resource) { return bindCallback((callback) => { this.context.acquireToken(resource, (error, tokenOut) => { if (error) { this.context.error('Error when acquiring token for resource: ' + resource, error); callback(null, error); } else { callback(tokenOut, null); } }); })() .pipe(map((result) => { if (!result[0] && result[1]) { throw (result[1]); } return result[0]; })); } /** * @return {?} */ getUser() { return bindCallback((callback) => { this.context.getUser((error, user) => { if (error) { this.context.error('Error when getting user', error); callback(null); } else { callback(user || null); } }); })(); } /** * @return {?} */ clearCache() { this.context.clearCache(); } /** * @param {?} resource * @return {?} */ clearCacheForResource(resource) { this.context.clearCacheForResource(resource); } /** * @param {?} message * @return {?} */ info(message) { this.context.info(message); } /** * @param {?} message * @return {?} */ verbose(message) { this.context.verbose(message); } /** * @param {?} url * @return {?} */ getResourceForEndpoint(url) { return this.context.getResourceForEndpoint(url); } /** * @return {?} */ refreshDataFromCache() { this.updateDataFromCache(); } /** * @return {?} */ updateDataFromCache() { /** @type {?} */ const token = this.context.getCachedToken(/** @type {?} */ (this.context.config.loginResource)); this.user.authenticated = token !== null && token.length > 0; /** @type {?} */ const user = this.context.getCachedUser(); if (user) { this.user.userName = user.userName; this.user.profile = user.profile; this.user.token = token; this.user.error = this.context.getLoginError(); this.user.loginCached = true; } else { this.user.userName = ''; this.user.profile = {}; this.user.token = ''; this.user.error = this.context.getLoginError(); this.user.loginCached = false; } } /** * @return {?} */ refreshLoginToken() { if (!this.user.loginCached) throw ("User not logged in"); this.acquireToken(/** @type {?} */ (this.context.config.loginResource)).subscribe((token) => { this.user.token = token; if (this.user.authenticated == false) { this.user.authenticated = true; this.user.error = ''; window.location.reload(); } else { this.setupLoginTokenRefreshTimer(); } }, (error) => { this.user.authenticated = false; this.user.error = this.context.getLoginError(); }); } /** * @return {?} */ now() { return Math.round(new Date().getTime() / 1000.0); } /** * @return {?} */ get isInCallbackRedirectMode() { return window.location.href.indexOf("#access_token") !== -1 || window.location.href.indexOf("#id_token") !== -1; } ; /** * @return {?} */ setupLoginTokenRefreshTimer() { /** @type {?} */ let exp = this.context._getItem(this.context.CONSTANTS.STORAGE.EXPIRATION_KEY + /** @type {?} */ (this.context.config.loginResource)); /** @type {?} */ let timerDelay = exp - this.now() - (this.context.config.expireOffsetSeconds || 300) > 0 ? exp - this.now() - (this.context.config.expireOffsetSeconds || 300) : 1; if (this.loginRefreshTimer) this.loginRefreshTimer.unsubscribe(); this.loginRefreshTimer = timer(timerDelay * 1000).subscribe((x) => { this.refreshLoginToken(); }); } } AdalService.decorators = [ { type: Injectable } ]; /** @nocollapse */ AdalService.ctorParameters = () => []; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ class AdalGuard { /** * @param {?} adalService */ constructor(adalService) { this.adalService = adalService; } /** * @param {?} route * @param {?} state * @return {?} */ canActivate(route, state) { return this.adalService.userInfo.authenticated; } /** * @param {?} childRoute * @param {?} state * @return {?} */ canActivateChild(childRoute, state) { return this.canActivate(childRoute, state); } } AdalGuard.decorators = [ { type: Injectable } ]; /** @nocollapse */ AdalGuard.ctorParameters = () => [ { type: AdalService } ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ class AdalInterceptor { /** * @param {?} adal */ constructor(adal) { this.adal = adal; } /** * @param {?} request * @param {?} next * @return {?} */ intercept(request, next) { /** @type {?} */ const resource = this.adal.getResourceForEndpoint(request.url); if (!resource) { return next.handle(request); } // if the user is not authenticated then drop the request if (!this.adal.userInfo.authenticated) { throw new Error('Cannot send request to registered endpoint if the user is not authenticated.'); } // if the endpoint is registered then acquire and inject token return this.adal.acquireToken(resource) .pipe(mergeMap((token) => { /** @type {?} */ const authorizedRequest = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token), }); return next.handle(authorizedRequest); })); } } AdalInterceptor.decorators = [ { type: Injectable } ]; /** @nocollapse */ AdalInterceptor.ctorParameters = () => [ { type: AdalService } ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ export { AdalService, AdalGuard, AdalInterceptor }; //# sourceMappingURL=adal-angular6-wrapper.js.map