From c265eb7deff52fa1d176df005de9164ae0586d44 Mon Sep 17 00:00:00 2001 From: isra el Date: Sat, 27 Apr 2024 05:25:50 +0300 Subject: [PATCH] chore: validate email and password length on signup --- api/src/auth/auth.service.ts | 31 +++++++++++++++++++++++++++++++ web/pages/register.tsx | 12 ++++++++++++ 2 files changed, 43 insertions(+) diff --git a/api/src/auth/auth.service.ts b/api/src/auth/auth.service.ts index 2b983da..ea1bc4d 100644 --- a/api/src/auth/auth.service.ts +++ b/api/src/auth/auth.service.ts @@ -90,6 +90,19 @@ export class AuthService { } async register(userData: any) { + const existingUser = await this.usersService.findOne({ + email: userData.email, + }) + if (existingUser) { + throw new HttpException( + { error: 'User already exists, please login instead' }, + HttpStatus.BAD_REQUEST, + ) + } + + this.validateEmail(userData.email) + this.validatePassword(userData.password) + const hashedPassword = await bcrypt.hash(userData.password, 10) const user = await this.usersService.create({ ...userData, @@ -240,4 +253,22 @@ export class AuthService { console.log(e) }) } + + async validateEmail(email: string) { + const re = /\S+@\S+\.\S+/ + if (!re.test(email)) { + throw new HttpException( + { error: 'Invalid email' }, + HttpStatus.BAD_REQUEST, + ) + } + } + async validatePassword(password: string) { + if (password.length < 6) { + throw new HttpException( + { error: 'Password must be at least 6 characters' }, + HttpStatus.BAD_REQUEST, + ) + } + } } diff --git a/web/pages/register.tsx b/web/pages/register.tsx index 6c45372..a552c52 100644 --- a/web/pages/register.tsx +++ b/web/pages/register.tsx @@ -47,6 +47,18 @@ export default function RegisterPage() { description: 'Please fill in all fields', status: 'warning', }) + } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(credentials.email)) { + toast({ + title: 'Error', + description: 'Invalid email address', + status: 'warning', + }) + } else if (credentials.password.length < 6) { + toast({ + title: 'Error', + description: 'Password must be at least 6 characters', + status: 'warning', + }) } else { dispatch(register(credentials)) }