barker/bookie/src/app/core/http-auth-interceptor.ts

43 lines
1.5 KiB
TypeScript
Raw Normal View History

import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError} from 'rxjs/operators';
import {ToasterService} from './toaster.service';
import {Router} from '@angular/router';
import {ConfirmDialogComponent} from '../shared/confirm-dialog/confirm-dialog.component';
import { MatDialog } from '@angular/material/dialog';
@Injectable()
export class HttpAuthInterceptor implements HttpInterceptor {
constructor(private router: Router, private dialog: MatDialog, private toaster: ToasterService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
return next.handle(req)
.pipe(
catchError((error: any) => {
if (error.status === 401) {
this.toaster.show('Danger', 'User has been logged out');
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px',
data: {
title: 'Logged out!',
content: 'You have been logged out.\nYou can press Cancel to stay on page and login in another tab to resume here, or you can press Ok to navigate to the login page.'
}
});
dialogRef.afterClosed().subscribe((result: boolean) => {
if (result) {
this.router.navigate(['login']);
}
});
}
return throwError(error);
}
)
);
}
}