View 확인

2. 권한부여하기
Reply
@Transient
private boolean isReplyOwner;
Reply 에 isReplyOwner 를 추가한다. board 객체의 reply 필드에 포함되기 때문에 board 객체에 담을 수 있다.
BoardJPARepository
public Board 글상세보기(int boardId, User sessionUser) {
Board board = boardJPARepository.findByIdJoinUser(boardId)
.orElseThrow(() -> new Exception404("게시글을 찾을 수 없습니다"));
boolean isBoardOwner = false;
if (sessionUser != null) {
if (sessionUser.getId() == board.getUser().getId()) {
isBoardOwner = true;
}
}
board.setBoardOwner(isBoardOwner);
board.getReplies().forEach(reply ->{
boolean isReplyOwner = false ;
if(sessionUser!=null) {
if (reply.getUser().getId() == sessionUser.getId()) {
isReplyOwner =true;
}
}
reply.setReplyOwner(isReplyOwner);
});
return board;
}
반복문을 돌면서 isReplyOwner 값을 확인한다. 로그인이 되어있고, 댓글 작성 id와 로그인한 id를 비교한다.
view
{{#isReplyOwner}}
<form action="/reply/{{id}}/delete" method="post">
<button class="btn">🗑</button>
</form>
{{/isReplyOwner}}

3. 댓글 삭제하기
ReplyController
@PostMapping("/board/{boardId}/reply/{replyId}/delete")
public String delete(@PathVariable Integer boardId, @PathVariable Integer replyId){ //컨트롤러에 책임은 인증체크 나머지는 서비스로
User sessionUser = (User) session.getAttribute("sessionUser");
replyService.댓글삭제(replyId, sessionUser.getId());
return "redirect:/board/"+boardId;
}
ReplyService
@Transactional
public void 댓글삭제(int replyId, int sessionUserId) {
Reply reply = replyJPARepository.findById(replyId)
.orElseThrow(() -> new Exception404("없는 댓글을 삭제할 수 없어요"));
if(reply.getUser().getId() != sessionUserId){
throw new Exception403("댓글을 삭제할 권한이 없어요");
}
replyJPARepository.deleteById(replyId);
}
댓글이 삭제된 후 원래의 게시글로 리다이렉션을 위해서는 게시글 번호가 필요하다. reply에 board 객체가 있기 때문에 reply.getBoard().getId() 를 이용하면 되지만, 댓글 삭제 이후엔 reply 값이 null이 된다. 따라서 데이터가 삭제되기 전에 boardId 를 저장했다 삭제 후 boardId 만 리턴했다.


Share article