Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 1x 1x 1x 1x 1x 1x | import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable, Injector } from "@angular/core";
import { environment } from "@environment";
import { ToastrService } from "ngx-toastr";
import { catchError, Observable, of, switchMap, throwError } from "rxjs";
import { LoginService } from "../login.service";
@Injectable({
providedIn: "root",
})
export class AuthInterceptor implements HttpInterceptor {
constructor (private readonly injector: Injector, private readonly toaster: ToastrService) {
}
intercept<T> (req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> {
Iif(!req.url.startsWith(environment.apiUrl) || !environment.msal)
return next.handle(req);
const loginService = this.injector.get(LoginService);
Iif(!loginService.isLoggedIn()) {
return of();
}
const account = loginService.getAccount();
if (account) {
// Get the access token for the API
return loginService.getToken().pipe(
catchError(error => {
console.error("Token acquisition failed:", error);
return next.handle(req);
}),
switchMap(token => {
const clonedRequest = req.clone({
setHeaders: {
"Auth-Method": loginService.getProvider(),
Authorization: `Bearer ${token}`,
},
});
return next.handle(clonedRequest);
}),
catchError(error => {
Iif(error.status !== 404) {
console.error("Request failed: ", error);
this.toaster.error("Request failed: " + error.message);
}
return throwError(() => error);
})
);
} else {
return next.handle(req); // Proceed without the token if no account is found
}
}
}
|