rajah преди 11 месеца
родител
ревизия
ec691e762f
променени са 4 файла, в които са добавени 51 реда и са изтрити 22 реда
  1. 2 2
      src/app/app.config.ts
  2. 21 13
      src/app/composants/login/login.component.ts
  3. 6 0
      src/app/services/account.service.ts
  4. 22 7
      src/app/services/auth.interceptor.ts

+ 2 - 2
src/app/app.config.ts

@@ -3,7 +3,7 @@ import { provideRouter } from '@angular/router';
 import { routes } from './app.routes';
 import { provideClientHydration } from '@angular/platform-browser';
 import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
-import { provideHttpClient, withInterceptorsFromDi, HTTP_INTERCEPTORS } from '@angular/common/http';
+import { provideHttpClient, withInterceptorsFromDi, HTTP_INTERCEPTORS, withXsrfConfiguration } from '@angular/common/http';
 
 import { AuthInterceptor } from './services/auth.interceptor';
 
@@ -14,7 +14,7 @@ export const appConfig: ApplicationConfig =
     provideRouter(routes),
     provideClientHydration(),
     provideAnimationsAsync(),
-    provideHttpClient(withInterceptorsFromDi()),
+    provideHttpClient(withInterceptorsFromDi(), withXsrfConfiguration({ cookieName: "XSRF-TOKEN", headerName: "X-XSRF-TOKEN" })),
     {
       provide: HTTP_INTERCEPTORS,
       useClass: AuthInterceptor,

+ 21 - 13
src/app/composants/login/login.component.ts

@@ -1,33 +1,41 @@
 import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
-import { Router } from '@angular/router';  
+import { Router } from '@angular/router';
+import { FormsModule, NgForm, NgModel } from '@angular/forms';
+
 import { MenuComponent } from '../menu/menu.component';
-import { User } from '../../interfaces/user';  
-import { AccountService } from '../../services/account.service' 
-import { FormsModule, NgForm, NgModel } from '@angular/forms'; 
+import { AccountService } from '../../services/account.service'
+import { User } from '../../interfaces/user';
+import { Journees } from '../../interfaces/divers';
 
 @Component({ selector: 'app-login', imports: [FormsModule, MenuComponent], templateUrl: './login.component.html', styleUrl: './login.component.css' })
 
 export class LoginComponent implements OnInit, AfterViewInit
 {
 
+  hello: Journees = new Journees();
+
   @ViewChild('formRef') loginForm!: NgForm;
   @ViewChild('userRef') userField!: NgModel; @ViewChild('userid', {static: false}) userFieldf!: ElementRef;
   @ViewChild('passRef') passField!: NgModel;
 
   identifiants: User = new User();
- 
+
   constructor(private router : Router, private accountService : AccountService) { }
-  
-  ngOnInit() { } 
-  
+
+  ngOnInit()
+  {
+    this.hello = new Journees();
+    this.accountService.salute().subscribe(data => { this.hello = data; });
+  }
+
   ngAfterViewInit() { }
 
   connexion()
-  {  
-    if (this.loginForm.valid) 
+  {
+    if (this.loginForm.valid)
     {
-      this.accountService.signIn(this.identifiants).subscribe(data => { this.identifiants = data; if (this.identifiants.username === "") { this.userFieldf.nativeElement.focus(); } else if (this.identifiants.password === "<success@auth>") { this.router.navigate(['/']); } }); 
+      this.accountService.signIn(this.identifiants).subscribe(data => { this.identifiants = data; if (this.identifiants.username === "") { this.userFieldf.nativeElement.focus(); } else if (this.identifiants.password === "<success@auth>") { this.router.navigate(['/']); } });
     }
-  } 
-  
+  }
+
 }

+ 6 - 0
src/app/services/account.service.ts

@@ -3,9 +3,11 @@ import { Router } from '@angular/router';
 import { HttpClient } from '@angular/common/http';
 import { BehaviorSubject, Observable } from 'rxjs';
 import { map } from 'rxjs/operators';
+
 import { Environnement } from '../env';
 import { User, RefreshToken } from '../interfaces/user';
 import { Participant } from '../interfaces/participant';
+import { Journees } from '../interfaces/divers';
 
 @Injectable({ providedIn: 'root' })
 
@@ -34,6 +36,10 @@ export class AccountService
   public getAccessToken() { if (this.userSubject.value) { return this.userSubject.value.accessToken; } return ""; }
   private getRefreshToken() { if (this.userSubject.value) { return this.userSubject.value.refreshToken; } return ""; }
 
+  salute(): Observable<Journees>
+  {
+    return this.httpClient.get<Journees>(`${this.baseURLsig}/hello`);
+  }
   signIn(usr: User): Observable<User>
   {
     return this.httpClient.post<User>(`${this.baseURLsig}/in`, usr).pipe(map(u => { sessionStorage.setItem('user', JSON.stringify(u)); this.userSubject.next(u); return u; }));

+ 22 - 7
src/app/services/auth.interceptor.ts

@@ -1,8 +1,9 @@
 import { catchError, switchMap } from 'rxjs/operators';
 import { throwError } from "rxjs";
 import { Injectable } from '@angular/core';
-import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse } from '@angular/common/http';
+import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse, HttpHeaders, HttpXsrfTokenExtractor } from '@angular/common/http';
 import { Observable } from 'rxjs';
+
 import { AccountService } from './account.service';
 
 @Injectable()
@@ -14,13 +15,11 @@ export class AuthInterceptor implements HttpInterceptor
 
   private isRefreshing = false;
 
-  constructor(private accountService: AccountService) { }
+  constructor(private csrfTokenExtrator: HttpXsrfTokenExtractor, private accountService: AccountService) { }
 
   intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>
   {
-    const authToken = this.accountService.getAccessToken();
-
-    const modified = request.clone({ headers: request.headers.append('Authorization', "Bearer " + authToken) });
+    const modified = request.clone({ headers: this.addExtraHeaders(request.headers, (request.method == "POST" || request.method == "PUT" || request.method == "DELETE")) });
 
     return next.handle(modified).pipe(
       catchError((error) => { if (error instanceof HttpErrorResponse && !request.url.includes('/sign/in') && error.status === 403) { return this.handle401Error(request, next); } return throwError(() => error); })
@@ -38,8 +37,7 @@ export class AuthInterceptor implements HttpInterceptor
         return this.accountService.updateToken().pipe(
           switchMap(() => {
             this.isRefreshing = false;
-            const authToken = this.accountService.getAccessToken();
-            const modified = request.clone({ headers: request.headers.append('Authorization', "Bearer " + authToken) });
+            const modified = request.clone({ headers: this.addExtraHeaders(request.headers, (request.method == "POST" || request.method == "PUT" || request.method == "DELETE")) });
             return next.handle(modified);
             }),
           catchError((error) => {
@@ -54,4 +52,21 @@ export class AuthInterceptor implements HttpInterceptor
     return next.handle(request);
   }
 
+  private addExtraHeaders(headers: HttpHeaders, postput: boolean): HttpHeaders
+  {
+    const authToken = this.accountService.getAccessToken();
+
+    headers = headers.append('Authorization', "Bearer " + authToken);
+
+    const csrfToken = this.csrfTokenExtrator.getToken() as string;
+
+    console.log("csrfToken = " + csrfToken); // TODO
+
+    if (postput && (csrfToken != null))
+    {
+      headers = headers.append('X-XSRF-TOKEN', csrfToken);
+    }
+
+    return headers;
+  }
 }