blob: 8dd26e44f7bf06129a57020f3fcb2288acd4a3e7 [file] [log] [blame]
/*
*******************************************************************************
* Copyright (c) 2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************
*/
import { SessionContext } from './../common/session-context';
import { ToasterMessageService, MessageDefines } from './toaster-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 toasterMessageService: ToasterMessageService,
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.toasterMessageService.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);
}
);
}
}