|
| 1 | +package org.openpodcastapi.opa.ui.controller; |
| 2 | + |
| 3 | +import jakarta.validation.Valid; |
| 4 | +import lombok.RequiredArgsConstructor; |
| 5 | +import lombok.extern.log4j.Log4j2; |
| 6 | +import org.openpodcastapi.opa.user.dto.CreateUserDto; |
| 7 | +import org.openpodcastapi.opa.user.service.UserService; |
| 8 | +import org.springframework.dao.DataIntegrityViolationException; |
| 9 | +import org.springframework.stereotype.Controller; |
| 10 | +import org.springframework.ui.Model; |
| 11 | +import org.springframework.validation.BindingResult; |
| 12 | +import org.springframework.web.bind.annotation.GetMapping; |
| 13 | +import org.springframework.web.bind.annotation.ModelAttribute; |
| 14 | +import org.springframework.web.bind.annotation.PostMapping; |
| 15 | +import org.springframework.web.bind.annotation.RequestParam; |
| 16 | + |
| 17 | +@Controller |
| 18 | +@Log4j2 |
| 19 | +@RequiredArgsConstructor |
| 20 | +public class AuthController { |
| 21 | + private static final String USER_REQUEST_ATTRIBUTE = "createUserRequest"; |
| 22 | + private static final String REGISTER_TEMPLATE = "auth/register"; |
| 23 | + private final UserService userService; |
| 24 | + |
| 25 | + // === Login page === |
| 26 | + @GetMapping("/login") |
| 27 | + public String loginPage(@RequestParam(value = "error", required = false) String error, |
| 28 | + Model model) { |
| 29 | + if (error != null) { |
| 30 | + model.addAttribute("loginError", true); |
| 31 | + } |
| 32 | + return "auth/login"; |
| 33 | + } |
| 34 | + |
| 35 | + // === Logout confirmation page === |
| 36 | + @GetMapping("/logout-confirm") |
| 37 | + public String logoutPage() { |
| 38 | + return "auth/logout"; |
| 39 | + } |
| 40 | + |
| 41 | + // === Registration page === |
| 42 | + @GetMapping("/register") |
| 43 | + public String getRegister(Model model) { |
| 44 | + model.addAttribute(USER_REQUEST_ATTRIBUTE, new CreateUserDto("", "", "")); |
| 45 | + return REGISTER_TEMPLATE; |
| 46 | + } |
| 47 | + |
| 48 | + // === Registration POST handler === |
| 49 | + @PostMapping("/register") |
| 50 | + public String processRegistration( |
| 51 | + @Valid @ModelAttribute CreateUserDto createUserRequest, |
| 52 | + BindingResult result, |
| 53 | + Model model |
| 54 | + ) { |
| 55 | + if (result.hasErrors()) { |
| 56 | + model.addAttribute(USER_REQUEST_ATTRIBUTE, createUserRequest); |
| 57 | + return REGISTER_TEMPLATE; |
| 58 | + } |
| 59 | + |
| 60 | + try { |
| 61 | + userService.createAndPersistUser(createUserRequest); |
| 62 | + } catch (DataIntegrityViolationException _) { |
| 63 | + result.rejectValue("username", "", "Username or email already exists"); |
| 64 | + model.addAttribute(USER_REQUEST_ATTRIBUTE, createUserRequest); |
| 65 | + return REGISTER_TEMPLATE; |
| 66 | + } |
| 67 | + |
| 68 | + return "redirect:/login?registered"; |
| 69 | + } |
| 70 | +} |
0 commit comments