blob: a654ad13a91cc36867b0909d4b644ceb2dfaf49d (
plain)
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
|
package com.blog.web.controllers;
import com.blog.web.dto.RegistrationDto;
import com.blog.web.models.UserEntity;
import com.blog.web.security.SecurityUtil;
import com.blog.web.services.UserService;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
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;
@Controller
public class AuthController {
private UserService userService;
public AuthController(UserService userService) {
this.userService = userService;
}
@GetMapping("/userlogin")
public String login(Model model) {
UserEntity user = userService.getLoggedInUser();
model.addAttribute("user", user);
return "auth/login";
}
@GetMapping("/register")
public String getRegisterForm(Model model) {
final RegistrationDto user = new RegistrationDto();
model.addAttribute("user", user);
return "auth/register";
}
@PostMapping("/register/save")
public String register(@Valid @ModelAttribute("user")RegistrationDto user,
BindingResult result,
Model model) {
UserEntity existingUserEmail = userService.findByEmail(user.getEmail());
if(
existingUserEmail != null &&
StringUtils.isBlank(existingUserEmail.getEmail())
) {
result.rejectValue("email", "There is already a user with this email");
}
UserEntity existingUsername = userService.findByUsername(user.getUsername());
if(
existingUsername != null &&
StringUtils.isBlank(existingUsername.getUsername())
)
{
result.rejectValue("username", "There is already a user with this username");
}
if(result.hasErrors()) {
model.addAttribute("user", user);
return "register";
}
userService.saveUser(user);
return "redirect:/articles?success";
}
}
|