Refactor tutorial service for public access and enhance authentication handling
This commit is contained in:
@@ -1,33 +1,57 @@
|
||||
import { HTTP_INTERCEPTORS, HttpEvent } from '@angular/common/http';
|
||||
import {HTTP_INTERCEPTORS, HttpErrorResponse, HttpEvent} from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
|
||||
|
||||
import { TokenStorageService } from '../services/token-storage.service';
|
||||
import { Observable } from 'rxjs';
|
||||
import {catchError, Observable, throwError} from 'rxjs';
|
||||
import {EventBusService} from '../_shared/event-bus.service';
|
||||
import {EventData} from '../_shared/event.class';
|
||||
import {environment} from '../../environments/environment';
|
||||
|
||||
const TOKEN_HEADER_KEY = 'Authorization'; // for Spring Boot back-end
|
||||
|
||||
@Injectable()
|
||||
export class AuthInterceptor implements HttpInterceptor {
|
||||
constructor(private token: TokenStorageService) { }
|
||||
private isRefreshing = false;
|
||||
enviorment = environment;
|
||||
|
||||
constructor(private tokenStorageService: TokenStorageService, private eventBusService: EventBusService) { }
|
||||
|
||||
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
||||
|
||||
|
||||
req = req.clone({
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
return next.handle(req);
|
||||
return next.handle(req).pipe(
|
||||
catchError((error) => {
|
||||
if (
|
||||
error instanceof HttpErrorResponse &&
|
||||
!req.url.includes('auth/signin') &&
|
||||
(error.status === 401
|
||||
|| error.status === 500
|
||||
|| error.status === 0
|
||||
|
||||
) /// must be only 401 without 500 and 0
|
||||
) {
|
||||
return this.handle401Error(req, next);
|
||||
}
|
||||
|
||||
/*let authReq = req;
|
||||
const token = this.token.getToken();
|
||||
if (token != null) {
|
||||
authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) });
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
|
||||
if (!this.isRefreshing) {
|
||||
this.isRefreshing = true;
|
||||
|
||||
if (this.tokenStorageService.isLoggedIn()) {
|
||||
this.eventBusService.emit(new EventData('logout', null));
|
||||
}
|
||||
}
|
||||
return next.handle(authReq);*/
|
||||
|
||||
return next.handle(request);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user