Untitled
unknown
plain_text
3 years ago
3.5 kB
7
Indexable
import { CustomErrorHandler } from '@utils/custom-error-handler';
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { Router } from '@angular/router';
import { LoginService } from '@services/login.service';
import { ToastrService } from 'ngx-toastr';
import { AsgardeoAuthService } from '@asgardeo/auth-angular';
@Injectable()
export class AppInterceptor implements HttpInterceptor {
// Se a rota não precisa ser autenticada, adicionar esse header
static readonly NO_AUTH = { 'No-Auth': 'True' };
constructor(public auth: LoginService, private router: Router, private Toastr: ToastrService, private asgardeoAuthService: AsgardeoAuthService) {
}
// Caso a API de erro chama essa função
showError(response: HttpErrorResponse): Observable<any> {
const isAcessoNegado = response.status === 401 || response.status === 403;
if (isAcessoNegado) {
this.auth.logout();
this.Toastr.error('Sua chave de acesso está expirada, por favor faça Login novamente.');
}
return throwError(response);
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authenticatedHttpCall = request.headers.get('No-Auth') !== 'True';
// Se a chamada necessita de autenticação, os headers do gateway são adicionados
if (authenticatedHttpCall) {
const defaultHeaders = {
'Accept': '*/*'
};
debugger;
var accessToken = this.asgardeoAuthService.getAccessToken().toPromise()
if(accessToken!=null) {
defaultHeaders['Authorization'] = 'Bearer ' + accessToken;
}
if (localStorage.idEmpresaLogada !== null && localStorage.idEmpresaLogada !== undefined) {
defaultHeaders['api-company-id'] = localStorage.idEmpresaLogada
}
if (request.headers.get('Content-Type') !== 'application/json') {
if (request.body?.constructor?.name !== 'FormData') {
defaultHeaders['Content-type'] = 'application/x-www-form-urlencoded, multipart/form-data';
}
}
const headers = Object.entries(defaultHeaders)
.reduce((headers, [key, value]) => {
if (headers.has(key)) {
return headers.append(key, value);
}
return headers.set(key, value);
}, request.headers);
request = request.clone({
setHeaders: headers.keys().reduce((acc, key) => {
acc[key] = headers.getAll(key);
return acc;
}, {})
});
}
return next.handle(request).pipe(
map((response: HttpResponse<any>) => {
//debugger;
// Qualquer requisição via API que é chamada vai passar por essa Arrow function (resposta da API)
if (response.headers?.get('www-authenticate')) {
response.headers.delete('www-authenticate');
}
if (response.status > 399) {
throw response;
}
// Para interceptar qualquer API basta criar uma lógica dentro desta camada, e caso seja necessário utilizar o RESPONSE
return response;
}),
catchError(error => {
CustomErrorHandler.handleError(error);
return this.showError(error);
}));
}
}
Editor is loading...