Show nice error message if username already exists

Closes #35
This commit is contained in:
Denis Natusch 2023-11-19 17:52:41 +01:00
parent 60644a74b3
commit 56cf10af8c
No known key found for this signature in database
GPG key ID: 5E57BD8EDACFA985
3 changed files with 18 additions and 3 deletions

View file

@ -35,12 +35,18 @@ public class UserController {
} }
@PostMapping("/register") @PostMapping("/register")
String register(@Valid RegistrationForm form, Errors result) { String register(@Valid RegistrationForm form, Errors result, Model model) {
if (result.hasErrors()){ if (result.hasErrors()){
return "register"; return "register";
} }
userManagement.createCustomer(form.getUsername(),form.getAddress(),form.getPassword()); if (userManagement.userNameExists(form.getUsername())) {
return "redirect:/login"; model.addAttribute("userNameExists",true);
return "register";
} else {
model.addAttribute("userNameExists",false);
userManagement.createCustomer(form.getUsername(),form.getAddress(),form.getPassword());
return "redirect:/login";
}
} }
@GetMapping("/login") @GetMapping("/login")

View file

@ -51,4 +51,12 @@ public class UserManagement {
public Optional<User> getUserByAccount(UserAccount userAccount) { public Optional<User> getUserByAccount(UserAccount userAccount) {
return users.findAll().stream().filter(u -> u.getUserAccount().equals(userAccount)).findFirst(); return users.findAll().stream().filter(u -> u.getUserAccount().equals(userAccount)).findFirst();
} }
public boolean userNameExists(String username){
return !users.findAll().stream()
.filter(u -> u.getUsername().equals(username))
.toList()
.isEmpty();
}
} }

View file

@ -9,6 +9,7 @@
<div class="mb-3"> <div class="mb-3">
<label class="form-label" for="username">Nutzername</label> <label class="form-label" for="username">Nutzername</label>
<input class="form-control" name="username" type="text" required> <input class="form-control" name="username" type="text" required>
<p th:if="${userNameExists}">Nutzername vergeben</p>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label" for="password">Passwort</label> <label class="form-label" for="password">Passwort</label>