Refactor user registration and update handling; modify UserController for putUser endpoint and enhance application properties

This commit is contained in:
jon ander 2025-05-09 19:23:04 +02:00
parent 3d3549a39f
commit e5d5c63763
7 changed files with 60 additions and 120 deletions

View File

@ -25,7 +25,7 @@ public class SecurityConfig {
.requestMatchers("/css/**", "/js/**", "/images/**").permitAll() // Permitir acceso a CSS, JS e imágenes .requestMatchers("/css/**", "/js/**", "/images/**").permitAll() // Permitir acceso a CSS, JS e imágenes
.requestMatchers("/admin/**").hasRole("ADMIN") .requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN") .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.requestMatchers("/management", "/user_management","/user_list","/departamento_list","/userPage").hasRole("ADMIN") .requestMatchers("/management", "/user_management","/user_list","/departamento_list","/userPage","/putUser").hasRole("ADMIN")
.requestMatchers("/", "/login").permitAll() .requestMatchers("/", "/login").permitAll()
.anyRequest().authenticated() .anyRequest().authenticated()
) )

View File

@ -27,11 +27,11 @@ import java.util.*;
public class UserController { public class UserController {
@Autowired @Autowired
private ApplicationContext context; private ApplicationContext context;
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
private final UserService userService; private final UserService userService;
private final DepartamentoService departamentoService; private final DepartamentoService departamentoService;
private final CategoriaService categoriaService; private final CategoriaService categoriaService;
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
private final BotonManager botonManager; private final BotonManager botonManager;
public UserController(UserService userService, DepartamentoService departamentoService, CategoriaService categoriaService, BotonManager botonManager) { public UserController(UserService userService, DepartamentoService departamentoService, CategoriaService categoriaService, BotonManager botonManager) {
this.userService = userService; this.userService = userService;
@ -110,14 +110,44 @@ public class UserController {
return "userPage"; return "userPage";
} }
// POST: Registrar nuevo usuario @PostMapping("/putUser")
@PostMapping("/register") public String putUser(@RequestParam String nombre,
public String registerUser(@RequestParam String username,
@RequestParam String password, @RequestParam String password,
@RequestParam String role, @RequestParam String role,
@RequestParam String mail, @RequestParam String mail,
@RequestParam(required = false) Integer iddepartamento, @RequestParam(required = false) Integer iddepartamento,
@RequestParam(required = false) Long id) { @RequestParam(required = false) Long id) {
logger.info("entra en putUser");
if(id == null)
return registerUser(nombre,password,role,mail,iddepartamento);
return updateUser(id,nombre,password,role,mail,iddepartamento);
}
private String updateUser(Long id,String nombre,String password,String role,String mail, Integer iddepartamento){
logger.info(" entra en updateUser jjknnjn");
Departamento departamento = null;
User user = new User();
if (iddepartamento != null) {
departamento = departamentoService.getDepartamentoById(iddepartamento);
}
user.setNombre(nombre);
user.setPassword(password);
Role userRole;
try {
userRole = Role.valueOf(role.toUpperCase());
} catch (IllegalArgumentException e) {
throw new RuntimeException("Rol no válido: " + role);
}
user.setRole(userRole);
user.setMail(mail);
user.setDepartamento(departamento);
userService.updateUser(id,user);
return "redirect:/user_list";
}
private String registerUser(String nombre,String password,String role,String mail, Integer iddepartamento) {
logger.info("entra en registerUser");
Departamento departamento = null; Departamento departamento = null;
if (iddepartamento != null) { if (iddepartamento != null) {
departamento = departamentoService.getDepartamentoById(iddepartamento); departamento = departamentoService.getDepartamentoById(iddepartamento);
@ -128,20 +158,10 @@ public class UserController {
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new RuntimeException("Rol no válido: " + role); throw new RuntimeException("Rol no válido: " + role);
} }
if (id != null) { userService.registerUser(nombre, password, userRole.toString(), mail, departamento);
User Old = userService.getUserById(id); return "redirect:/user_list";
Old.setNombre(username);
if(password != null)
Old.setPassword(password);
Old.setRole(Role.valueOf(role));
Old.setMail(mail);
Old.setDepartamento(departamento);
userService.saveUser(Old);
} else {
userService.registerUser(username, password, userRole.toString(), mail, departamento);
}
return "redirect:/user_list"; // redirige a lista o página deseada
} }
@PostMapping("/delete_user") @PostMapping("/delete_user")
public String deleteUser(@RequestParam("id") Long id) { public String deleteUser(@RequestParam("id") Long id) {
User user = userService.getUserById(id); User user = userService.getUserById(id);
@ -230,68 +250,7 @@ public class UserController {
return "list"; return "list";
} }
//GENERICO-------------------------------------------------------------------------------------------------------- //GENERICO--------------------------------------------------------------------------------------------------------
/**
@GetMapping("/list/{tabla}")
public String tablaList(Model model, @PathVariable String entity) {
String serviceName = entity.toLowerCase() + "Service";
Object serviceBean = context.getBean(serviceName);
return "";
}
@GetMapping("/list/{entity}")
public String entityList(Model model, @PathVariable String entity) {
//construye el nombre del servicio de la entidad
String serviceName = entity.toLowerCase() + "Service";
try {
//busca el servicio de la entidad
Object serviceBean = context.getBean(serviceName);
//si el Bean es una instancia de GenericEntityService
if (serviceBean instanceof GenericEntityService<?> genericService) {
//genericService es un Servicio de los que hay, eso trae todas las instancias, entities sería por ejemplo user,categoria,etc
List<?> entities = genericService.findAll();
List<Map<String, Object>> items = entities.stream().map(e ->
Map.of(
"id", getId(e),
"values", genericService.getRowValues(e)
)
).toList();
model.addAttribute("title", "Gestión de " + entity);
model.addAttribute("headers", genericService.getHeaders());
model.addAttribute("items", items);
model.addAttribute("actionsUrl", Map.of(
"edit", "",
"delete", "" // puedes personalizar por entidad
));
model.addAttribute("backUrl", "/Inventario/home");
model.addAttribute("addUrl", "/Inventario/");
return "list";
} else {
throw new IllegalArgumentException("No es un GenericEntityService válido");
}
} catch (Exception e) {
model.addAttribute("error", "No se pudo cargar la entidad: " + entity);
return "error";
}
}
private Object getId(Object entity) {
try {
Method method = entity.getClass().getMethod("getId");
return method.invoke(entity);
} catch (Exception e) {
return null;
}
}
**/
} }

View File

@ -1,11 +0,0 @@
package com.ieslamar.GestionInventario.repos;
import com.ieslamar.GestionInventario.entities.User;
import java.util.List;
public interface GenericEntityService<T> {
List<T> findAll();
List<String> getHeaders();
List<Object> getRowValues(T entity);
}

View File

@ -3,7 +3,6 @@ package com.ieslamar.GestionInventario.services;
import com.ieslamar.GestionInventario.entities.Departamento; import com.ieslamar.GestionInventario.entities.Departamento;
import com.ieslamar.GestionInventario.entities.Role; import com.ieslamar.GestionInventario.entities.Role;
import com.ieslamar.GestionInventario.entities.User; import com.ieslamar.GestionInventario.entities.User;
import com.ieslamar.GestionInventario.repos.GenericEntityService;
import com.ieslamar.GestionInventario.repos.UserRepository; import com.ieslamar.GestionInventario.repos.UserRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
@ -11,9 +10,10 @@ import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
import java.util.Objects;
@Service @Service
public class UserService implements GenericEntityService<User> { public class UserService {
@Autowired @Autowired
public UserRepository userRepository; public UserRepository userRepository;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
@ -44,28 +44,18 @@ public class UserService implements GenericEntityService<User> {
return userRepository.findAll(); return userRepository.findAll();
} }
@Override public void updateUser(Long id, User user){
public List<User> findAll() { User original = userRepository.findById(id).orElse(null);
return userRepository.findAll(); if(!original.getNombre().equals(user.getNombre()))
} original.setNombre(user.getNombre());
if(!original.getMail().equals(user.getMail()))
@Override original.setMail(user.getMail());
public List<String> getHeaders() { if(user.getPassword()!= null)
return List.of("ID", "Nombre", "Rol", "Email", "Departamento"); original.setPassword(passwordEncoder.encode(user.getPassword()));
} if(!original.getRole().equals(user.getRole()))
original.setRole(user.getRole());
@Override if(!Objects.equals(original.getDepartamento(), user.getDepartamento()))
public List<Object> getRowValues(User user) { original.setDepartamento(user.getDepartamento());
return List.of( userRepository.save(original);
user.getId(),
user.getNombre(),
user.getRole(),
user.getMail(),
user.getDepartamento() != null ? user.getDepartamento().getNombre() : " "
);
}
public void saveUser(User user) {
userRepository.save(user);
} }
} }

View File

@ -14,6 +14,6 @@ spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Configuración de JPA e Hibernate # Configuración de JPA e Hibernate
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=validate spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
org.hibernate.SQL=DEBUG

View File

@ -7,8 +7,9 @@
<body> <body>
<h2>Registro</h2> <h2>Registro</h2>
<div class="container1"> <div class="container1">
<form th:action="@{/register}" th:object="${user}" method="post"> <form th:action="@{/putUser}" th:object="${user}" method="post">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/> <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<input type="hidden" th:if="*{id != null}" th:field="*{id}" />
<div class="input-group"> <div class="input-group">
<label>Usuario:</label> <label>Usuario:</label>
<input type="text" th:field="*{nombre}" required> <input type="text" th:field="*{nombre}" required>
@ -31,11 +32,12 @@
</div> </div>
<div class="input-group"> <div class="input-group">
<label for="departamento">Departamento:</label> <label for="departamento">Departamento:</label>
<select th:field="*{departamento.id}"> <select name="iddepartamento" th:value="${user.departamento?.id}">
<option value="">-- Sin departamento --</option> <option value="">-- Sin departamento --</option>
<option th:each="departamento : ${departamentos}" <option th:each="departamento : ${departamentos}"
th:value="${departamento.id}" th:value="${departamento.id}"
th:text="${departamento.nombre}"> th:text="${departamento.nombre}"
th:selected="${departamento.id == user.departamento?.id}">
</option> </option>
</select> </select>
</div> </div>