Add role selector to Manage Users page

This commit is contained in:
Dmitry Isaenko 2024-01-01 17:28:30 +03:00
parent 4a1e62e6f8
commit be50438b7a
3 changed files with 19 additions and 4 deletions

View file

@ -1,5 +1,7 @@
package ru.redrise.marinesco; package ru.redrise.marinesco;
import java.util.Collections;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotEmpty;
@ -25,11 +27,13 @@ public class AdministatorAddUserForm {
@NotEmpty(message = "Display name could not be blank") @NotEmpty(message = "Display name could not be blank")
private String displayname; private String displayname;
public User toUser(PasswordEncoder passwordEncoder, RolesRepository rolesRepo){ private UserRole role;
public User toUser(PasswordEncoder passwordEncoder){
return new User( return new User(
username, username,
passwordEncoder.encode(password), passwordEncoder.encode(password),
displayname, displayname,
rolesRepo.findByType(UserRole.Type.USER)); Collections.singletonList(role));
} }
} }

View file

@ -60,6 +60,11 @@ public class ManageUsersController {
} }
model.addAttribute("USR", usersGen); model.addAttribute("USR", usersGen);
} }
@ModelAttribute
public void addRoles(Model model) {
Iterable<UserRole> roles = rolesRepository.findAll();
model.addAttribute("roles", roles);
}
@GetMapping @GetMapping
public String getPage() { public String getPage() {
@ -86,8 +91,8 @@ public class ManageUsersController {
return "manage_users"; return "manage_users";
} }
User user = userRepository.save(form.toUser(passwordEncoder, rolesRepository)); User user = userRepository.save(form.toUser(passwordEncoder));
log.info("Added user {} {} {}", user.getId(), user.getUsername(), user.getDisplayname()); log.info("Added user {} {} {}", user.getId(), user.getUsername(), user.getDisplayname(), user.getAuthorities().get(0));
// Reloads page therefore new records appears // Reloads page therefore new records appears
return "redirect:/manage_users"; return "redirect:/manage_users";
} }

View file

@ -52,6 +52,12 @@
<label for="displayname">Displayed name: </label> <label for="displayname">Displayed name: </label>
<input type="text" name="displayname" id="displayname" size="50%" /><br /> <input type="text" name="displayname" id="displayname" size="50%" /><br />
<br />
<label for="role">Role: </label>
<select name="role">
<option th:each="role : ${roles}" th:value="${role.id}" th:text="${role.name}" ></option>
</select>
<p> <p>
<button class="sign" type="submit">Add user</button> <button class="sign" type="submit">Add user</button>
</p> </p>