Add auth interceptor bootstrap.

This commit is contained in:
Alexis Lahouze 2017-08-01 23:51:52 +02:00
parent e2a4b0b7ec
commit ef4baeed88

View File

@ -0,0 +1,49 @@
// vim: set tw=80 ts=2 sw=2 sts=2 :
import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from '@angular/common/http';
import { Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Logger } from '@nsalaun/ng-logger';
import { LoginService } from './login.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private logger: Logger,
private loginService: LoginService,
) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
this.logger.log('Intercepted request', req, next);
if(!req.headers.has('Authorization')) {
let accessToken: string = this.loginService.accessToken();
if(accessToken){
req = req.clone({
headers: req.headers.set('Authorization', `Bearer ${accessToken}`)
});
}
}
this.logger.log('Request', req);
return next.handle(req).map(
(event: HttpEvent<any>) => event,
(error) => {
if(error instanceof HttpErrorResponse && error.status === 401) {
this.logger.error('Unauthorized', error);
}
}
);
}
}