I make a web application in Java using:

Spring MVC Spring Security Hibernate

The distribution of access rights to resources / pages occurs through Spring Security. There are two roles: ADMIN USER Problem -When USER made a login, it will show all USERs, including his Question- how to make sure that when USER made a login, he showed all USERs except him?

SECURITY Current User

public class CurrentUser extends User { private am.teletalk.teletalk.model.User user; public CurrentUser( am.teletalk.teletalk.model.User user) { super(user.getEmail(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getUserType().name())); this.user = user; } public am.teletalk.teletalk.model.User getUser() { return user; } public int getId() { return user.getId(); } 

}

SECURITY CurrentUserDetailService

 public class CurrentUserDetailService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { User user = userRepository.findOneByEmail(s); if (user == null) { throw new UsernameNotFoundException("User not exist"); } return new CurrentUser(user); } 

}

Controller

  @RequestMapping(value = "/", method = RequestMethod.GET) public String mainPage(ModelMap map) { map.addAttribute("allUsers", userRepository.findAll()); map.addAttribute("manager", new User()); return "index"; } 
  • one
    I do not see the controller giving all users when logged in - Komdosh
  • oh sorry now add - user295262

1 answer 1

Function to get the user object for the current session

 public User getCurrentUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication instanceof AnonymousAuthenticationToken) return null; return (User) authentication.getPrincipal(); } 

In the simplest version, you can filter the list

 User currentUser = getCurrentUser(); List<User> users = userRepository.findAll().stream().filter(u->u.getId()!=currentUser.getId()).collect(Collectors.toList()); 

Well, further improvements, this is your fantasy, it’s better to create a method in the repository that will get all users who don’t have the same Id , but that’s up to you.

  • Thank you so much - user295262
  • But can you arrange all this with the help of else if? - user295262
  • in the sense of filtering in a loop using if? - Komdosh
  • I mean if (currentUser.id! = user.id) {userRepository.findAll write this in jsp - user295262
  • what is user.id? - Komdosh