refactor: apply email format validator to LoginComponent and rename 'mail' to 'email'

This commit is contained in:
Chneemann 2025-05-06 12:50:36 +02:00
parent c049f29407
commit e5c4e5a527
14 changed files with 217 additions and 234 deletions

View file

@ -21,7 +21,7 @@ export const environment = {
baseUrl: "YOUR_API_URL_HERE",
// Guest account
guestMail: "YOUR_GUEST_EMAIL_HERE",
guestEmail: "YOUR_GUEST_EMAIL_HERE",
guestPassword: "YOUR_GUEST_PASSWORD_HERE",
};
```

View file

@ -1,50 +1,50 @@
<section class="login-background">
<div class="content">
<div class="headline">Forgot your password?</div>
@if (!queryEmail && !sendMailSuccess && !queryEmailSuccess) {
@if (!queryEmail && !sendEmailSuccess && !queryEmailSuccess) {
<div class="note">
<p>We will send you an email with instructions to reset your password.</p>
</div>
<form
#taskForm="ngForm"
(ngSubmit)="onSubmit(taskForm, mail)"
(ngSubmit)="onSubmit(taskForm, email)"
onsubmit="return false"
>
<div class="mail-field">
<div class="email-field">
<input
type="mail"
id="mail"
name="mail"
#mail="ngModel"
type="email"
id="email"
name="email"
#email="ngModel"
placeholder="Email Address"
class="custom-input"
autocomplete="email"
[(ngModel)]="authData.mail"
[(ngModel)]="authData.email"
[class.error-border]="
(!mail.valid && mail.touched) ||
(mail.touched &&
!isUserEmailValid(authData.mail.toLowerCase()) &&
authData.mail.length > 0)
(!email.valid && email.touched) ||
(email.touched &&
!isUserEmailValid(authData.email.toLowerCase()) &&
authData.email.length > 0)
"
(click)="this.errorService.clearError()"
required
/>
<img class="mail-icon" src="./assets/img/mail.svg" />
<img class="email-icon" src="./assets/img/email.svg" />
</div>
<div class="error-msg">
@if (!mail.valid && mail.touched) {
@if (!email.valid && email.touched) {
<p>Please enter your email</p>
} @else { @if (mail.touched && authData.mail.length > 0 &&
!isUserEmailValid(authData.mail.toLowerCase())) {
} @else { @if (email.touched && authData.email.length > 0 &&
!isUserEmailValid(authData.email.toLowerCase())) {
<p>This is not a valid email format</p>
}}
</div>
<app-btn-large
[value]="'Send Email'"
[disabled]="!isUserEmailValid(authData.mail) || authData.send"
[disabled]="!isUserEmailValid(authData.email) || authData.send"
></app-btn-large>
</form>
} @else { @if (sendMailSuccess) {
} @else { @if (sendEmailSuccess) {
<div class="note">
<p>
If the email you entered exists on our server, you will receive a
@ -134,7 +134,7 @@
<app-btn-large
[value]="'Update Password'"
[disabled]="
!isUserEmailValid(authData.mail) ||
!isUserEmailValid(authData.email) ||
authData.password !== authData.passwordConfirm ||
!authData.password ||
!authData.passwordConfirm ||

View file

@ -14,12 +14,12 @@ import { ErrorService } from '../../../services/error.service';
styleUrl: './forgot-password.component.scss',
})
export class ForgotPasswordComponent implements OnInit {
sendMailSuccess: boolean = false;
sendEmailSuccess: boolean = false;
queryEmail: boolean = false;
queryEmailSuccess: boolean = false;
authData = {
mail: '',
email: '',
token: '',
password: '',
passwordConfirm: '',
@ -50,7 +50,7 @@ export class ForgotPasswordComponent implements OnInit {
this.route.queryParams.subscribe((params) => {
this.extractAuthParams(params);
this.queryEmailSuccess = params['pw-change'] || '';
if (this.authData.mail && this.authData.token) {
if (this.authData.email && this.authData.token) {
this.queryEmail = true;
}
});
@ -62,7 +62,7 @@ export class ForgotPasswordComponent implements OnInit {
* @param params The query parameters from the URL.
*/
private extractAuthParams(params: Params): void {
this.authData.mail = params['email'] || '';
this.authData.email = params['email'] || '';
this.authData.token = params['token'] || '';
}
@ -81,20 +81,20 @@ export class ForgotPasswordComponent implements OnInit {
* Handles form submission based on which field was used (email or password).
*
* @param ngForm The form group.
* @param mailInput The input field triggering the submit.
* @param emailInput The input field triggering the submit.
*/
async onSubmit(ngForm: NgForm, mailInput: any): Promise<void> {
async onSubmit(ngForm: NgForm, emailInput: any): Promise<void> {
if (ngForm.submitted && ngForm.form.valid) {
try {
if (mailInput.name === 'mail') {
if (emailInput.name === 'email') {
await this.verifyEmail();
} else if (mailInput.name === 'password') {
} else if (emailInput.name === 'password') {
await this.changePassword();
}
ngForm.form.reset();
} catch {}
} else {
mailInput.control.markAsTouched();
emailInput.control.markAsTouched();
}
}
@ -104,16 +104,16 @@ export class ForgotPasswordComponent implements OnInit {
*/
private async verifyEmail(): Promise<void> {
const body = {
email: this.authData.mail.toLowerCase(),
email: this.authData.email.toLowerCase(),
};
this.authData.send = true;
try {
await this.authService.forgotPassword(body);
this.sendMailSuccess = true;
this.sendEmailSuccess = true;
this.errorService.clearError();
} catch (error) {
this.authData.send = false;
this.sendMailSuccess = false;
this.sendEmailSuccess = false;
this.errorService.handleError(error);
}
}
@ -124,7 +124,7 @@ export class ForgotPasswordComponent implements OnInit {
*/
private async changePassword(): Promise<void> {
const body = {
email: this.authData.mail.toLowerCase(),
email: this.authData.email.toLowerCase(),
token: this.authData.token,
new_password: this.authData.password,
};

View file

@ -6,31 +6,31 @@
</div>
<form
#taskForm="ngForm"
(ngSubmit)="onSubmit(taskForm, mail)"
(ngSubmit)="onSubmit(taskForm, email)"
onsubmit="return false"
>
<input
type="mail"
id="mail"
name="mail"
#mail="ngModel"
type="email"
id="email"
name="email"
#email="ngModel"
placeholder="Email Address"
class="custom-input"
autocomplete="email"
[(ngModel)]="authData.mail"
[(ngModel)]="authData.email"
[class.error-border]="
(!mail.valid && mail.touched) ||
(mail.touched &&
!isUserEmailValid(authData.mail) &&
authData.mail.length > 0)
(!email.valid && email.touched) ||
(email.touched &&
!isUserEmailValid(authData.email) &&
authData.email.length > 0)
"
required
/>
<div class="error-msg">
@if (!mail.valid && mail.touched) {
@if (!email.valid && email.touched) {
<p>Please enter your email</p>
} @else { @if (mail.touched && authData.mail.length > 0 &&
!isUserEmailValid(authData.mail)) {
} @else { @if (email.touched && authData.email.length > 0 &&
!isUserEmailValid(authData.email)) {
<p>This is not a valid email format</p>
}}
</div>
@ -40,7 +40,7 @@
[imgPath]="'arrow_right'"
[imgReverse]="true"
[disabled]="
(!isUserEmailValid(authData.mail) && authData.mail.length > 0) ||
(!isUserEmailValid(authData.email) && authData.email.length > 0) ||
authData.send
"
></app-btn-large>

View file

@ -15,7 +15,7 @@ import { AuthService } from '../../../services/auth.service';
})
export class LandingPageComponent {
authData = {
mail: '',
email: '',
send: false,
};
@ -45,13 +45,13 @@ export class LandingPageComponent {
* If the form is valid, checks for duplicate email addresses.
*
* @param ngForm The submitted form.
* @param mailInput The input field for the email.
* @param emailInput The input field for the email.
*/
async onSubmit(ngForm: NgForm, mailInput: any): Promise<void> {
async onSubmit(ngForm: NgForm, emailInput: any): Promise<void> {
if (ngForm.submitted && ngForm.form.valid) {
await this.checkDuplicatesEmail();
} else {
mailInput.control.markAsTouched();
emailInput.control.markAsTouched();
}
}
@ -61,15 +61,15 @@ export class LandingPageComponent {
* Handles UI state and errors accordingly.
*/
private async checkDuplicatesEmail(): Promise<void> {
const email = this.authData.mail.trim().toLowerCase();
const email = this.authData.email.trim().toLowerCase();
if (!email) return;
this.authData.send = true;
try {
await this.authService.checkAuthUserMail({ email });
await this.authService.checkAuthUserEmail({ email });
this.errorService.clearError();
this.router.navigate(['/register'], { queryParams: { mail: email } });
this.router.navigate(['/register'], { queryParams: { email: email } });
} catch (error) {
this.errorService.handleError(error);
} finally {

View file

@ -1,55 +1,50 @@
<section class="login-background">
<div class="content">
<div class="headline">Log in</div>
<form
#loginForm="ngForm"
(ngSubmit)="onSubmit(loginForm)"
onsubmit="return false"
[formGroup]="form"
(ngSubmit)="onSubmit()"
(input)="this.errorService.clearError()"
>
<div class="mail-field">
<div class="email-field">
<input
type="mail"
id="mail"
name="mail"
#mail="ngModel"
formControlName="email"
type="email"
id="email"
placeholder="Email Address"
autocomplete="email"
[(ngModel)]="authData.mail"
[class.error-border]="
(!mail.valid && mail.touched) ||
(mail.touched &&
!isUserEmailValid(authData.mail) &&
authData.mail.length > 0)
form.controls['email'].invalid && form.controls['email'].touched
"
required
/>
<img class="mail-icon" src="./assets/img/mail.svg" />
<img class="email-icon" src="./assets/img/email.svg" />
</div>
<div class="error-container">
@if (form.controls['email'].touched && form.controls['email'].invalid) {
<div class="error-msg">
@if (!mail.valid && mail.touched) {
<p>Please enter your email</p>
} @else { @if (mail.touched && authData.mail.length > 0 &&
!isUserEmailValid(authData.mail)) {
<p>This is not a valid email format</p>
}}
@if (form.controls['email'].errors?.['required']) {
<p role="alert">Please enter your email</p>
} @if (form.controls['email'].errors?.['invalidEmailFormat']) {
<p role="alert">This is not a valid email format</p>
}
</div>
}
</div>
<div class="password-field">
<input
[type]="authService.passwordFieldType"
id="password"
name="password"
class="password-input"
#password="ngModel"
formControlName="password"
placeholder="Enter a password"
autocomplete="new-password"
[(ngModel)]="authData.password"
pattern="[^<>]*"
minlength="6"
minlength="8"
[class.error-border]="
password.invalid && password.touched && authData.password.length < 6
form.controls['password'].invalid &&
form.controls['password'].touched
"
required
/>
<img class="password-icon" src="./assets/img/password.svg" />
<img
@ -58,50 +53,46 @@
[src]="authService.passwordIcon"
/>
</div>
<div class="error-container">
@if (form.controls['password'].touched &&
form.controls['password'].invalid) {
<div class="error-msg">
@if (!password.valid && password.touched && authData.password.length <
1) {
<p>Please enter your password</p>
} @else { @if (authData.password && authData.password.length < 6 &&
password.touched) {
<p>Password is too short, min 6 characters</p>
} }
@if (form.controls['password'].errors?.['required']) {
<p role="alert">Please enter a password</p>
} @if (form.controls['password'].errors?.['minlength']) {
<p role="alert">Password is too short, min 8 characters</p>
}
</div>
}
</div>
<div class="checkbox">
<label class="container"
>Remember me
<label class="container">
Stay signed in?
<input
type="checkbox"
id="checkbox"
name="checkbox"
#checkbox
[(ngModel)]="authData.checkbox"
type="checkbox"
formControlName="keepLoggedIn"
/>
<span class="checkmark"></span>
</label>
</div>
<div class="buttons">
<app-btn-large
[value]="'Log in'"
[disabled]="
!authData.mail ||
(!isUserEmailValid(authData.mail) && authData.mail.length > 0) ||
!password.valid ||
authData.guestLogin ||
authData.send
"
[disabled]="form.invalid"
></app-btn-large>
<app-btn-large
[value]="'Guest Log in'"
[disabled]="
authData.guestLogin ||
(!!authData.mail && !!authData.password) ||
authData.send
"
(click)="guestLogin(loginForm)"
[disabled]="form.value.mail || form.value.password"
(click)="guestLogin()"
></app-btn-large>
</div>
</form>
<div class="footer">
<a routerLink="/forgot-password">Forgot password?</a>
<div class="footer-content">

View file

@ -1,107 +1,114 @@
import { Component } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { BtnLargeComponent } from '../../../shared/components/buttons/btn-large/btn-large.component';
import { FormsModule, NgForm } from '@angular/forms';
import {
FormBuilder,
FormGroup,
FormsModule,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
import { ErrorService } from '../../../services/error.service';
import { CommonModule } from '@angular/common';
import { environment } from '../../../../environments/environment';
import { emailFormatValidator } from '../../../validators/email-format.validator';
@Component({
selector: 'app-login',
standalone: true,
imports: [BtnLargeComponent, CommonModule, FormsModule, RouterLink],
imports: [
BtnLargeComponent,
CommonModule,
FormsModule,
ReactiveFormsModule,
RouterLink,
],
templateUrl: './login.component.html',
styleUrl: './login.component.scss',
})
export class LoginComponent {
export class LoginComponent implements OnInit {
showPassword: boolean = false;
authData = {
mail: '',
password: '',
checkbox: false,
send: false,
guestLogin: false,
};
form: FormGroup = new FormGroup({});
/**
* Initializes the LoginComponent with Router, AuthService, and ErrorService.
* Initializes the LoginComponent with Router, FormBuilder, AuthService, and ErrorService.
*/
constructor(
private router: Router,
private fb: FormBuilder,
public authService: AuthService,
public errorService: ErrorService
) {}
/**
* Validates the given email address.
* Converts to lowercase before checking against the regex.
*
* @param emailValue The email address to validate.
* @returns True if the email format is valid, false otherwise.
* Initializes the component by setting up necessary data.
*/
isUserEmailValid(emailValue: string): boolean {
const emailRegex = /^[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(emailValue.toLowerCase());
ngOnInit(): void {
this.createLoginForm();
}
/**
* Logs the user in as a guest using predefined credentials from the environment.
* Resets form and navigates to the main application area on success.
*
* @param ngForm The login form instance.
* Initializes the login form with required fields and validators.
*/
async guestLogin(ngForm: NgForm): Promise<void> {
private createLoginForm(): void {
this.form = this.fb.group({
email: ['', [Validators.required, emailFormatValidator()]],
password: ['', Validators.required],
keepLoggedIn: [false],
});
}
/**
* Handles the submission of the login form.
*
* @returns A Promise that resolves when the login process is complete.
*/
async onSubmit(): Promise<void> {
if (this.form.invalid) return;
const body = this.createLoginRequestBody();
await this.performLogin(body);
}
/**
* Initiates a guest login by preparing guest credentials and performing the login request.
*
* @returns A Promise that resolves when the login process is complete.
*/
async guestLogin(): Promise<void> {
this.prepareGuestLoginData();
const body = this.createLoginRequestBody(
environment.guestMail,
environment.guestPassword
);
const body = this.createLoginRequestBody();
try {
this.authData.send = true;
await this.authService.login(body, this.authData.checkbox);
this.resetAuthData();
this.router.navigate(['/browse/']);
this.errorService.clearError();
} catch (error) {
this.handleLoginError(error, ngForm);
}
}
/**
* Handles standard login form submission.
* Sends login request and navigates to the application on success.
*
* @param ngForm The login form instance.
*/
async onSubmit(ngForm: NgForm): Promise<void> {
if (ngForm.submitted && ngForm.form.valid) {
const body = this.createLoginRequestBody(
this.authData.mail,
this.authData.password
);
try {
this.authData.send = true;
await this.authService.login(body, this.authData.checkbox);
ngForm.resetForm();
this.router.navigate(['/browse/']);
this.errorService.clearError();
} catch (error) {
this.handleLoginError(error, ngForm);
}
}
await this.performLogin(body);
}
/**
* Prepares the authentication data for a guest login.
*/
private prepareGuestLoginData(): void {
this.authData.mail = environment.guestMail;
this.authData.password = environment.guestPassword;
this.authData.guestLogin = true;
this.form.patchValue({
email: environment.guestEmail.toLowerCase(),
password: environment.guestPassword,
});
}
/**
* Performs the login process.
*
* @param body The login request body containing email, password, and keepLoggedIn.
* @returns A Promise that resolves when the login process is complete.
*/
private async performLogin(body: any): Promise<void> {
try {
this.form.disable();
await this.authService.login(body);
this.form.reset();
this.router.navigate(['/browse/']);
} catch (error) {
this.form.enable();
this.errorService.handleError(error);
}
}
/**
@ -109,37 +116,19 @@ export class LoginComponent {
*
* @param email The email for the login request.
* @param password The password for the login request.
* @param keepLoggedIn Whether to keep the user signed in.
* @returns The body of the login request.
*/
private createLoginRequestBody(
email: string,
password: string
): { email: string; password: string } {
private createLoginRequestBody(): {
email: string;
password: string;
keepLoggedIn: boolean;
} {
const formValue = this.form.value;
return {
email,
password,
email: formValue.email.toLowerCase(),
password: formValue.password,
keepLoggedIn: formValue.keepLoggedIn,
};
}
/**
* Resets the authentication data after a successful login.
*/
private resetAuthData(): void {
this.authData.mail = '';
this.authData.password = '';
this.authData.guestLogin = false;
}
/**
* Handles errors during login, resets form, and clears errors.
*
* @param error The error to handle.
* @param ngForm The login form instance.
*/
private handleLoginError(error: any, ngForm: NgForm): void {
this.authData.send = false;
this.authData.guestLogin = false;
ngForm.reset();
this.errorService.handleError(error);
}
}

View file

@ -16,26 +16,26 @@
(ngSubmit)="onSubmit()"
(input)="this.errorService.clearError()"
>
<div class="mail-field">
<div class="email-field">
<input
formControlName="mail"
formControlName="email"
type="email"
id="mail"
id="email"
placeholder="Email Address"
autocomplete="email"
[class.error-border]="
form.controls['mail'].invalid && form.controls['mail'].touched
form.controls['email'].invalid && form.controls['email'].touched
"
/>
<img class="mail-icon" src="./assets/img/mail.svg" />
<img class="email-icon" src="./assets/img/email.svg" />
</div>
<div class="error-container">
@if (form.controls['mail'].touched && form.controls['mail'].invalid) {
@if (form.controls['email'].touched && form.controls['email'].invalid) {
<div class="error-msg">
@if (form.controls['mail'].errors?.['required']) {
@if (form.controls['email'].errors?.['required']) {
<p role="alert">Please enter your email</p>
} @if (form.controls['mail'].errors?.['invalidEmailFormat']) {
} @if (form.controls['email'].errors?.['invalidEmailFormat']) {
<p role="alert">This is not a valid email format</p>
}
</div>
@ -102,11 +102,11 @@
form.controls['passwordConfirm'].invalid ) {
<div class="error-msg">
@if (form.controls['passwordConfirm'].errors?.['required']) {
<p>Please confirm your password</p>
<p role="alert">Please confirm your password</p>
} @if ( form.controls['password'].value !==
form.controls['passwordConfirm'].value &&
form.controls['passwordConfirm'].touched ) {
<p>The passwords do not match</p>
<p role="alert">The passwords do not match</p>
}
</div>
}
@ -116,16 +116,19 @@
<label class="container">
I agree to the&nbsp;
<a routerLink="/privacy-policy">Privacy policy</a>.
<input type="checkbox" formControlName="privacyPolicy" />
<input
id="checkbox"
name="checkbox"
type="checkbox"
formControlName="privacyPolicy"
/>
<span class="checkmark"></span>
</label>
</div>
<app-btn-large
[value]="'Get Started'"
[disabled]="
form.invalid || form.controls['privacyPolicy'].value === false
"
[disabled]="form.invalid"
></app-btn-large>
</form>
}

View file

@ -53,7 +53,7 @@ export class RegisterComponent implements OnInit {
*/
private createRegisterForm(): void {
this.form = this.fb.group({
mail: ['', [Validators.required, emailFormatValidator()]],
email: ['', [Validators.required, emailFormatValidator()]],
password: ['', Validators.required],
passwordConfirm: ['', Validators.required],
privacyPolicy: [false, Validators.requiredTrue],
@ -61,12 +61,12 @@ export class RegisterComponent implements OnInit {
}
/**
* Sets the email address from the query parameters in the URL.
* Sets the mail address from the query parameters in the URL.
*/
private setEmailFromQueryParams(): void {
this.route.queryParams.subscribe((params) => {
const email = params['mail'] || '';
this.form.patchValue({ mail: email });
const email = params['email'] || '';
this.form.patchValue({ email: email });
});
}
@ -104,8 +104,8 @@ export class RegisterComponent implements OnInit {
} {
const formValue = this.form.value;
return {
email: formValue.mail.toLowerCase(),
username: formValue.mail.split('@')[0],
email: formValue.email.toLowerCase(),
username: formValue.email.split('@')[0],
password: formValue.password,
};
}

View file

@ -15,7 +15,7 @@ export class VerifyEmailComponent {
verified: boolean = false;
authData = {
mail: '',
email: '',
token: '',
send: false,
};
@ -54,7 +54,7 @@ export class VerifyEmailComponent {
* @param params The query parameters from the route.
*/
private extractAuthParams(params: Params): void {
this.authData.mail = params['email'] || '';
this.authData.email = params['email'] || '';
this.authData.token = params['token'] || '';
}
@ -64,7 +64,7 @@ export class VerifyEmailComponent {
*/
private async verifyEmail(): Promise<void> {
const body = {
email: this.authData.mail.toLowerCase(),
email: this.authData.email.toLowerCase(),
token: this.authData.token,
};

View file

@ -28,12 +28,12 @@ export class AuthService {
* @param storage Whether to persist the token in local storage.
* @throws Error if no token is received upon successful login.
*/
async login(body: any, storage: boolean) {
async login(body: any) {
const data = await firstValueFrom(
this.apiService.post<{ token: string }>('/auth/login/', body)
);
if (data?.token) {
this.tokenService.setToken(data.token, storage);
this.tokenService.setToken(data.token, body.keepLoggedIn);
} else {
throw new Error('Login failed: No token received');
}
@ -87,7 +87,7 @@ export class AuthService {
*
* @param body The email to verify.
*/
async checkAuthUserMail(body: any) {
async checkAuthUserEmail(body: any) {
await firstValueFrom(this.apiService.post('/auth/', body));
}

View file

Before

Width:  |  Height:  |  Size: 929 B

After

Width:  |  Height:  |  Size: 929 B

View file

@ -71,7 +71,7 @@ form {
// Show / Hide Password
.password-field,
.mail-field {
.email-field {
position: relative;
width: 100%;
@ -94,7 +94,7 @@ form {
// Icons
.mail-icon,
.email-icon,
.password-icon {
position: absolute;
left: 44px;

View file

@ -3,6 +3,6 @@ export const environment = {
baseUrl: 'YOUR_API_URL_HERE',
// Guest account
guestMail: 'YOUR_GUEST_EMAIL_HERE',
guestEmail: 'YOUR_GUEST_EMAIL_HERE',
guestPassword: 'YOUR_GUEST_PASSWORD_HERE',
};