Add auth interceptor bootstrap.
This commit is contained in:
parent
e2a4b0b7ec
commit
ef4baeed88
49
src/login/authInterceptor.ts
Normal file
49
src/login/authInterceptor.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user