chore: validate email and password length on signup

This commit is contained in:
isra el
2024-04-27 05:25:50 +03:00
parent 583e184b47
commit c265eb7def
2 changed files with 43 additions and 0 deletions

View File

@@ -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,
)
}
}
}

View File

@@ -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))
}