#29 One-Time Code Authentication Controller
Perform a code review of the controller:
@RestController
public class SessionController {
@Autowired
UserRepository userRepository;
@GetMapping("/session")
private void getSession(@RequestParam Integer userId) {
Optional<User> user = userRepository.findById(userId);
String code = UUID.randomUUID().toString().substring(0, 6);
if (user.isPresent()) {
user.get().setConfirmationCode(code);
MailSenderUtil.sendEmail(user.get().getEmail(), "Enter code: " + code);
userRepository.save(user.get());
} else {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "User not found");
}
}
@PostMapping("/session/confirm")
private User confirmSession(@RequestParam Integer userId, @RequestParam String code) {
Optional<User> user = userRepository.findById(userId);
String session = UUID.randomUUID().toString();
if (user.isPresent()) {
if (code.equals(user.get().getConfirmationCode())) {
user.get().setSession(session);
userRepository.save(user.get());
return user.get();
} else {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Wrong code");
}
} else {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "User not found");
}
}
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor