automatically checks if isAuthenticated(): - if !isAuthenticated() (token expired), route to login and delete token from sessionStorage;
41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
|
|
import {Injectable} from '@angular/core';
|
|
import {Observable} from 'rxjs';
|
|
import {NGXLogger} from 'ngx-logger';
|
|
import {AuthService} from './auth.service';
|
|
import {Router} from '@angular/router';
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
/**
|
|
* The InterceptorService intercepts EVERY http event.
|
|
*/
|
|
export class InterceptorService implements HttpInterceptor {
|
|
|
|
constructor(private logger: NGXLogger,
|
|
private authService: AuthService,
|
|
private router: Router
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* Intercepts every HTTP request.
|
|
* If the token is invalid (expired) the user is redirected to logout (always).
|
|
* @param req http request
|
|
* @param next http response handler
|
|
*/
|
|
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
|
// FOR TESTING ONLY - sets an expired token
|
|
// sessionStorage.setItem('loginToken', 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTk4ODYzNTF9.e83okQ1NHjeO-AxaB3SQP9P5UjOYy-e5DFissDdf2Mo');
|
|
|
|
const authenticated = this.authService.isAuthenticated();
|
|
this.logger.debug('isAuthenticated?', authenticated);
|
|
if (!this.authService.isAuthenticated()) {
|
|
this.logger.debug('token invalid, route to login');
|
|
this.router.navigate(['login']).then(() => {});
|
|
}
|
|
return next.handle(req);
|
|
}
|
|
}
|