All files / app/core/auth auth.service.ts

82.35% Statements 42/51
76.47% Branches 13/17
77.77% Functions 14/18
80.43% Lines 37/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125                25x   25x 25x 25x 25x 25x   25x 25x 25x   25x       8x           5x         17x       15x 15x 15x 15x             3x 1x     2x   1x 1x 1x           3x 3x 3x 3x           3x                   15x 1x     14x                                           3x 3x       5x 5x         5x   5x      
import { computed, inject, Injectable, signal } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, Subscription, catchError, interval, map, of, switchMap, throwError } from 'rxjs';
import { environment } from '../../../environments/environment';
import { AuthUser, LoginData } from './auth.interfaces';
import { Router } from '@angular/router';
 
@Injectable({ providedIn: 'root' })
export class AuthService {
 
  private readonly router = inject(Router);
  private readonly apiBase = environment.authApiBaseUrl;
  private readonly authUserSignal = signal<AuthUser | null>(null);
  private readonly authResolvedSignal = signal(false);
  private refreshSessionSubscription: Subscription | null = null;
 
  readonly authUser = this.authUserSignal.asReadonly();
  readonly authResolved = this.authResolvedSignal.asReadonly();
  readonly isAuthenticated = computed(() => this.authUser() !== null);
 
  constructor(private http: HttpClient) {
  }
 
  login(credentials: LoginData): Observable<AuthUser> {
    return this.http.post(this.apiBase+"/api/v1/auth/login", credentials, {
      responseType: 'text',
      withCredentials: true // ✅ recibe la cookie
    }).pipe(
      catchError(this.handleError),
      // ✅ cuando el login es exitoso, encadena la petición del usuario
      switchMap(() => this.fetchCurrentUser()),
    );
  }
 
  fetchCurrentUser(): Observable<AuthUser> {
    return this.http.post<AuthUser>(this.apiBase+'/api/v1/auth/session', {}, {
      withCredentials: true // ✅ envía la cookie para autenticarse
    }).pipe(
      map((user) => {
        this.authUserSignal.set(user);
        this.authResolvedSignal.set(true);
        this.refreshSession();
        return user;
      }),
      catchError(this.handleError)
    );
  }
 
  ensureAuthState(): Observable<AuthUser | null> {
    if (this.authResolvedSignal()) {
      return of(this.authUserSignal());
    }
 
    return this.fetchCurrentUser().pipe(
      catchError(() => {
        this.authUserSignal.set(null);
        this.authResolvedSignal.set(true);
        return of(null);
      })
    );
  }
 
  logout(): void {
    this.stopRefreshSession();
    this.authUserSignal.set(null);
    this.authResolvedSignal.set(true);
    this.http.post(this.apiBase+'/api/v1/auth/logout', {}, {
      withCredentials: true,
      responseType: 'text'
    }).subscribe(
      {
        next: (response) => { 
          console.log(response)
        },
        error: (err) => {     
          console.log("Error al hacer logout: ", err)      
        }
      }
    );
  }
 
  private refreshSession(): void {
    if (this.refreshSessionSubscription) {
      return;
    }
 
    this.refreshSessionSubscription = interval(540_000).pipe(
      switchMap(() =>
        this.http.post(this.apiBase+"/api/v1/auth/refresh", null, {
          responseType: 'text',
          withCredentials: true // ✅ recibe la cookie
        }).pipe(
          catchError(this.handleError)
        )
      )
    ).subscribe({
      next: (res) => { console.log(res); },
      error: (err) => {
        this.stopRefreshSession();
        this.authUserSignal.set(null);
        this.authResolvedSignal.set(true);
        this.router.navigateByUrl('/login');
        console.error('Error refreshing session:', err);
      }
    });
  }
 
  private stopRefreshSession(): void {
    this.refreshSessionSubscription?.unsubscribe();
    this.refreshSessionSubscription = null;
  }
 
  private handleError(error: HttpErrorResponse) {
    let errorMessage = 'Error desconocido';
    Iif (error.error instanceof ErrorEvent) {
      // Error del lado del cliente
      errorMessage = `Error: ${error.error.message}`;
    } else {
      // Error del lado del servidor
      errorMessage = `Código: ${error.status} - Mensaje: ${error.message}`;
    }
    return throwError(() => new Error(errorMessage));
  }
}