I'm writting a registration feature currently and I I'm confused how to divide logic between layers. Can you review this code and tell if it's good way to do? In try-catch block I publish event to send verification email to new User.
Should I keep in my Controller class just
AuthService
field? I'm usinguserRepository
to check if username and email is available.In
AuthService
should I keep justauthRepository
and other services fields? Currently I'm using thereRoleRepository
.Is return type in my controller a good practise?
ApiRespose
is two-field class.
Controller:
@PostMapping("/signup")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRequest, HttpServletRequest httpServletRequest) {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
return new ResponseEntity(new ApiResponse(false, "Username is already in use!"), HttpStatus.BAD_REQUEST);
}
if (userRepository.existsByEmail(signUpRequest.getEmail())) {
return new ResponseEntity(new ApiResponse(false, "Email is already in use!"), HttpStatus.BAD_REQUEST);
}
User user = new User(signUpRequest.getName(), signUpRequest.getUsername(), signUpRequest.getEmail(), signUpRequest.getPassword());
User resultUser = authService.createUser(user);
try {
String host = httpServletRequest.getHeader("apphost");
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(resultUser, host));
} catch (Exception e) {
e.printStackTrace();
}
URI location = ServletUriComponentsBuilder
.fromCurrentContextPath().path("/users/{username}")
.buildAndExpand(resultUser.getUsername()).toUri();
return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully"));
}
Service:
@Override
public User createUser(User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
.orElseThrow(() -> new AppException("User Role not set."));
user.setRoles(Collections.singleton(userRole));
return userService.saveRegisteredUser(user);
}