From d592e0a9b2931c7c9cbedb27fb8efc9aaacad9bb Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 14 Sep 2017 11:57:49 +0200 Subject: Move to HttpClient and PrimeNG data table --- .../app/shared/auth/auth-interceptor.service.ts | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 client/src/app/shared/auth/auth-interceptor.service.ts (limited to 'client/src/app/shared/auth/auth-interceptor.service.ts') diff --git a/client/src/app/shared/auth/auth-interceptor.service.ts b/client/src/app/shared/auth/auth-interceptor.service.ts new file mode 100644 index 000000000..1e890d8f3 --- /dev/null +++ b/client/src/app/shared/auth/auth-interceptor.service.ts @@ -0,0 +1,62 @@ +import { Injectable, Injector } from '@angular/core' +import { + HttpInterceptor, + HttpRequest, + HttpEvent, + HttpHandler, HTTP_INTERCEPTORS +} from '@angular/common/http' +import { Observable } from 'rxjs/Observable' + +import { AuthService } from '../../core' +import 'rxjs/add/operator/switchMap' + +@Injectable() +export class AuthInterceptor implements HttpInterceptor { + private authService: AuthService + + // https://github.com/angular/angular/issues/18224#issuecomment-316957213 + constructor (private injector: Injector) {} + + intercept (req: HttpRequest, next: HttpHandler): Observable> { + if (this.authService === undefined) { + this.authService = this.injector.get(AuthService) + } + + const authReq = this.cloneRequestWithAuth(req) + + // Pass on the cloned request instead of the original request + // Catch 401 errors (refresh token expired) + return next.handle(authReq) + .catch(err => { + if (err.status === 401) { + return this.handleTokenExpired(req, next) + } + + return Observable.throw(err) + }) + } + + private handleTokenExpired (req: HttpRequest, next: HttpHandler): Observable> { + return this.authService.refreshAccessToken() + .switchMap(() => { + const authReq = this.cloneRequestWithAuth(req) + + return next.handle(authReq) + }) + } + + private cloneRequestWithAuth (req: HttpRequest) { + const authHeaderValue = this.authService.getRequestHeaderValue() + + if (authHeaderValue === null) return req + + // Clone the request to add the new header + return req.clone({ headers: req.headers.set('Authorization', authHeaderValue) }) + } +} + +export const AUTH_INTERCEPTOR_PROVIDER = { + provide: HTTP_INTERCEPTORS, + useClass: AuthInterceptor, + multi: true +} -- cgit v1.2.3