refactor: clean up ForgotPasswordComponent by removing unnecessary code

This commit is contained in:
Chneemann 2025-05-08 09:29:53 +02:00
parent a8a74761b4
commit bd501f3d47
3 changed files with 61 additions and 126 deletions

View file

@ -1,7 +1,8 @@
<section class="login-background"> <section class="login-background">
<div class="content"> <div class="content">
<div class="headline">Forgot your password?</div> <div class="headline">Forgot your password?</div>
@if (!queryEmail && !emailSendSuccess && !passwordChangeSuccess) { @if (!hasVerificationParams && !emailSendSuccess && !passwordChangeSuccess)
{
<app-email-request <app-email-request
(submittedChangeEmail)="submittedChangeEmail($event)" (submittedChangeEmail)="submittedChangeEmail($event)"
></app-email-request> ></app-email-request>
@ -21,9 +22,9 @@
</p> </p>
<a routerLink="/login">To the login</a> <a routerLink="/login">To the login</a>
</div> </div>
} @if (queryEmail && !passwordChangeSuccess) { } @if (hasVerificationParams && !passwordChangeSuccess) {
<app-password-request <app-password-request
[queryData]="queryData" [verificationParams]="verificationParams"
(submittedChangePassword)="submittedChangePassword($event)" (submittedChangePassword)="submittedChangePassword($event)"
></app-password-request> ></app-password-request>

View file

@ -1,12 +1,11 @@
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { BtnLargeComponent } from '../../../shared/components/buttons/btn-large/btn-large.component'; import { FormsModule } from '@angular/forms';
import { FormsModule, NgForm } from '@angular/forms';
import { ActivatedRoute, Params, RouterLink } from '@angular/router'; import { ActivatedRoute, Params, RouterLink } from '@angular/router';
import { AuthService } from '../../../services/auth.service'; import { AuthService } from '../../../services/auth.service';
import { ErrorService } from '../../../services/error.service';
import { EmailRequestComponent } from './email-request/email-request.component'; import { EmailRequestComponent } from './email-request/email-request.component';
import { PasswordRequestComponent } from './password-request/password-request.component'; import { PasswordRequestComponent } from './password-request/password-request.component';
import { firstValueFrom } from 'rxjs';
@Component({ @Component({
selector: 'app-forgot-password', selector: 'app-forgot-password',
@ -24,140 +23,75 @@ import { PasswordRequestComponent } from './password-request/password-request.co
export class ForgotPasswordComponent implements OnInit { export class ForgotPasswordComponent implements OnInit {
emailSendSuccess: boolean = false; emailSendSuccess: boolean = false;
passwordChangeSuccess: boolean = false; passwordChangeSuccess: boolean = false;
hasVerificationParams: boolean = false;
queryEmail: boolean = false; verificationParams: { email: string; token: string } = {
queryEmailSuccess: boolean = false;
authData = {
email: '',
token: '',
password: '',
send: false,
};
queryData = {
email: '', email: '',
token: '', token: '',
}; };
/** /**
* Initializes the ForgotPasswordComponent with ActivatedRoute, AuthService, and ErrorService. * Initializes the ForgotPasswordComponent with ActivatedRoute and AuthService.
*/ */
constructor( constructor(private route: ActivatedRoute, public authService: AuthService) {}
private route: ActivatedRoute,
public authService: AuthService,
public errorService: ErrorService
) {}
/** /**
* Lifecycle hook that initializes the component. * Initializes the component and triggers the email verification process.
* Extracts query parameters and triggers email query flag if needed.
*/ */
ngOnInit(): void { async ngOnInit(): Promise<void> {
this.handleQueryParams(); await this.initVerification();
} }
/**
* Coordinates the overall email verification process by handling query parameters
* and calling the verification API if valid data is present.
*/
private async initVerification(): Promise<void> {
await this.handleQueryParams();
if (this.verificationParams.email && this.verificationParams.token) {
this.hasVerificationParams = true;
}
}
/**
* Retrieves and processes query parameters from the current route.
* Extracts the necessary authentication data for verification.
*/
private async handleQueryParams(): Promise<void> {
const params = await firstValueFrom(this.route.queryParams);
this.extractAuthParams(params);
}
/**
* Extracts the 'email' and 'token' values from the given query parameters
* and stores them in the verifyData object.
*
* @param params The query parameters from the current route.
*/
private extractAuthParams(params: Params): void {
this.verificationParams = {
email: params['email'] || '',
token: params['token'] || '',
};
}
/**
* Event handler for the completion of the email change request process.
* Updates the UI to reflect the success status of the email change.
*
* @param success A boolean indicating whether the request was successful.
*/
submittedChangeEmail(success: boolean): void { submittedChangeEmail(success: boolean): void {
this.emailSendSuccess = success; this.emailSendSuccess = success;
} }
/**
* Event handler for the completion of the password change request process.
* Updates the UI to reflect the success status of the password change.
*
* @param success A boolean indicating whether the password change was successful.
*/
submittedChangePassword(success: boolean): void { submittedChangePassword(success: boolean): void {
this.passwordChangeSuccess = success; this.passwordChangeSuccess = success;
} }
/**
* Subscribes to query parameters and sets internal flags based on them.
*/
private handleQueryParams(): void {
this.route.queryParams.subscribe((params) => {
this.extractAuthParams(params);
if (this.queryData.email && this.queryData.token) {
this.queryEmail = true;
}
});
}
/**
* Extracts email and token from route parameters and stores them in authData.
*
* @param params The query parameters from the URL.
*/
private extractAuthParams(params: Params): void {
this.queryData.email = params['email'] || '';
this.queryData.token = params['token'] || '';
}
/**
* Validates the given email address.
*
* @param emailValue The email to validate.
* @returns True if the email is valid, false otherwise.
*/
isUserEmailValid(emailValue: string): boolean {
const emailRegex = /^[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(emailValue);
}
/**
* Handles form submission based on which field was used (email or password).
*
* @param ngForm The form group.
* @param emailInput The input field triggering the submit.
*/
async onSubmit(ngForm: NgForm, emailInput: any): Promise<void> {
if (ngForm.submitted && ngForm.form.valid) {
try {
if (emailInput.name === 'email') {
await this.verifyEmail();
} else if (emailInput.name === 'password') {
await this.changePassword();
}
ngForm.form.reset();
} catch {}
} else {
emailInput.control.markAsTouched();
}
}
/**
* Sends a request to start the forgot-password process.
* Updates flags and handles errors accordingly.
*/
private async verifyEmail(): Promise<void> {
const body = {
email: this.authData.email.toLowerCase(),
};
this.authData.send = true;
try {
await this.authService.forgotPassword(body);
this.emailSendSuccess = true;
this.errorService.clearError();
} catch (error) {
this.authData.send = false;
this.emailSendSuccess = false;
this.errorService.handleError(error);
}
}
/**
* Sends a request to update the user's password using the token.
* Updates flags and handles errors accordingly.
*/
private async changePassword(): Promise<void> {
const body = {
email: this.authData.email.toLowerCase(),
token: this.authData.token,
new_password: this.authData.password,
};
this.authData.send = true;
try {
await this.authService.changePassword(body);
this.queryEmail = false;
this.queryEmailSuccess = true;
this.errorService.clearError();
} catch (error) {
this.authData.send = false;
this.errorService.handleError(error);
}
}
} }

View file

@ -17,7 +17,7 @@ import { ErrorService } from '../../../../services/error.service';
styleUrl: './password-request.component.scss', styleUrl: './password-request.component.scss',
}) })
export class PasswordRequestComponent { export class PasswordRequestComponent {
@Input() queryData!: { email: string; token: string }; @Input() verificationParams!: { email: string; token: string };
@Output() submittedChangePassword = new EventEmitter<boolean>(); @Output() submittedChangePassword = new EventEmitter<boolean>();
@ -84,8 +84,8 @@ export class PasswordRequestComponent {
password: string; password: string;
} { } {
return { return {
email: this.queryData.email, email: this.verificationParams.email,
token: this.queryData.token, token: this.verificationParams.token,
password: this.form.value.password, password: this.form.value.password,
}; };
} }