#29 One-Time Code Authentication Controller

Companies:
Lemana PRO
Themes:
SpringSpring BootCode Review

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

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in