Skip to content

Commit

Permalink
implements interceptor for all requests
Browse files Browse the repository at this point in the history
  • Loading branch information
thalesbarbosab committed Jun 10, 2021
1 parent 81c0ff6 commit 5708b9e
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/app/account/shared/account.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,8 @@ export class AccountService {
const result = await this.http.post<any>(`${environment.api}/api/users`,account,{headers: http_headers}).toPromise();
return result;
}
getAuthorizationToken(){
const token = window.localStorage.getItem('token');
return token;
}
}
5 changes: 4 additions & 1 deletion src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { LoginComponent } from './account/login/login.component';
import { CreateAccountComponent } from './account/create-account/create-account.component';
import { HomeComponent } from './layout/home/home.component';
import { AuthenticationComponent } from './layout/authentication/authentication.component';
import { httpInterceptorProviders } from './http-interceptors';

@NgModule({
declarations: [
Expand All @@ -30,7 +31,9 @@ import { AuthenticationComponent } from './layout/authentication/authentication.
FormsModule,
AppRoutingModule
],
providers: [],
providers: [
httpInterceptorProviders
],
bootstrap: [AppComponent]
})
export class AppModule { }
49 changes: 49 additions & 0 deletions src/app/http-interceptors/auth-interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Injectable } from '@angular/core';
import { AccountService } from './../account/shared/account.service';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

constructor(
private accountService: AccountService
) { }

intercept(req: HttpRequest<any>, next: HttpHandler) {

const token = this.accountService.getAuthorizationToken();
let request: HttpRequest<any> = req;

//if (token && !this.accountService.isTokenExpired(token)) {
if (token) {
// O request é imutavel, ou seja, não é possível mudar nada
// Faço o clone para conseguir mudar as propriedades
// Passo o token de autenticação no header
request = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
}

// retorno o request com o erro tratado
return next.handle(request)
.pipe(
catchError(this.handleError)
);
}

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// Erro de client-side ou de rede
console.error('Ocorreu um erro:', error.error.message);
} else {
// Erro retornando pelo backend
console.error(
`Código do erro ${error.status}, ` +
`Erro: ${JSON.stringify(error.error)}`);
}
// retornar um observable com uma mensagem amigavel.
return throwError('Ocorreu um erro, tente novamente');
}
}
6 changes: 6 additions & 0 deletions src/app/http-interceptors/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth-interceptor';

export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
];

0 comments on commit 5708b9e

Please sign in to comment.