[英]Jhipster - check Role of a User
I have the following method in UserResourse.java generated by default by Jhipster:我在Jhipster默认生成的UserResource.java中有以下方法:
@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.用户 class 有一个属性
Set<Authority> authorities
,我想我可以用它来检查用户的角色,但我不知道该怎么做。 Can someone assist me?有人可以帮助我吗?
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.一种方法是向您的
User.java
class 添加一个新方法来检查用户是否具有特定角色。 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
:然后从您的
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);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.