From c7f8cdf623211ec0ab8e67a4d7ea91805004fcc6 Mon Sep 17 00:00:00 2001 From: Eugene Pankov Date: Mon, 26 Jul 2021 21:54:28 +0200 Subject: [PATCH] . --- frontend/src/app.module.ts | 9 +++------ frontend/src/interceptor.ts | 20 +++++++++++++++++++- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/frontend/src/app.module.ts b/frontend/src/app.module.ts index b78299c..34fe7f0 100644 --- a/frontend/src/app.module.ts +++ b/frontend/src/app.module.ts @@ -9,7 +9,7 @@ import { HttpClientModule, HttpClientXsrfModule, HTTP_INTERCEPTORS } from '@angu import { ClipboardModule } from '@angular/cdk/clipboard' import { TransferHttpCacheModule } from '@nguniversal/common' import { FontAwesomeModule } from '@fortawesome/angular-fontawesome' -import { UniversalInterceptor } from './interceptor' +import { BackendXsrfInterceptor, UniversalInterceptor } from './interceptor' import { AppComponent } from './components/app.component' import { MainComponent } from './components/main.component' import { ConfigModalComponent } from './components/configModal.component' @@ -62,11 +62,8 @@ const ROUTES = [ RouterModule.forRoot(ROUTES), ], providers: [ - { - provide: HTTP_INTERCEPTORS, - useClass: UniversalInterceptor, - multi: true, - }, + { provide: HTTP_INTERCEPTORS, useClass: UniversalInterceptor, multi: true }, + { provide: HTTP_INTERCEPTORS, useClass: BackendXsrfInterceptor, multi: true }, ], declarations: [ AppComponent, diff --git a/frontend/src/interceptor.ts b/frontend/src/interceptor.ts index d6814f8..2d3e4cb 100644 --- a/frontend/src/interceptor.ts +++ b/frontend/src/interceptor.ts @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core' -import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http' +import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpXsrfTokenExtractor } from '@angular/common/http' import { Observable } from 'rxjs' import { CommonService } from './services/common.service' @@ -18,3 +18,21 @@ export class UniversalInterceptor implements HttpInterceptor { return next.handle(request) } } + +@Injectable() +export class BackendXsrfInterceptor implements HttpInterceptor { + constructor ( + private commonService: CommonService, + private tokenExtractor: HttpXsrfTokenExtractor, + ) { } + + intercept (req: HttpRequest, next: HttpHandler): Observable> { + if (this.commonService.backendURL && req.url.startsWith(this.commonService.backendURL)) { + let token = this.tokenExtractor.getToken() as string; + if (token !== null) { + req = req.clone({ setHeaders: { 'X-XSRF-TOKEN': token } }); + } + } + return next.handle(req); + } +}