Refactor user registration and update handling; modify UserController for putUser endpoint and enhance application properties
This commit is contained in:
parent
3d3549a39f
commit
e5d5c63763
|
|
@ -25,7 +25,7 @@ public class SecurityConfig {
|
|||
.requestMatchers("/css/**", "/js/**", "/images/**").permitAll() // Permitir acceso a CSS, JS e imágenes
|
||||
.requestMatchers("/admin/**").hasRole("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()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
|
|
|
|||
|
|
@ -27,11 +27,11 @@ import java.util.*;
|
|||
public class UserController {
|
||||
@Autowired
|
||||
private ApplicationContext context;
|
||||
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
|
||||
|
||||
private final UserService userService;
|
||||
private final DepartamentoService departamentoService;
|
||||
private final CategoriaService categoriaService;
|
||||
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
|
||||
private final BotonManager botonManager;
|
||||
public UserController(UserService userService, DepartamentoService departamentoService, CategoriaService categoriaService, BotonManager botonManager) {
|
||||
this.userService = userService;
|
||||
|
|
@ -110,14 +110,44 @@ public class UserController {
|
|||
return "userPage";
|
||||
}
|
||||
|
||||
// POST: Registrar nuevo usuario
|
||||
@PostMapping("/register")
|
||||
public String registerUser(@RequestParam String username,
|
||||
@PostMapping("/putUser")
|
||||
public String putUser(@RequestParam String nombre,
|
||||
@RequestParam String password,
|
||||
@RequestParam String role,
|
||||
@RequestParam String mail,
|
||||
@RequestParam(required = false) Integer iddepartamento,
|
||||
@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;
|
||||
if (iddepartamento != null) {
|
||||
departamento = departamentoService.getDepartamentoById(iddepartamento);
|
||||
|
|
@ -128,20 +158,10 @@ public class UserController {
|
|||
} catch (IllegalArgumentException e) {
|
||||
throw new RuntimeException("Rol no válido: " + role);
|
||||
}
|
||||
if (id != null) {
|
||||
User Old = userService.getUserById(id);
|
||||
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
|
||||
userService.registerUser(nombre, password, userRole.toString(), mail, departamento);
|
||||
return "redirect:/user_list";
|
||||
}
|
||||
|
||||
@PostMapping("/delete_user")
|
||||
public String deleteUser(@RequestParam("id") Long id) {
|
||||
User user = userService.getUserById(id);
|
||||
|
|
@ -230,68 +250,7 @@ public class UserController {
|
|||
|
||||
return "list";
|
||||
}
|
||||
|
||||
|
||||
//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;
|
||||
}
|
||||
}
|
||||
**/
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -3,7 +3,6 @@ package com.ieslamar.GestionInventario.services;
|
|||
import com.ieslamar.GestionInventario.entities.Departamento;
|
||||
import com.ieslamar.GestionInventario.entities.Role;
|
||||
import com.ieslamar.GestionInventario.entities.User;
|
||||
import com.ieslamar.GestionInventario.repos.GenericEntityService;
|
||||
import com.ieslamar.GestionInventario.repos.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
|
@ -11,9 +10,10 @@ import org.springframework.stereotype.Repository;
|
|||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class UserService implements GenericEntityService<User> {
|
||||
public class UserService {
|
||||
@Autowired
|
||||
public UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
|
@ -44,28 +44,18 @@ public class UserService implements GenericEntityService<User> {
|
|||
return userRepository.findAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> findAll() {
|
||||
return userRepository.findAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getHeaders() {
|
||||
return List.of("ID", "Nombre", "Rol", "Email", "Departamento");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Object> getRowValues(User user) {
|
||||
return List.of(
|
||||
user.getId(),
|
||||
user.getNombre(),
|
||||
user.getRole(),
|
||||
user.getMail(),
|
||||
user.getDepartamento() != null ? user.getDepartamento().getNombre() : " "
|
||||
);
|
||||
}
|
||||
|
||||
public void saveUser(User user) {
|
||||
userRepository.save(user);
|
||||
public void updateUser(Long id, User user){
|
||||
User original = userRepository.findById(id).orElse(null);
|
||||
if(!original.getNombre().equals(user.getNombre()))
|
||||
original.setNombre(user.getNombre());
|
||||
if(!original.getMail().equals(user.getMail()))
|
||||
original.setMail(user.getMail());
|
||||
if(user.getPassword()!= null)
|
||||
original.setPassword(passwordEncoder.encode(user.getPassword()));
|
||||
if(!original.getRole().equals(user.getRole()))
|
||||
original.setRole(user.getRole());
|
||||
if(!Objects.equals(original.getDepartamento(), user.getDepartamento()))
|
||||
original.setDepartamento(user.getDepartamento());
|
||||
userRepository.save(original);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,6 @@ spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
|||
# Configuración de JPA e Hibernate
|
||||
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
|
||||
spring.jpa.hibernate.ddl-auto=validate
|
||||
|
||||
|
||||
spring.jpa.show-sql=true
|
||||
org.hibernate.SQL=DEBUG
|
||||
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -7,8 +7,9 @@
|
|||
<body>
|
||||
<h2>Registro</h2>
|
||||
<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:if="*{id != null}" th:field="*{id}" />
|
||||
<div class="input-group">
|
||||
<label>Usuario:</label>
|
||||
<input type="text" th:field="*{nombre}" required>
|
||||
|
|
@ -31,11 +32,12 @@
|
|||
</div>
|
||||
<div class="input-group">
|
||||
<label for="departamento">Departamento:</label>
|
||||
<select th:field="*{departamento.id}">
|
||||
<select name="iddepartamento" th:value="${user.departamento?.id}">
|
||||
<option value="">-- Sin departamento --</option>
|
||||
<option th:each="departamento : ${departamentos}"
|
||||
th:value="${departamento.id}"
|
||||
th:text="${departamento.nombre}">
|
||||
th:text="${departamento.nombre}"
|
||||
th:selected="${departamento.id == user.departamento?.id}">
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Reference in New Issue