Restore API token if expired

This commit is contained in:
2023-01-12 18:14:40 +01:00
parent ee2f371b21
commit b5b35dd44b
6 changed files with 41 additions and 14 deletions

View File

@@ -6,21 +6,45 @@ import {
HttpInterceptor
} from '@angular/common/http';
import { AuthService } from '../auth/auth.service';
import { Observable } from 'rxjs';
import { EMPTY, Observable } from 'rxjs';
import moment from 'moment';
import { catchError, mergeMap } from 'rxjs/operators';
import { NotificationsService } from '../services/notifications.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private auth$: AuthService
private auth$: AuthService,
private notifications$: NotificationsService
) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
if (!request.url.includes('/auth/apiToken')) {
return next.handle(request.clone({
headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`),
}));
if (this.auth$.expirationTime.isBefore(moment.utc())) {
return this.auth$.getAPITokenObservable().pipe(
mergeMap(() => {
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 {
return next.handle(request.clone({
headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`),
}));
}
} else {
return next.handle(request);
}
}
}