Search code examples
javaspringspring-securityjhipsterroles

Jhipster - check Role of a User


I have the following method in UserResourse.java generated by default by Jhipster:

@DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
@PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")")
@Transactional
public ResponseEntity<Void> deleteUser(@PathVariable String login) {
    log.debug("REST request to delete User: {}", login);

    userService.deleteUser(login);
    return ResponseEntity.noContent().headers(HeaderUtil.createAlert(applicationName,  "userManagement.deleted", login)).build();
} 

If the user to be deleted has a certain role I want to make other changes to the database. I need to write something like :

Optional<User> user =  this.userService.findOneByLogin(login);
if(user.get().hasRole("ROLE_USER"){
 // do something
}

The User class has an attribute Set<Authority> authorities and I am thinking that I can maybe use this to check the role of the user, but I cannot figure out how to do it. Can someone assist me ?


Solution

  • You can do this in many ways, I would delegate this behaviour to the service instead of the resource.

    One approach is to add a new method to your User.java class that checks whether the user has certain role. Something like:

    public boolean hasRole(String role) {
        return this.authorities.stream().map(Authority::getName).anyMatch(a -> a.equals(role));
    }
    

    And then call it from your UserService.java:

    public void deleteUser(String login) {
        userRepository.findOneWithAuthoritiesByLogin(login).ifPresent(user -> {
    
            if (user.hasRole(AuthoritiesConstants.USER)){
                // Do your things here
    
            }
    
            userRepository.delete(user);
            log.debug("Deleted User: {}", user);
        });
    }