adal-angular4
Version:
Angular 4+ ADAL Wrapper
291 lines (285 loc) • 11.3 kB
JavaScript
import { __decorate } from 'tslib';
import { NgZone, ɵɵdefineInjectable, ɵɵinject, Injectable } from '@angular/core';
import { bindCallback, timer } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
import { inject } from 'adal-angular';
let AdalService = class AdalService {
constructor(ngZone) {
this.ngZone = ngZone;
this.context = null;
this.loginRefreshTimer = null;
this.user = {
authenticated: false,
userName: '',
error: '',
token: '',
profile: {},
loginCached: false
};
}
init(configOptions) {
if (!configOptions) {
throw new Error('You must set config, when calling init.');
}
// redirect and logout_redirect are set to current location by default
const existingHash = window.location.hash;
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);
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();
}
}
get config() {
return this.context.config;
}
get userInfo() {
return this.user;
}
login() {
this.context.login();
}
loginInProgress() {
return this.context.loginInProgress();
}
logOut() {
this.context.logOut();
}
handleWindowCallback(removeHash = true) {
const hash = window.location.hash;
if (this.context.isCallback(hash)) {
let isPopup = false;
if (this.context._openedWindows.length > 0
&& this.context._openedWindows[this.context._openedWindows.length - 1].opener
&& this.context._openedWindows[this.context._openedWindows.length - 1].opener._adalInstance) {
this.context = this.context._openedWindows[this.context._openedWindows.length - 1].opener._adalInstance;
isPopup = true;
}
else if (window.parent && window.parent._adalInstance) {
this.context = window.parent._adalInstance;
}
const requestInfo = this.context.getRequestInfo(hash);
this.context.saveTokenFromHash(requestInfo);
const callback = this.context._callBackMappedToRenewStates[requestInfo.stateResponse] || this.context.callback;
if (requestInfo.requestType === this.context.REQUEST_TYPE.LOGIN) {
this.updateDataFromCache();
this.setupLoginTokenRefreshTimer();
}
if (requestInfo.stateMatch) {
if (typeof callback === 'function') {
if (requestInfo.requestType === this.context.REQUEST_TYPE.RENEW_TOKEN) {
// Idtoken or Accestoken can be renewed
if (requestInfo.parameters.access_token) {
callback(this.context._getItem(this.context.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters.access_token);
}
else if (requestInfo.parameters.id_token) {
callback(this.context._getItem(this.context.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters.id_token);
}
else if (requestInfo.parameters.error) {
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 = '';
}
}
}
}
getCachedToken(resource) {
return this.context.getCachedToken(resource);
}
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];
}));
}
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);
}
});
})();
}
clearCache() {
this.context.clearCache();
}
clearCacheForResource(resource) {
this.context.clearCacheForResource(resource);
}
info(message) {
this.context.info(message);
}
verbose(message) {
this.context.verbose(message);
}
getResourceForEndpoint(url) {
return this.context.getResourceForEndpoint(url);
}
refreshDataFromCache() {
this.updateDataFromCache();
}
updateDataFromCache() {
const token = this.context.getCachedToken(this.context.config.loginResource);
this.user.authenticated = token !== null && token.length > 0;
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;
}
}
refreshLoginToken() {
if (!this.user.loginCached) {
throw new Error('User not logged in');
}
this.acquireToken(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();
});
}
now() {
return Math.round(new Date().getTime() / 1000.0);
}
get isInCallbackRedirectMode() {
return window.location.href.indexOf('#access_token') !== -1 || window.location.href.indexOf('#id_token') !== -1;
}
setupLoginTokenRefreshTimer() {
// Get expiration of login token
const exp = this.context._getItem(this.context.CONSTANTS.STORAGE.EXPIRATION_KEY + this.context.config.loginResource);
// Either wait until the refresh window is valid or refresh in 1 second (measured in seconds)
const 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.ngZone.runOutsideAngular(() => {
this.loginRefreshTimer = timer(timerDelay * 1000).subscribe((x) => {
this.refreshLoginToken();
});
});
}
};
AdalService.ctorParameters = () => [
{ type: NgZone }
];
AdalService.ɵprov = ɵɵdefineInjectable({ factory: function AdalService_Factory() { return new AdalService(ɵɵinject(NgZone)); }, token: AdalService, providedIn: "root" });
AdalService = __decorate([
Injectable({
providedIn: 'root'
})
], AdalService);
let AdalGuard = class AdalGuard {
constructor(service) {
this.service = service;
}
canActivate(next, state) {
return this.service.userInfo.authenticated;
}
};
AdalGuard.ctorParameters = () => [
{ type: AdalService }
];
AdalGuard.ɵprov = ɵɵdefineInjectable({ factory: function AdalGuard_Factory() { return new AdalGuard(ɵɵinject(AdalService)); }, token: AdalGuard, providedIn: "root" });
AdalGuard = __decorate([
Injectable({
providedIn: 'root'
})
], AdalGuard);
let AdalInterceptor = class AdalInterceptor {
constructor(service) {
this.service = service;
}
intercept(request, next) {
// if the endpoint is not registered
// or if the header 'skip-adal' is set
// then pass the request as it is to the next handler
const resource = this.service.getResourceForEndpoint(request.url);
const skipAdal = request.headers.get('skip-adal');
if (!resource || skipAdal) {
return next.handle(request);
}
// if the user is not authenticated then drop the request
if (!this.service.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.service.acquireToken(resource)
.pipe(mergeMap((token) => {
// clone the request and replace the original headers with
// cloned headers, updated with the authorization
const authorizedRequest = request.clone({
headers: request.headers.set('Authorization', 'Bearer ' + token),
});
return next.handle(authorizedRequest);
}));
}
};
AdalInterceptor.ctorParameters = () => [
{ type: AdalService }
];
AdalInterceptor = __decorate([
Injectable()
], AdalInterceptor);
/**
* Generated bundle index. Do not edit.
*/
export { AdalGuard, AdalInterceptor, AdalService };
//# sourceMappingURL=adal-angular4.js.map