Spaces:
Running
Running
File size: 1,071 Bytes
a828e09 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { AuthService } from './auth.service';
import { catchError } from 'rxjs/operators';
import { AuthUiService } from './auth-ui.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private auth: AuthService,
private authUi: AuthUiService
) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.auth.getAccessToken();
let authReq = req;
if (token && !req.headers.has('Authorization')) {
authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
}
return next.handle(authReq).pipe(
catchError((err: HttpErrorResponse) => {
if (err.status === 401) {
this.auth.logout();
this.authUi.openSignin();
}
return throwError(() => err);
})
);
}
}
|