我需要获得我要删除的用户的权限。我的尝试如下。
@DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
@Timed
@Secured({AuthoritiesConstants.ADMIN, AuthoritiesConstants.LECTURER})
public ResponseEntity<Void> deleteUser(@PathVariable String login) {
log.debug("REST request to delete User: {}", login);
boolean hasAuthorityAdmin = false;
boolean hasAuthorityMember = false;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
hasAuthorityAdmin = authorities.contains(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));
hasAuthorityMember = authorities.contains(new SimpleGrantedAuthority(AuthoritiesConstants.MEMBER));
if (hasAuthorityAdmin) {
// delete user
userService.deleteUser(login);
} else {
if (hasAuthorityMember) {
// delete user if it is a student
if (**x**.contains(AuthoritiesConstants.STUDENT)) {
userService.deleteUser(login);
}
}
}
return ResponseEntity.ok().headers(HeaderUtil.createAlert("userManagement.deleted", login)).build();
}
而不是x我需要一个方法来检索它?这意味着我需要检索我要删除的权限。所以任何人都有想法。这是在userResource.java中。任何人都可以帮我解释代码吗?
假设我以成员身份登录。然后我要删除学生。所以当我点击学生记录的删除按钮时,应该能够通过一种方法获得ROLE_STUDENT。
答案 0 :(得分:1)
这应该这样做:
if (hasAuthorityMember) {
Optional<User> user = userService.getUserWithAuthoritiesByLogin(login);
Set<Authority> currentUserAuthorities = user.get().getAuthorities();
for(Authority auth : currentUserAuthorities) {
// delete user if it is a student
if(auth.getName().equals(AuthoritiesConstants.STUDENT)) {
userService.deleteUser(login);
}
}
}
使用UserService,您可以通过登录获得用户及其权限,并且对于每个权限(如果有很多),我们会检查权限的名称。如果对应于学生,则删除该用户。