All files / app/authentication/login login.ts

97.05% Statements 33/34
100% Branches 21/21
80% Functions 4/5
96.66% Lines 29/30

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                        66x 1x 1x 1x 1x   1x   1x 1x 1x   1x           10x 10x   10x 2x 2x     8x   8x 8x 8x 5x 5x 5x         3x     3x   8x         179x 179x       22x 5x        
import { Component, OnDestroy, inject, signal } from '@angular/core';
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { TranslocoModule, TranslocoService } from '@jsverse/transloco';
import { SupabaseConnector } from '../../services/supabase-connector';
 
@Component({
  selector: 'app-login',
  imports: [ReactiveFormsModule, RouterLink, TranslocoModule],
  templateUrl: './login.html',
  styleUrl: './login.scss',
})
export class Login implements OnDestroy {
  private readonly fb = inject(FormBuilder);
  private readonly supabaseService = inject(SupabaseConnector);
  private readonly router = inject(Router);
  private readonly transloco = inject(TranslocoService);
 
  private redirectTimeoutId: number | null = null;
 
  readonly isSubmitting = signal(false);
  readonly submitError = signal<string | null>(null);
  readonly loginSucceeded = signal(false);
 
  readonly loginForm = this.fb.nonNullable.group({
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(8)]],
  });
 
  async onSubmit(): Promise<void> {
    this.submitError.set(null);
    this.loginSucceeded.set(false);
 
    if (this.loginForm.invalid) {
      this.loginForm.markAllAsTouched();
      return;
    }
 
    this.isSubmitting.set(true);
 
    try {
      const { email, password } = this.loginForm.getRawValue();
      await this.supabaseService.login(email, password);
      this.loginSucceeded.set(true);
      this.loginForm.reset();
      this.redirectTimeoutId = window.setTimeout(() => {
        this.router.navigateByUrl('/account');
      }, 1500);
    } catch (error) {
      const message =
        error instanceof Error
          ? error.message
          : this.transloco.translate('auth.login.submitFailed');
      this.submitError.set(message);
    } finally {
      this.isSubmitting.set(false);
    }
  }
 
  isInvalid(controlName: keyof typeof this.loginForm.controls): boolean {
    const control = this.loginForm.controls[controlName];
    return control.invalid && control.touched;
  }
 
  ngOnDestroy(): void {
    if (this.redirectTimeoutId !== null) {
      window.clearTimeout(this.redirectTimeoutId);
    }
  }
}