blob: 7d3d0d3487343c5fea6a71925387001efb29836a [file] [log] [blame]
/*
******************************************************************************
* Copyright © 2018 PTA GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************
*/
import { SessionContext } from './../common/session-context';
import { AuthenticationService } from './authentication.service';
import { MessageServiceCustom, MessageDefines } from './message.service';
import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpErrorResponse,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
constructor(private msgService: MessageServiceCustom,
private authService: AuthenticationService,
private router: Router,
private sessionContext: SessionContext) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(request)
.do((ev: HttpEvent<any>) => {
// could do something with the resonse
/* if (ev instanceof HttpResponse) {
console.log('Response:', ev);
} */
}).catch(error => {
if (error instanceof HttpErrorResponse) {
// this.sessionContext.centralHttpResultCode$.emit(error.status);
if (error.status === 401) {
// redirect to the login route
// or show a modal
if (this.sessionContext.isUserAuthenticated()) {
this.msgService.loginLogoff$.emit(MessageDefines.MSG_LOG_OFF);
this.router.navigate(['/loggedout']);
}
} else if (error.status !== 302 && (error.status < 200 || error.status >= 300)) {
throw new Error('Bad response status: ' + error.status);
}
}
return Observable.throw(error);
}
);
}
}