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