From ef4baeed881e8d4044652092314e583f8351a600 Mon Sep 17 00:00:00 2001 From: Alexis Lahouze Date: Tue, 1 Aug 2017 23:51:52 +0200 Subject: [PATCH] Add auth interceptor bootstrap. --- src/login/authInterceptor.ts | 49 ++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/login/authInterceptor.ts diff --git a/src/login/authInterceptor.ts b/src/login/authInterceptor.ts new file mode 100644 index 0000000..7dce326 --- /dev/null +++ b/src/login/authInterceptor.ts @@ -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, + next: HttpHandler + ): Observable> { + 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) => event, + (error) => { + if(error instanceof HttpErrorResponse && error.status === 401) { + this.logger.error('Unauthorized', error); + } + } + ); + } +}