How to extract a name from my controller?

0

I have times trying to extract the current user to be able to make a comparison in my controller so that only the user who made it can delete a reservation. But I have not found a way to get that user, any ideas?

Controller

    @RequestMapping(value = "/EliminarRESAU.do", method = RequestMethod.GET)
public String borrarRESA(ModelMap model,@RequestParam("id") Long idRESA ) throws Exception {
    try {


        RESA resa = resaBo.obtener(idRESA);
        if (!resa.getEstado().equals("Activa")) {
            JOptionPane.showMessageDialog(null,"1"); 
            return "redirect:ListarRESAU.do"; 
        }
        if (resa.getEstado().equals("Activa")) {
            JOptionPane.showMessageDialog(null,resa.getUsuario().getParticipante());
            return "redirect:ListarRESAU.do"; 
        }else{
            JOptionPane.showMessageDialog(null,"3"); 
        return "redirect:ListarRESAU.do";}

    } catch (Exception e) {
        throw e;
    }
}

    
asked by Jose Diaz 02.11.2016 в 16:05
source

1 answer

1

I guess you use Spring Security for the login system, so you could retrieve the current user inside the controller with

SecurityContextHolder.getContext().getAuthentication().getPrincipal();

If you do not have it yet, you can inherit from the class User to be able to add the properties you want, regularly the id in the database and the name of the user

public class MiAppUser extends User  {
    private String nombre;
    private Long idUsuario;
    ....

And in a Service that takes care of the login

@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

   /*Buscamos el username y verificamos que exista*/

   MiAppUser user = new MiAppUser();
  //Setters de User
   user.setUsername(x);
   user.setPassword(x);
   user.setEnabled(x);
   user.setAccountNonExpired(x);
   user.setCredentialsNonExpired(x);
   user.setAccountNonLocked(x);
   user.setAuthorities(x);
   //Setters de MiAppUser
   user.setNombre(x);
   user.setIdUsuario(x);

   return user;
}

And you find in our controller we use:

MiAppUser user = (MiAppUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if(user.getIdUsuario() == idRESAUsuarioCrea){
     //podemos borrar
}
    
answered by 02.11.2016 в 16:32