From be50438b7a2d552c4af6dcc32bba657bc379b071 Mon Sep 17 00:00:00 2001 From: Dmitry Isaenko Date: Mon, 1 Jan 2024 17:28:30 +0300 Subject: [PATCH] Add role selector to Manage Users page --- .../ru/redrise/marinesco/AdministatorAddUserForm.java | 8 ++++++-- .../marinesco/security/ManageUsersController.java | 9 +++++++-- src/main/resources/templates/manage_users.html | 6 ++++++ 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/main/java/ru/redrise/marinesco/AdministatorAddUserForm.java b/src/main/java/ru/redrise/marinesco/AdministatorAddUserForm.java index 57ed0b8..68929bb 100644 --- a/src/main/java/ru/redrise/marinesco/AdministatorAddUserForm.java +++ b/src/main/java/ru/redrise/marinesco/AdministatorAddUserForm.java @@ -1,5 +1,7 @@ package ru.redrise.marinesco; +import java.util.Collections; + import org.springframework.security.crypto.password.PasswordEncoder; import jakarta.validation.constraints.NotEmpty; @@ -25,11 +27,13 @@ public class AdministatorAddUserForm { @NotEmpty(message = "Display name could not be blank") private String displayname; - public User toUser(PasswordEncoder passwordEncoder, RolesRepository rolesRepo){ + private UserRole role; + + public User toUser(PasswordEncoder passwordEncoder){ return new User( username, passwordEncoder.encode(password), displayname, - rolesRepo.findByType(UserRole.Type.USER)); + Collections.singletonList(role)); } } diff --git a/src/main/java/ru/redrise/marinesco/security/ManageUsersController.java b/src/main/java/ru/redrise/marinesco/security/ManageUsersController.java index 43d0fff..4bb49f0 100644 --- a/src/main/java/ru/redrise/marinesco/security/ManageUsersController.java +++ b/src/main/java/ru/redrise/marinesco/security/ManageUsersController.java @@ -60,6 +60,11 @@ public class ManageUsersController { } model.addAttribute("USR", usersGen); } + @ModelAttribute + public void addRoles(Model model) { + Iterable roles = rolesRepository.findAll(); + model.addAttribute("roles", roles); + } @GetMapping public String getPage() { @@ -86,8 +91,8 @@ public class ManageUsersController { return "manage_users"; } - User user = userRepository.save(form.toUser(passwordEncoder, rolesRepository)); - log.info("Added user {} {} {}", user.getId(), user.getUsername(), user.getDisplayname()); + User user = userRepository.save(form.toUser(passwordEncoder)); + log.info("Added user {} {} {}", user.getId(), user.getUsername(), user.getDisplayname(), user.getAuthorities().get(0)); // Reloads page therefore new records appears return "redirect:/manage_users"; } diff --git a/src/main/resources/templates/manage_users.html b/src/main/resources/templates/manage_users.html index f985b87..3c75d9f 100644 --- a/src/main/resources/templates/manage_users.html +++ b/src/main/resources/templates/manage_users.html @@ -52,6 +52,12 @@
+
+ + +