add checks for login process
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Bea 2024-08-09 06:00:36 +02:00
parent 86f4b05b8c
commit d656ab54eb
3 changed files with 28 additions and 9 deletions

View File

@ -39,9 +39,8 @@ public class AuthResource {
@PostMapping( @PostMapping(
value="/login", value="/login",
produces="application/json") produces="application/json")
public ResponseEntity<LoginResponse> login(@RequestBody LoginUserDto userDto) public ResponseEntity<LoginResponse> login(@RequestBody LoginUserDto userDto) throws BadRequestException {
{ User authenticatedUser = accountService.authenticate(userDto);
User authenticatedUser = accountService.login(userDto);
String jwtToken = jwtService.generateToken(authenticatedUser); String jwtToken = jwtService.generateToken(authenticatedUser);

View File

@ -10,5 +10,5 @@ public interface AccountService
User register(RegisterUserDto user) throws BadRequestException; User register(RegisterUserDto user) throws BadRequestException;
User login(LoginUserDto user); User authenticate(LoginUserDto user) throws BadRequestException;
} }

View File

@ -71,15 +71,35 @@ public class AccountServiceImpl implements AccountService {
} }
@Override @Override
public User login(LoginUserDto user) { public User authenticate(LoginUserDto userDto) throws BadRequestException {
if (userDto.getEmail() == null ||
userDto.getEmail().isEmpty() ||
userDto.getPassword() == null ||
userDto.getPassword().isEmpty()) {
throw new BadRequestException("Please provide a valid email and password");
}
if(!userDto.getEmail().matches(InternalConfiguration.EMAIL_REGEX_RCF)) {
throw new BadRequestException("Invalid email format");
}
if(!userDto.getPassword().matches(InternalConfiguration.PASSWORD_REGEX)) {
throw new BadRequestException("Invalid password format");
}
if (!userRepository.findByEmail(userDto.getEmail()).isPresent()) {
throw new BadRequestException("No account registered with this email");
}
authenticationManager.authenticate( authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken( new UsernamePasswordAuthenticationToken(
user.getEmail(), userDto.getEmail(),
user.getPassword())); userDto.getPassword()));
return userRepository.findByEmail(user.getEmail()) return userRepository.findByEmail(userDto.getEmail())
.orElseThrow(); .orElseThrow();
} }
} }