Add user registration page and update user management; implement departamento selection and modify security configuration

This commit is contained in:
jon ander 2025-04-15 17:32:13 +02:00
parent 1df99d3ea0
commit 81465b21ac
7 changed files with 94 additions and 25 deletions

View File

@ -11,13 +11,14 @@ import org.springframework.context.annotation.Configuration;
@Configuration
public class DataInitializer {
// @Bean
// public CommandLineRunner initData(UserService userService) {
// return args -> {
@Bean
public CommandLineRunner initData(UserService userService,DepartamentoService departamentoService) {
return args -> {
// userService.registerUser("Test","test123",Role.USER.name(),"test4@gmail.com",departamentoService.getDepartamentoById(1));
// userService.registerUser("admin", "admin123", Role.ADMIN.name(), "admin123@ejemplo.com",null);
// userService.registerUser("user", "user123", Role.USER.name(), "user123@ejemplo.com",null);
// };
// }
};
}
// @Bean
// public CommandLineRunner initData(DepartamentoService departamentoService) {

View File

@ -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", "/register","/user_list","/departamento_list").hasRole("ADMIN")
.requestMatchers("/management", "/user_management", "/register","/user_list","/departamento_list","/userPage").hasRole("ADMIN")
.requestMatchers("/", "/login").permitAll()
.anyRequest().authenticated()
)

View File

@ -2,6 +2,7 @@ package com.ieslamar.GestionInventario.controllers;
import com.ieslamar.GestionInventario.dto.BotonDTO;
import com.ieslamar.GestionInventario.entities.Departamento;
import com.ieslamar.GestionInventario.entities.User;
import com.ieslamar.GestionInventario.services.DepartamentoService;
import com.ieslamar.GestionInventario.services.UserService;
@ -13,6 +14,8 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.core.GrantedAuthority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
@ -26,6 +29,7 @@ public class UserController {
private final UserService userService;
private final DepartamentoService departamentoService;
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
public UserController(UserService userService, DepartamentoService departamentoService) {
this.userService = userService;
@ -66,7 +70,6 @@ public class UserController {
}
@GetMapping("/login")
public String loginPage() {
return "login"; // Retorna la vista login.html
@ -102,18 +105,26 @@ public class UserController {
}
@GetMapping("/register")
public String registerPage() {
return "register"; // Retorna la vista register.html
@GetMapping("/userPage")
public String userPage(Model model) {
model.addAttribute("departamentos",departamentoService.getAllDepartamentos());
return "userPage"; // 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);
@PostMapping("/userPage")
public String userPage(@RequestParam String username,
@RequestParam String password,
@RequestParam String role,
@RequestParam String mail,
@RequestParam(required = false) Integer iddepartamento
) {
Departamento departamento = null;
if(iddepartamento != null)
departamento = departamentoService.getDepartamentoById(iddepartamento);
userService.registerUser(username, password, role, mail, departamento);
return "redirect:/user_list"; // Redirige al login tras registrarse
}
@PostMapping("/delete_user")
public String deleteUser(@RequestParam("id") Long id) {
User user = userService.getUserById(id);
@ -125,11 +136,11 @@ public class UserController {
@GetMapping("/user_list")
public String genericPage(Model model) {
model.addAttribute("title", "Gestión de usuarios");
model.addAttribute("headers", List.of("ID", "Nombre", "Rol", "Email", "Acciones"));
model.addAttribute("headers", List.of("ID", "Nombre", "Rol", "Email","Departamento", "Acciones"));
model.addAttribute("items", userService.getAllUsers().stream()
.map(user -> Map.of(
"id", user.getId(),
"values", List.of(user.getId(), user.getNombre(), user.getRole(), user.getMail())
"values", List.of(user.getId(), user.getNombre(), user.getRole(), user.getMail(), user.getDepartamento() != null ? user.getDepartamento().getNombre() : " ")
))
.toList());
model.addAttribute("actionsUrl", Map.of(
@ -137,26 +148,28 @@ public class UserController {
"delete", "/delete_user"
));
model.addAttribute("backUrl", "/Inventario/home");
model.addAttribute("addUrl", "/Inventario/register");
model.addAttribute("addUrl", "/Inventario/userPage");
return "list";
}
@GetMapping("/departamento_list")
public String genericPageDepartamento(Model model) {
model.addAttribute("title", "Gestión Genérica");
model.addAttribute("title", "Gestión de Departamentos");
model.addAttribute("headers", List.of("ID", "Nombre","Acciones"));
model.addAttribute("items", departamentoService.getAllDepartamentos().stream()
.map(departamento -> Map.of(
"id", departamento.getId(),
"values", List.of(departamento.getId(), departamento.getNombre())
))
.toList());
model.addAttribute(
"items",
departamentoService.getAllDepartamentos().stream().map(departamento -> Map.of("id", departamento.getId(),
"values", List.of(departamento.getId(), departamento.getNombre()))).toList()
);
model.addAttribute("actionsUrl", Map.of(
"edit", "",
"delete", ""
));
model.addAttribute("backUrl", "/Inventario/home");
model.addAttribute("addUrl", "/Inventario/register");
model.addAttribute("addUrl", "/Inventario/");
return "list";
}

View File

@ -35,6 +35,8 @@ public class User {
@ManyToOne
@JoinColumn(name = "departamentos_iddepartamentos", nullable = true)
private Departamento departamento;
}

View File

@ -4,4 +4,5 @@ import com.ieslamar.GestionInventario.entities.Departamento;
import org.springframework.data.jpa.repository.JpaRepository;
public interface DepartamentoRepository extends JpaRepository<Departamento, Integer> {
}

View File

@ -1,6 +1,7 @@
package com.ieslamar.GestionInventario.services;
import com.ieslamar.GestionInventario.entities.Departamento;
import com.ieslamar.GestionInventario.entities.User;
import com.ieslamar.GestionInventario.repos.DepartamentoRepository;
import com.ieslamar.GestionInventario.repos.UserRepository;
import org.springframework.stereotype.Service;
@ -16,6 +17,9 @@ public class DepartamentoService {
public List<Departamento> getAllDepartamentos() {
return departamentoRepository.findAll();
}
public Departamento getDepartamentoById(Integer id) {
return departamentoRepository.findById(id).orElse(null);
}
public void registerDepartamento(String nombre) {
Departamento departamento = new Departamento();

View File

@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="es" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Registro</title>
<link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
<h2>Registro</h2>
<div class="container1">
<form th:action="@{/userPage}" method="post">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<div class="input-group">
<label>Usuario:</label>
<input type="text" name="username" required>
</div>
<div class="input-group">
<label>Contraseña:</label>
<input type="password" name="password" required>
</div>
<div class="input-group">
<label>Mail:</label>
<input type="text" name="mail" required>
</div>
<div class="input-group">
<label>Rol:</label>
<select name="role">
<option value="USER">Usuario</option>
<option value="ADMIN">Administrador</option>
</select>
</div>
<label for="departamento">Departamento:</label>
<select id="departamento" name="iddepartamento">
<option value="">-- Sin departamento --</option>
<option th:each="departamento : ${departamentos}"
th:value="${departamento.id}"
th:text="${departamento.nombre}">
</option>
</select>
<button type="submit">Registrar</button>
</form>
<a href="/Inventario/home">
<button class="button_salir">Volver al inicio</button>
</a>
</div>
</body>
</html>