Added: email validation, email validation exception.

This commit is contained in:
KamilM1205 2025-06-30 00:28:21 +04:00
parent 94a6f234c5
commit d047c17700
4 changed files with 28 additions and 0 deletions

View file

@ -3,6 +3,7 @@ package ru.team58.profileservice.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ru.team58.profileservice.controller.exceptions.BadRequestException;
import ru.team58.profileservice.controller.exceptions.IncorrectEmailException;
import ru.team58.profileservice.controller.exceptions.UnauthorizedException;
import ru.team58.profileservice.controller.exceptions.UserNotFoundException;
import ru.team58.profileservice.controller.schemes.CreateUserRequest;
@ -13,6 +14,7 @@ import ru.team58.profileservice.mapper.UserMapper;
import ru.team58.profileservice.service.UserDTO;
import ru.team58.profileservice.service.UserService;
import ru.team58.profileservice.service.exceptions.UserAlreadyExistsException;
import ru.team58.profileservice.utils.EmailValidator;
import java.security.Principal;
import java.util.UUID;
@ -73,6 +75,9 @@ public class UserController {
public void createMe(@RequestBody CreateUserRequest request) {
UserDTO user = UserMapper.INSTANCE.toUserDTO(request);
if (!EmailValidator.validateEmail(user.getEmail()))
throw new IncorrectEmailException();
try {
userService.createUser(user);
} catch (UserAlreadyExistsException ex) {

View file

@ -37,4 +37,10 @@ public class UserControllerExceptionHandler {
ErrorDetails errorDetails = new ErrorDetails("Unauthorized", HttpStatus.UNAUTHORIZED.value());
return new ResponseEntity<>(errorDetails, HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler(IncorrectEmailException.class)
public ResponseEntity<ErrorDetails> handleIncorrectEmailException(IncorrectEmailException ex) {
ErrorDetails errorDetails = new ErrorDetails("Email is incorrect", HttpStatus.BAD_REQUEST.value());
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
}
}

View file

@ -0,0 +1,4 @@
package ru.team58.profileservice.controller.exceptions;
public class IncorrectEmailException extends BadRequestException {
}

View file

@ -0,0 +1,13 @@
package ru.team58.profileservice.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator {
public static boolean validateEmail(String email) {
String regexPattern = "^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@"
+ "[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";
return Pattern.compile(regexPattern).matcher(email).matches();
}
}