Files
DiunaBI/Frontend/src/app/interceptors/auth.interceptor.ts

57 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-12-09 00:14:05 +01:00
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { AuthService } from '../auth/auth.service';
2023-01-12 18:14:40 +01:00
import { EMPTY, Observable } from 'rxjs';
import moment from 'moment';
import { catchError, mergeMap } from 'rxjs/operators';
import { NotificationsService } from '../services/notifications.service';
2022-12-09 00:14:05 +01:00
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
2023-01-12 18:14:40 +01:00
private auth$: AuthService,
private notifications$: NotificationsService
2022-12-09 00:14:05 +01:00
) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
2023-01-12 18:47:05 +01:00
console.log('Welcome to interceptor:', request.url);
console.log('IsAuth?', request.url.includes('/auth/apiToken'));
2022-12-09 00:14:05 +01:00
if (!request.url.includes('/auth/apiToken')) {
2023-01-12 18:47:05 +01:00
console.log(this.auth$.expirationTime.format(), moment.utc().format());
2023-01-12 18:14:40 +01:00
if (this.auth$.expirationTime.isBefore(moment.utc())) {
2023-01-12 18:47:05 +01:00
console.log('Need to refresh token');
2023-01-12 18:14:40 +01:00
return this.auth$.getAPITokenObservable().pipe(
mergeMap(() => {
2023-01-12 18:47:05 +01:00
console.log('New token is ready');
2023-01-12 18:14:40 +01:00
return next.handle(request.clone({
headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`),
}));
}),
catchError(() => {
this.notifications$.add({
text: "User session is expired and unable to restore. Please restart the app.",
btn: "Restart",
action: () => { window.location.reload(); },
duration: 5000,
});
return EMPTY;
})
);
} else {
2023-01-12 18:47:05 +01:00
console.log('TOken is fine');
2023-01-12 18:14:40 +01:00
return next.handle(request.clone({
headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`),
}));
}
2022-12-09 00:14:05 +01:00
} else {
return next.handle(request);
}
}
}
2023-01-12 18:14:40 +01:00