import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root', }) export class AuthService { private ApiVerifAuthUrl = `${environment.apiBaseUrl}/api/token/verify/`; private ApiTokAuthUrl = `${environment.apiBaseUrl}/api/token/`; private ApiRefAuthUrl = `${environment.apiBaseUrl}/api-token-refresh/`; // Options HTTP utilisées pour effectuer les appels API private httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), }; // Le jeton JWT réel public token: string | undefined; // La date d'expiration du jeton public token_expires: Date | undefined; // Le nom d'utilisateur de l'utilisateur connecté public username: string | undefined; // Messages d'erreur reçus lors de la tentative de connexion // eslint-disable-next-line @typescript-eslint/no-explicit-any public errors: any[] = []; constructor(private http: HttpClient) {} public verifyToken( token: string // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Observable<{ status: boolean; data?: any }> { const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'X-CSRFToken': 'eiasfUdm3tAA1j8nJYoL3fqBR6uFk3dJ7XCffWJ7v3oAGBXHKW4rWXxL1FoRUnXZ', }); const body = { token }; return ( this.http // eslint-disable-next-line @typescript-eslint/no-explicit-any .post(this.ApiVerifAuthUrl, body, { headers, observe: 'response', }) .pipe( // eslint-disable-next-line @typescript-eslint/no-explicit-any map((response: HttpResponse) => { return { status: response.status === 200, data: response.body }; }), catchError(error => { console.error('An error occurred:', error); return throwError({ status: false }); }) ) ); } // Utilise http.post() pour obtenir un jeton d'authentification à partir de l'endpoint djangorestframework-jwt public login(user: { username: string; password: string }) { return ( this.http // eslint-disable-next-line @typescript-eslint/no-explicit-any .post(this.ApiTokAuthUrl, user, this.httpOptions) .subscribe( data => { console.log(data['access']); // eslint-disable-next-line @typescript-eslint/no-unused-vars const token = data['access']; console.log('====>', token); this.updateData(data['access']); }, err => { this.errors = err.error; } ) ); } // Rafraîchit le jeton JWT pour prolonger la session de l'utilisateur public refreshToken() { return ( this.http // eslint-disable-next-line @typescript-eslint/no-explicit-any .post(this.ApiRefAuthUrl, { token: this.token }, this.httpOptions) .subscribe( data => { data; console.log(data); }, err => { this.errors = err.error; } ) ); } // Déconnexion de l'utilisateur public logout() { this.token = ''; this.token_expires; this.username = ''; } // Met à jour les données utilisateur après une connexion réussie ou un rafraîchissement de jeton private updateData(token: string) { this.token = token; this.errors = []; // Décoder le jeton pour lire le nom d'utilisateur et le timestamp d'expiration const token_parts = token.split(/\./); const token_decoded = JSON.parse(atob(token_parts[1])); this.token_expires = new Date(token_decoded.exp * 1000); this.username = token_decoded.username; } }