diff --git a/src/main/java/com/example/proyectofinal/controllers/AdminController.java b/src/main/java/com/example/proyectofinal/controllers/AdminController.java new file mode 100644 index 0000000..3116d70 --- /dev/null +++ b/src/main/java/com/example/proyectofinal/controllers/AdminController.java @@ -0,0 +1,178 @@ +package com.example.proyectofinal.controllers; + +import com.example.proyectofinal.models.empresas.Alumno; +import com.example.proyectofinal.models.empresas.Ciclo; +import com.example.proyectofinal.models.empresas.Skill; +import com.example.proyectofinal.models.login.Usuario; +import com.example.proyectofinal.servicios.empresa.AlumnoService; +import com.example.proyectofinal.servicios.empresa.CicloService; +import com.example.proyectofinal.servicios.empresa.SkillService; +import com.example.proyectofinal.servicios.user.UsuarioService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Collection; +import java.util.List; +import java.util.Set; + +@Controller +public class AdminController { + + @Autowired + private UsuarioService usuarioService; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private AlumnoService alumnoService; + + @Autowired + private CicloService cicloService; + @Autowired + private SkillService skillService; + + @GetMapping("/admin/alta_admin_nuevo") + public String showCreateFormAdmin(Model model, Authentication authentication) { + Collection authorities = authentication.getAuthorities(); + boolean isAdmin = authorities.stream() + .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); + if (!isAdmin) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); + } + + model.addAttribute("usuario", new Usuario()); // Add this line + + return "admin/usuario/create"; + } + + @PostMapping("/admin/alta_admin_nuevo") + public String saveNewAdmin(@ModelAttribute Usuario usuario, Authentication authentication) { + Collection authorities = authentication.getAuthorities(); + boolean isAdmin = authorities.stream() + .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); + if (!isAdmin) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); + } + usuario.setRol(usuarioService.getRolById(1)); + + if(usuarioService.getUserByLogInName(usuario.getNombreLogIn()) == null){ + usuarioService.createUsuario(usuario.getNombreUsuario(), usuario.getNombreLogIn(), usuario.getEmail(), usuario.getPassword(), usuario.isLogedIn(), usuario.getRol().getId()); + return "redirect:/buscador?userCreated=true"; + }else { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Este usuario ya existe"); + } + + + } + + @GetMapping("/api/currentUser") + public ResponseEntity getCurrentUser(Authentication authentication) { + String username = authentication.getName(); + Usuario usuario = usuarioService.findByLogInName(username); + return ResponseEntity.ok(usuario); + } + + @GetMapping("/admin/editar_usuario") + public String showUpdateFormAdmin(Model model, Authentication authentication) { + Collection authorities = authentication.getAuthorities(); + boolean isAdmin = authorities.stream() + .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); + if (!isAdmin) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); + } + List users = usuarioService.findAll(); + model.addAttribute("users", users); + model.addAttribute("usuario", new Usuario()); + return "admin/usuario/update"; + } + + @PostMapping("/admin/update_usuario") + public String updateUser(@ModelAttribute Usuario usuario, Authentication authentication) { + Collection authorities = authentication.getAuthorities(); + boolean isAdmin = authorities.stream() + .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); + if (!isAdmin) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); + } + Usuario existingUser = usuarioService.findUserById(usuario.getId()); + if (existingUser == null) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Este usuario no existe"); + } + // Check if the password field is empty + if (usuario.getPassword().isEmpty()) { + // If the password field is empty, keep the original password + usuario.setPassword(existingUser.getPassword()); + } else { + // If the password field is not empty, encrypt the new password + String password = usuario.getPassword(); + existingUser.setPassword(passwordEncoder.encode(password)); + } + usuarioService.saveUser(usuario); + return "redirect:/buscador?userUpdated=true"; + } + + + @GetMapping("/admin/user/{id}") + public ResponseEntity getUser(@PathVariable Long id) { + Usuario usuario = usuarioService.findUserById(id); + return ResponseEntity.ok(usuario); + } + + @GetMapping("/admin/delete_usuario") + public String showDeleteFormAdmin(Model model, Authentication authentication) { + Collection authorities = authentication.getAuthorities(); + boolean isAdmin = authorities.stream() + .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); + if (!isAdmin) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); + } + List users = usuarioService.findAll(); + model.addAttribute("users", users); + model.addAttribute("usuario", new Usuario()); + return "admin/usuario/delete"; + } + + @GetMapping("/admin/delete_usuario/{id}") + public ResponseEntity deleteUser(@PathVariable Long id, Authentication authentication) { + Collection authorities = authentication.getAuthorities(); + boolean isAdmin = authorities.stream() + .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); + if (!isAdmin) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); + } + Usuario existingUser = usuarioService.findUserById(id); + if (existingUser == null) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Este usuario no existe"); + } + // Get the currently authenticated user + String username = authentication.getName(); + Usuario currentUser = usuarioService.findByLogInName(username); + // Check if the user to be deleted is the currently authenticated user + // ... + if (currentUser.getId().equals(id)) { + return ResponseEntity.ok("selfDelete"); + } + Usuario user = usuarioService.findUserById(id); + if(user.getRol().getId() == 2){ + Alumno alumno = alumnoService.findByEmail(user.getEmail()); + System.out.println("TEST DELETING ALUMNO WITH ID: " + alumno.getId()+" AND EMAIL: "+alumno.getCorreo()+" AND NAME: "+alumno.getNombre()); + alumnoService.deleteById(alumno.getId()); + } + usuarioService.deleteUser(id); + return ResponseEntity.ok("userDeleted"); + } + + + + + +} diff --git a/src/main/java/com/example/proyectofinal/controllers/UserController.java b/src/main/java/com/example/proyectofinal/controllers/UserController.java index 71378d6..c87c43d 100644 --- a/src/main/java/com/example/proyectofinal/controllers/UserController.java +++ b/src/main/java/com/example/proyectofinal/controllers/UserController.java @@ -12,20 +12,26 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.server.ResponseStatusException; -import java.util.Collection; import java.util.List; import java.util.Set; @Controller public class UserController { + @Autowired + private CicloService cicloService; + @Autowired + private SkillService skillService; + @Autowired private UsuarioService usuarioService; @@ -35,130 +41,7 @@ public class UserController { @Autowired private AlumnoService alumnoService; - @Autowired - private CicloService cicloService; - @Autowired - private SkillService skillService; - - @GetMapping("/admin/alta_admin_nuevo") - public String showCreateFormAdmin(Model model, Authentication authentication) { - Collection authorities = authentication.getAuthorities(); - boolean isAdmin = authorities.stream() - .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); - if (!isAdmin) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); - } - - model.addAttribute("usuario", new Usuario()); // Add this line - - return "admin/usuario/create"; - } - - @PostMapping("/admin/alta_admin_nuevo") - public String saveNewAdmin(@ModelAttribute Usuario usuario, Authentication authentication) { - Collection authorities = authentication.getAuthorities(); - boolean isAdmin = authorities.stream() - .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); - if (!isAdmin) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); - } - usuario.setRol(usuarioService.getRolById(1)); - - if(usuarioService.getUserByLogInName(usuario.getNombreLogIn()) == null){ - usuarioService.createUsuario(usuario.getNombreUsuario(), usuario.getNombreLogIn(), usuario.getEmail(), usuario.getPassword(), usuario.isLogedIn(), usuario.getRol().getId()); - return "redirect:/buscador?userCreated=true"; - }else { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Este usuario ya existe"); - } - - - } - - @GetMapping("/api/currentUser") - public ResponseEntity getCurrentUser(Authentication authentication) { - String username = authentication.getName(); - Usuario usuario = usuarioService.findByLogInName(username); - return ResponseEntity.ok(usuario); - } - - @GetMapping("/admin/editar_usuario") - public String showUpdateFormAdmin(Model model, Authentication authentication) { - Collection authorities = authentication.getAuthorities(); - boolean isAdmin = authorities.stream() - .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); - if (!isAdmin) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); - } - List users = usuarioService.findAll(); - model.addAttribute("users", users); - model.addAttribute("usuario", new Usuario()); - return "admin/usuario/update"; - } - - @PostMapping("/admin/update_usuario") - public String updateUser(@ModelAttribute Usuario usuario, Authentication authentication) { - Collection authorities = authentication.getAuthorities(); - boolean isAdmin = authorities.stream() - .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); - if (!isAdmin) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); - } - Usuario existingUser = usuarioService.findUserById(usuario.getId()); - if (existingUser == null) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Este usuario no existe"); - } - String password = existingUser.getPassword(); - existingUser.setPassword(passwordEncoder.encode(password)); - usuarioService.saveUser(usuario); - return "redirect:/buscador?userUpdated=true"; - } - - - @GetMapping("/admin/user/{id}") - public ResponseEntity getUser(@PathVariable Long id) { - Usuario usuario = usuarioService.findUserById(id); - return ResponseEntity.ok(usuario); - } - - @GetMapping("/admin/delete_usuario") - public String showDeleteFormAdmin(Model model, Authentication authentication) { - Collection authorities = authentication.getAuthorities(); - boolean isAdmin = authorities.stream() - .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); - if (!isAdmin) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); - } - List users = usuarioService.findAll(); - model.addAttribute("users", users); - model.addAttribute("usuario", new Usuario()); - return "admin/usuario/delete"; - } - - @GetMapping("/admin/delete_usuario/{id}") - public String deleteUser(@PathVariable Long id, Authentication authentication) { - Collection authorities = authentication.getAuthorities(); - boolean isAdmin = authorities.stream() - .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ADMIN")); - if (!isAdmin) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); - } - Usuario existingUser = usuarioService.findUserById(id); - if (existingUser == null) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Este usuario no existe"); - } - Usuario user = usuarioService.findUserById(id); - if(user.getRol().getId() == 2){ - Alumno alumno = alumnoService.findByEmail(user.getEmail()); - System.out.println("TEST DELETING ALUMNO WITH ID: " + alumno.getId()+" AND EMAIL: "+alumno.getCorreo()+" AND NAME: "+alumno.getNombre()); - alumnoService.deleteById(alumno.getId()); - } - usuarioService.deleteUser(id); - return "redirect:/buscador?userDeleted=true"; - } - - - - @GetMapping("/usuario/usuario_update_form") + @GetMapping("/usuario/alu_update_form") public String showUpdateForm(Model model, Authentication authentication) { String username = authentication.getName(); Usuario usuario = usuarioService.findByLogInName(username); @@ -172,13 +55,14 @@ public class UserController { } - @PostMapping("/usuario/update") + @PostMapping("/usuario/alu_update") public ResponseEntity updateAlumno(Alumno alumno, @RequestParam("ciclo") Long ciclo, @RequestParam("skills") List skills){ try{ Ciclo cicloEntity = cicloService.findById(ciclo); Set skillEntities = skillService.findAllByIds(skills); alumno.setCiclo(cicloEntity); alumno.setSkills(skillEntities); + //System.out.println("TEST UPDATE ALUMNO: "+alumno.getNombre()); alumnoService.save(alumno); return new ResponseEntity<>("El alumno fue actualizado con exito", HttpStatus.OK); }catch (Exception e) { @@ -186,6 +70,53 @@ public class UserController { } } + @GetMapping("/usuario/usuario_norm_update_form") + public String showUsuarioNormUpdateForm(Model model, Authentication authentication){ + String username = authentication.getName(); + Usuario users = usuarioService.getUserByLogInName(username); + model.addAttribute("usuario", users); + return "user/update_usuario"; + } + @PostMapping("/usuario/update_usuario_normal") + public String updateUserNormal(@ModelAttribute Usuario usuario, Authentication authentication) { + Usuario existingUser = usuarioService.findUserById(usuario.getId()); + if (existingUser == null) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Este usuario no existe"); + } + // Check if the password field is empty + if (usuario.getPassword().isEmpty()) { + // If the password field is empty, keep the original password + usuario.setPassword(existingUser.getPassword()); + } else { + // If the password field is not empty, encrypt the new password + String password = usuario.getPassword(); + existingUser.setPassword(passwordEncoder.encode(password)); + } + usuario.setRol(usuarioService.getRolById(2)); + //System.out.println("TEST UPDATE USUARIO: "+usuario.getNombreUsuario()); + usuarioService.saveUser(usuario); + return "redirect:/buscador?userUpdated=true"; + } + + + + @GetMapping("/usuario/info") + public String showUserInfo(Model model, Authentication authentication) { + // Get the current user + String username = authentication.getName(); + Usuario usuario = usuarioService.findByLogInName(username); + + if(usuario.getRol().getId() ==1){ + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "No tienes permisos para acceder a esta página"); + } + Alumno alumno = alumnoService.findByEmail(usuario.getEmail()); + + model.addAttribute("usuario", usuario); + model.addAttribute("alumno", alumno); + + // Return the name of the view + return "user/info_user"; + } } diff --git a/src/main/java/com/example/proyectofinal/controllers/modelControllers/AlumnoController.java b/src/main/java/com/example/proyectofinal/controllers/modelControllers/AlumnoController.java index cb12c3e..ebb1d42 100644 --- a/src/main/java/com/example/proyectofinal/controllers/modelControllers/AlumnoController.java +++ b/src/main/java/com/example/proyectofinal/controllers/modelControllers/AlumnoController.java @@ -57,12 +57,13 @@ public class AlumnoController { @PostMapping("/alumno/save") - public ResponseEntity saveAlumno(Alumno alumno, @RequestParam("ciclo") Long ciclo, @RequestParam("skills") List skills){ + public ResponseEntity saveAlumno(Alumno alumno, @RequestParam("ciclo") Long ciclo, @RequestParam("skills") List skills, @RequestParam("joinedKeywords") String keywords){ try{ Ciclo cicloEntity = cicloService.findById(ciclo); Set skillEntities = skillService.findAllByIds(skills); alumno.setCiclo(cicloEntity); alumno.setSkills(skillEntities); + alumno.setKeywords(keywords); // Set the keywords from the joinedKeywords string Alumno testIfExist = alumnoService.exists(alumno); if(testIfExist != null){ return new ResponseEntity<>("El alumno ya existe", HttpStatus.BAD_REQUEST); diff --git a/src/main/resources/templates/admin/alumno/create.html b/src/main/resources/templates/admin/alumno/create.html index 2443888..b823d3f 100644 --- a/src/main/resources/templates/admin/alumno/create.html +++ b/src/main/resources/templates/admin/alumno/create.html @@ -10,6 +10,8 @@ + + @@ -87,17 +89,29 @@
- +
-
- + +
+
+ + + +
+ + +
\ No newline at end of file diff --git a/src/main/resources/templates/buscador_admin.html b/src/main/resources/templates/buscador_admin.html index 943da9b..8230dd0 100644 --- a/src/main/resources/templates/buscador_admin.html +++ b/src/main/resources/templates/buscador_admin.html @@ -93,7 +93,7 @@
@@ -201,6 +201,15 @@ alert('Usuario actualizado correctamente'); } }); + + $(document).ready(function() { + const urlParams = new URLSearchParams(window.location.search); + const error = urlParams.get('error'); + + if (error === 'selfDelete') { + alert('No puedes eliminarte a ti mismo'); + } + }); function deleteUser() { isValidUserId().then(isValid => { diff --git a/src/main/resources/templates/buscador_alumno.html b/src/main/resources/templates/buscador_alumno.html index 0236616..e3e68e3 100644 --- a/src/main/resources/templates/buscador_alumno.html +++ b/src/main/resources/templates/buscador_alumno.html @@ -72,29 +72,6 @@ #user p { font-size: 10px; /* Adjust as needed */ } - #info{ - position: relative; - margin-left: 50px; - padding: 0px; - background-color: #dddddd; - width: 50px; /* Adjust as needed */ - height: 50px; /* Adjust as needed */ - display: flex; - flex-direction: column; /* New property */ - align-items: center; /* Vertically center the contents */ - justify-content: center; /* Horizontally center the contents */ - text-align: center; /* Center the text */ - } - - #info-icon { - width: 22px; /* Adjust as needed */ - height: 22px; /* Adjust as needed */ - } - - #info p { - font-size: 10px; /* Adjust as needed */ - } - .modal-content p{ background-color: antiquewhite; @@ -108,10 +85,6 @@

Usuario

-
- -

Información

-

PAGINA PRINCIPAL

@@ -120,16 +93,9 @@ - - @@ -162,64 +128,24 @@ + + diff --git a/src/main/resources/templates/user/update.html b/src/main/resources/templates/user/update_alu.html similarity index 95% rename from src/main/resources/templates/user/update.html rename to src/main/resources/templates/user/update_alu.html index 2b2bed3..eafcc42 100644 --- a/src/main/resources/templates/user/update.html +++ b/src/main/resources/templates/user/update_alu.html @@ -28,14 +28,11 @@ margin-right: 5px; width: 120px; height: 40px; - font-family: Verdana; + font-family: Verdana, Geneva, Tahoma, sans-serif } form input[type="submit"], form input[type="button"] { width: 100px; } - form input[type="text"]{ - width: 75%; - } form label{ font-size: 20px; margin-bottom: 10px; @@ -48,12 +45,17 @@ width: 100%; box-sizing: border-box; } + input[type="text"], input[type="password"], input[type="email"] { + width: 350px; + height: 25px; + font-size: 15px; + }

Editar datos de Alumno

-
+
@@ -167,7 +169,7 @@ }); function goBack() { - window.history.back(); + window.location.href = "/buscador"; } $(document).ready(function () { $("form").on("submit", function (event) { diff --git a/src/main/resources/templates/user/update_usuario.html b/src/main/resources/templates/user/update_usuario.html new file mode 100644 index 0000000..90f1711 --- /dev/null +++ b/src/main/resources/templates/user/update_usuario.html @@ -0,0 +1,117 @@ + + + + Editar Usuario + + + + + + + + + + +

Editar Usuario

+ + + +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ + +
+ + + + \ No newline at end of file