public void deletePost(Long id, User user) {
Post post = findPostById(id);
// 게시글이 존재하지 않을 경우 예외 던지기
if (post == null) {
throw new NotFoundException("해당 ID의 포스트를 찾을 수 없습니다.");
}
// 삭제 권한 체크
checkDeletePermission(post, user);
// 게시글 삭제
postRepository.delete(post);
}
private Post findPostById(Long id) {
// 포스트를 데이터베이스에서 조회하는 로직 구현
}
private void checkDeletePermission(Post post, User user) {
boolean isAdmin = user.getRole().equals(UserRoleEnum.ADMIN);
boolean isPostOwner = post.getUser().equals(user);
if (!(isAdmin || isPostOwner)) {
throw new UnauthorizedAccessException("포스트를 삭제할 권한이 없습니다.");
}
}
deletePost 메서드
- findPostById 메서드를 호출하여 삭제할 게시글을 찾음
- 찾는 게시글이 존재하지 않을 경우,
NotFoundException을 던지고 예외 처리
- checkDeletePermission 메서드를 호출하여 삭제 권한을 확인
- 삭제 권한이 있으면 해당 게시글을 데이터베이스에서 삭제
checkDeletePermission 메서드
- isAdmin 변수에는 사용자가 관리자인지 여부를 저장
- isPostOwner 변수에는 게시글 작성자가 주어진 사용자인지 여부를 저장
- 사용자가 관리자이거나 게시글 작성자일 경우 권한이 있으므로,
권한이 없는 경우 UnauthorizedAccessException을 던짐