Admin is able to set role and change display name to anyone

This commit is contained in:
Dmitry Isaenko 2024-01-02 20:02:25 +03:00
parent be50438b7a
commit 5d3664d148
5 changed files with 80 additions and 36 deletions

View file

@ -1,6 +1,6 @@
package ru.redrise.marinesco;
import java.util.Collections;
import java.util.List;
import org.springframework.security.crypto.password.PasswordEncoder;
@ -8,7 +8,6 @@ import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import ru.redrise.marinesco.data.RolesRepository;
import ru.redrise.marinesco.security.UserRole;
//TODO: refactor along with RegistrationForm.java
@ -27,13 +26,15 @@ public class AdministatorAddUserForm {
@NotEmpty(message = "Display name could not be blank")
private String displayname;
private UserRole role;
@NotNull
@Size(min=1, message="You must choose at least 1 role")
private List<UserRole> athorities;
public User toUser(PasswordEncoder passwordEncoder){
return new User(
username,
passwordEncoder.encode(password),
displayname,
Collections.singletonList(role));
athorities);
}
}

View file

@ -2,7 +2,6 @@ package ru.redrise.marinesco;
import java.util.List;
import org.hibernate.annotations.ManyToAny;
import org.springframework.security.core.userdetails.UserDetails;
import jakarta.persistence.Column;
@ -37,7 +36,7 @@ public class User implements UserDetails{
private String displayname;
@ManyToMany(fetch = FetchType.EAGER)
private final List<UserRole> authorities;
private List<UserRole> authorities;
public User(String username, String password, String displayname, List<UserRole> authorities){
this.username = username;
@ -66,11 +65,19 @@ public class User implements UserDetails{
return true;
}
public void setRole(UserRole role){ // TODO
public void addRole(UserRole role){
this.authorities.add(role);
}
public void removeRole(UserRole role){
this.authorities.remove(role);
}
public boolean isAdmin(){
return authorities.get(0).getAuthority().equals("ROLE_ADMIN");
for (UserRole athority : authorities){
if (athority.getAuthority().equals("ROLE_ADMIN"))
return true;
}
return false;
}
}

View file

@ -1,6 +1,7 @@
package ru.redrise.marinesco;
import java.util.List;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.NoArgsConstructor;
@ -16,12 +17,16 @@ public class UserGenerified {
private String name;
private String displayName;
private List<UserRole> role;
private List<UserRole> athorities;
private List<UserRole> athoritiesLost;
public UserGenerified(User user){
public UserGenerified(User user, List<UserRole> allRolesList){
this.id = user.getId();
this.name = user.getUsername();
this.displayName = user.getDisplayname();
this.role = user.getAuthorities();
this.athorities = user.getAuthorities();
athoritiesLost = allRolesList.stream()
.filter(element -> !athorities.contains(element))
.collect(Collectors.toList());
}
}

View file

@ -10,6 +10,7 @@ import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -21,7 +22,6 @@ import ru.redrise.marinesco.UserGenerified;
import ru.redrise.marinesco.data.RolesRepository;
import ru.redrise.marinesco.data.UserRepository;
//TODO
@Slf4j
@Controller
@RequestMapping("/manage_users")
@ -55,15 +55,19 @@ public class ManageUsersController {
public void addUsers(Model model) {
Iterable<User> users = userRepository.findAll();
List<UserGenerified> usersGen = new ArrayList<>();
List<UserRole> allRolesList = new ArrayList<>();
rolesRepository.findAll().forEach(allRolesList::add);
for (User user : users) {
usersGen.add(new UserGenerified(user));
usersGen.add(new UserGenerified(user, allRolesList));
}
model.addAttribute("USR", usersGen);
model.addAttribute("users", usersGen);
}
@ModelAttribute
public void addRoles(Model model) {
Iterable<UserRole> roles = rolesRepository.findAll();
model.addAttribute("roles", roles);
model.addAttribute("rolesSet", roles);
}
@GetMapping
@ -71,11 +75,27 @@ public class ManageUsersController {
return "manage_users";
}
@PostMapping("/delete")
public String processDelete(UserGenerified userGenerified) {
log.info(userGenerified.toString());
@GetMapping("/delete/{id}")
public String delete(@PathVariable("id") String id) {
try {
long userId = Long.parseLong(id);
userRepository.deleteById(userId);
} catch (Exception e) {
log.error(id, e);
}
userRepository.deleteById(userGenerified.getId());
return "redirect:/manage_users";
}
@PostMapping("/update")
public String updateRoles(UserGenerified userGenerified) {
User user = userRepository.findById(userGenerified.getId()).get();
if (user == null)
return "redirect:/manage_users";
user.setAuthorities(userGenerified.getAthorities());
user.setDisplayname(userGenerified.getDisplayName());
userRepository.save(user);
return "redirect:/manage_users";
}
@ -92,7 +112,8 @@ public class ManageUsersController {
}
User user = userRepository.save(form.toUser(passwordEncoder));
log.info("Added user {} {} {}", user.getId(), user.getUsername(), user.getDisplayname(), user.getAuthorities().get(0));
log.info("Added user {} {} {}", user.getId(), user.getUsername(), user.getDisplayname(),
user.getAuthorities().get(0));
// Reloads page therefore new records appears
return "redirect:/manage_users";
}

View file

@ -14,22 +14,29 @@
<div class="container base">
<h1 th:text="${header_text}"></h1>
<p>
<div th:each="user : ${USR}">
<span th:text="${user.id+' '+user.name+' '+user.displayName}+' ROLES: '">user</span>
<span th:each="role : ${user.role}">
<span th:text="'[ '+${role.id+' '+role.name+' '+role.type}+' ]'">user</span>
</span>
<form method="POST" th:action="@{/manage_users/delete}" th:object="${userGenerified}">
<div th:each="user : ${users}">
<form method="POST" th:action="@{/manage_users/update}" th:object="${userGenerified}">
<span th:text="${user.id + '. '}"></span>
<span th:text="${user.name}"></span>
<input type="hidden" th:value="${user.id}" name="id" />
<input type="hidden" th:value="${user.name}" name="name" />
<input type="hidden" th:value="${user.displayName}" name="displayName" />
<span th:each="role : ${user.role}">
<input type="hidden" th:value="${role.id}" th:attr="name='role'" />
</span>
<br />
Display name:
<input type="text" th:value="${user.displayName}" name="displayName" />
<br /><br /><b>Roles:</b>
<div th:each="athorities : ${user.athorities}">
<input name="athorities" type="checkbox" th:value="${athorities.id}" th:checked="true" />
<span th:text="${athorities.name}"></span><br />
</div>
<div th:each="athorities : ${user.athoritiesLost}">
<input name="athorities" type="checkbox" th:value="${athorities.id}" />
<span th:text="${athorities.name}"></span><br />
</div>
<button>Delete</button>
<button>Update</button><a th:href="'/manage_users/delete/' + ${user.id}">Delete</a>
</form>
<br />
<hr>
</div>
<hr>
<b>Add user</b>
@ -53,10 +60,13 @@
<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>
<b>Roles:</b>
<br />
<span class="validationError" th:if="${#fields.hasErrors('athorities')}" th:errors="*{athorities}"></span>
<div th:each="athorities : ${rolesSet}">
<input th:field="*{athorities}" type="checkbox" th:value="${athorities.id}" />
<span th:text="${athorities.name}"></span><br />
</div>
<p>
<button class="sign" type="submit">Add user</button>