Implement filtered button rendering based on user roles; update home page to use new endpoint for dynamic button display

This commit is contained in:
jon ander 2025-04-11 18:23:26 +02:00
parent d60b10f4d8
commit bde7cc3407
3 changed files with 27 additions and 49 deletions

View File

@ -7,6 +7,9 @@ import com.ieslamar.GestionInventario.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@ -27,15 +30,23 @@ public class UserController {
return "login"; // Retorna la vista login.html
}
@GetMapping("/home")
public String homePage(Model model) {
@GetMapping("/filtered-buttons")
public String getFilteredButtons(Model model, Authentication authentication) {
List<BotonDTO> botones = List.of(
new BotonDTO("Inventario", "/management", false, null),
new BotonDTO("Gestión", "/management", true, null)
);
model.addAttribute("buttons", botones);
// Filtrar botones según el rol del usuario
List<BotonDTO> filteredButtons = botones.stream()
.filter(button -> !button.isRequireAdmin() ||
(authentication != null && authentication.getAuthorities().stream()
.anyMatch(auth -> auth.getAuthority().equals("ROLE_ADMIN"))))
.toList();
model.addAttribute("buttons", filteredButtons);
return "home"; // Retorna la vista home.html
}
}
@GetMapping("/register")
public String registerPage() {

View File

@ -5,23 +5,15 @@
<div th:fragment="buttonList(buttons)">
<div class="container1">
<div th:each="button : ${buttons}">
<div th:if="${!button.isRequireAdmin()}">
<a th:href="@{${button.getUrl()}}">
<button th:class="${button.getCssClass()}" th:text="${button.getTexto()}"></button>
</a>
</div>
<div th:if="${button.isRequireAdmin()}">
<div sec:authorize="hasRole('ADMIN')">
<a th:href="@{${button.getUrl()}}">
<button th:class="${button.getCssClass()}" th:text="${button.getTexto()}"></button>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

View File

@ -1,25 +0,0 @@
<!DOCTYPE html>
<html lang="es" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.w3.org/1999/xhtml">
<body>
<div th:fragment="tableFragment(titulo, columnas, datos, acciones)">
<h2 th:text="${titulo}"></h2>
<div class="table-container">
<table class="table1">
<thead>
<tr>
<th th:each="columna : ${columnas}" th:text="${columna}"></th>
</tr>
</thead>
<tbody>
<tr th:each="fila : ${datos}">
<td th:each="celda : ${fila}" th:text="${celda}"></td>
<td th:if="${acciones}">
<button th:each="accion : ${acciones}" th:text="${accion.nombre}" th:onclick="${accion.evento}"></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>