package com.ieslamar.GestionInventario.controllers; import com.ieslamar.GestionInventario.dto.BotonDTO; import com.ieslamar.GestionInventario.entities.User; 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; import java.util.List; @Controller public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping("/login") public String loginPage() { return "login"; // Retorna la vista login.html } @GetMapping("/filtered-buttons") public String getFilteredButtons(Model model, Authentication authentication) { List botones = List.of( new BotonDTO("Inventario", "/management", false, null), new BotonDTO("Gestión", "/management", true, null) ); // Filtrar botones según el rol del usuario List 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() { return "register"; // Retorna la vista register.html } @PostMapping("/register") public String register(@RequestParam String username, @RequestParam String password, @RequestParam String role, @RequestParam String mail) { userService.registerUser(username, password, role, mail, null); return "redirect:/login?success"; // Redirige al login tras registrarse } @GetMapping("/management") public String managementPage(){ return "management"; } @GetMapping("/user_management") public String listUsers(Model model) { List users = userService.getAllUsers(); model.addAttribute("users", users); return "user_management"; } @GetMapping("/delete_user") public String deleteUser(@RequestParam Long id) { User user = userService.getUserById(id); if (user != null) { userService.deleteUser(user); } return "redirect:/user_management"; } }