Files
smartguide/webapp/src/app/modules/app-login/app-login.component.ts
T
Roman bda7aff447
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
fix(login): re-enable forms after failed auth requests
2026-07-06 23:15:52 +02:00

255 lines
6.4 KiB
TypeScript

import { Component, effect, OnDestroy } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { CredentialService } from '../../shared/services/credential.service';
import { MatIconModule } from '@angular/material/icon';
import { CommonModule } from '@angular/common';
import { finalize, Subscription } from 'rxjs';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { Router, RouterLink } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
type LoginStep = 'credentials' | 'otk';
@Component({
selector: 'app-app-login',
imports: [
CommonModule,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatIconModule,
MatSnackBarModule,
RouterLink,
],
templateUrl: './app-login.component.html',
styleUrl: './app-login.component.scss',
standalone: true,
})
export class AppLoginComponent implements OnDestroy {
credentialsForm = new FormGroup({
email: new FormControl<string>('', [Validators.required, Validators.email]),
password: new FormControl<string>('', [
Validators.required,
Validators.minLength(8),
]),
});
otkForm = new FormGroup({
code: new FormControl<string>('', [
Validators.required,
Validators.pattern(/^[0-9A-Za-z]{6,10}$/),
]),
});
currentStep: LoginStep = 'credentials';
showPassword = false;
isSubmitting = false;
codeExpiresIn = 0;
readonly codeLifetimeSeconds = 300;
subscription?: Subscription;
private countdownInterval?: ReturnType<typeof setInterval>;
private accountId?: string;
constructor(
protected credentialService: CredentialService,
protected router: Router,
protected snackBar: MatSnackBar,
) {
effect(() => {
if (this.credentialService.isValidating()) {
this.credentialsForm.disable();
this.otkForm.disable();
} else {
this.credentialsForm.enable();
this.otkForm.enable();
this.checkEnter();
}
});
}
checkEnter(): void {
if (this.credentialService.isAuthenticated()) {
this.router.navigate(['/dashboard']);
}
}
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
this.subscription = undefined;
}
this.stopCountdown();
}
requestOtk() {
if (this.credentialsForm.invalid || this.isSubmitting) {
this.credentialsForm.markAllAsTouched();
return;
}
this.isSubmitting = true;
this.credentialsForm.disable();
const email = this.credentialsForm.controls.email.value ?? '';
const password = this.credentialsForm.controls.password.value ?? '';
this.credentialService
.requestOtk(email, password)
.pipe(
finalize(() => {
this.isSubmitting = false;
this.credentialsForm.enable();
}),
)
.subscribe({
next: (otkResponse) => {
const accountId = otkResponse.account_id;
this.accountId = accountId;
this.currentStep = 'otk';
this.otkForm.reset();
this.startCountdown();
this.snackBar.open(
'OTK-Code wurde an die E-Mail-Adresse gesendet.',
'OK',
{
duration: 4000,
},
);
},
error: (error: unknown) => {
this.snackBar.open(
this.getLoginErrorMessage(error as HttpErrorResponse),
'OK',
{
duration: 5000,
},
);
},
});
}
resendCode() {
if (this.isSubmitting) {
return;
}
this.requestOtk();
}
login() {
if (this.otkForm.invalid || this.isSubmitting) {
this.otkForm.markAllAsTouched();
return;
}
if (this.codeExpiresIn <= 0) {
this.snackBar.open(
'Der Code ist abgelaufen. Bitte fordere einen neuen Code an.',
'OK',
{ duration: 5000 },
);
return;
}
if (!this.accountId) {
this.snackBar.open('Bitte fordere zuerst einen neuen Code an.', 'OK', {
duration: 5000,
});
return;
}
this.isSubmitting = true;
this.otkForm.disable();
const code = this.otkForm.controls.code.value ?? '';
this.credentialService
.loginWithOtk(this.accountId, code)
.pipe(
finalize(() => {
this.isSubmitting = false;
this.otkForm.enable();
}),
)
.subscribe({
next: () => {
this.credentialService.reauthenticateViaIdToken().subscribe({
next: () => {
this.checkEnter();
this.stopCountdown();
this.router.navigate(['/dashboard']);
},
});
},
error: (error: unknown) => {
this.snackBar.open(
this.getLoginErrorMessage(error as HttpErrorResponse),
'OK',
{
duration: 5000,
},
);
},
});
}
editCredentials() {
this.currentStep = 'credentials';
this.accountId = undefined;
this.stopCountdown();
this.otkForm.reset();
}
formatCountdown(): string {
const minutes = Math.floor(this.codeExpiresIn / 60);
const seconds = this.codeExpiresIn % 60;
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
private startCountdown(): void {
this.stopCountdown();
this.codeExpiresIn = this.codeLifetimeSeconds;
this.countdownInterval = setInterval(() => {
this.codeExpiresIn = Math.max(this.codeExpiresIn - 1, 0);
if (this.codeExpiresIn === 0) {
this.stopCountdown(false);
}
}, 1000);
}
private stopCountdown(reset = true): void {
if (this.countdownInterval) {
clearInterval(this.countdownInterval);
this.countdownInterval = undefined;
}
if (reset) {
this.codeExpiresIn = 0;
}
}
private getLoginErrorMessage(error: HttpErrorResponse): string {
console.error('Login error:', error);
if (error.status === 401) {
return 'E-Mail, Passwort oder OTK-Code ist ungültig.';
}
if (error.status === 403) {
return 'Dieser Account ist deaktiviert und kann sich nicht anmelden.';
}
return 'Die Anmeldung konnte nicht abgeschlossen werden. Bitte versuche es erneut.';
}
}