我有這個代碼來檢查用戶是管理員還是訊息的所有者。我必須將此方法拆分為兩種方法:第一個 - 檢查用戶是否為管理員,第二個 - 用戶是否為所有者。但是,如果我只是將條件一分為二,它將無法正常作業。
public static void checkIfTheUserIsAdminOrTheOwnerOfTheComment(Comment commentFound, SecurityUser user){
if (!(commentFound.getAuthor().getId().equals(user.getUserId())
||(user.getAuthorities().contains(new SimpleGrantedAuthority(Authorities.ADMIN_WRITE.getPermission()))))) {
throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
}
}
我試過這個
public static void checkIfTheUserIsTheOwnerOfTheComment(Comment commentFound, SecurityUser user){
if (!commentFound.getAuthor().getId().equals(user.getUserId())) {
throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
}
}
public static void checkIfTheUserIsAdmin(Comment commentFound, SecurityUser user){
if (!user.getAuthorities().contains(new SimpleGrantedAuthority(Authorities.ADMIN_WRITE.getPermission())))) {
throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
}
}
但它不會正常作業,因為如果我以管理員身份登錄,我將有一個例外,我不是所有者,但我必須將它分成兩個單獨的方法。有什么建議?
uj5u.com熱心網友回復:
重構的一種方法是提取執行每個檢查的單獨方法。也許仍然不完美,但它看起來像這樣:
- 第一次檢查:
private boolean checkIsUserOwnerOfComment(Comment commentFound, SecurityUser user) {
return commentFound.getAuthor().getId().equals(user.getUserId());
}
- 第二次檢查:
private boolean checkIsUserAdmin(Comment commentFound, SecurityUser user) {
return user.getAuthorities().contains(new SimpleGrantedAuthority(Authorities.ADMIN_WRITE.getPermission()));
}
最后,根據與您的用例相關的任何邏輯執行兩項檢查并引發例外。
public static void validateUser(Comment commentFound, SecurityUser user){
boolean userIsAdminOrOwnerOfComment = this.checkIsUserAdmin(commentFound, user) || this.checkIsUserOwnerOfComment(commentFound, user);
if (!userIsAdminOrOwnerOfComment) {
throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407936.html
標籤:
