81일차
97. 자격
로그인한 사람만쓸수있도록해주자.
add에 authentication 자격이 없다면 401에러를 내게 해주자.
97.1 컨트롤러
@PostMapping("add")
public ResponseEntity<Map<String, Object>> add(@RequestBody Comment comment, Authentication authentication) {
if(authentication == null) {
Map<String, Object> res = Map.of("message", "로그인 후 댓글을 작성해주세요.");
return ResponseEntity.status(401).body(res);
} else {
Map<String, Object> res = service.add(comment, authentication);
return ResponseEntity.ok().body(res);
}
}97.2 서비스
Authentication객체를 사용하게 되었으니 임의로 넣었던 이름을 유저 이름으로 넣어준다.
public Map<String, Object> add(Comment comment, Authentication authentication) {
comment.setMemberId(authentication.getName());
var res = new HashMap<String, Object>();
int cnt = mapper.insert(comment);
if (cnt == 1) {
res.put("message", "댓글이 등록되었습니다.");
} else {
res.put("message", "댓글이 등록되지 않았습니다.");
}
return res;
}97.3 view
화면에서도 로그아웃이라면 댓글 쓰는 창을 보여주지 말자.
<div id="commentContainer">
<sec:authorize access="isAuthenticated()">
<div id="addCommentContainer">
<h6>입력</h6>
<textarea id="commentTextArea"></textarea>
<button id="sendCommentBtn">전송</button>
</div>
<div id="updateCommentContainer">
<h6>수정</h6>
<input type="hidden" id="commentUpdateIdInput" />
<textarea id="commentUpdateTextArea"></textarea>
<button id="updateCommentBtn">수정</button>
</div>
</sec:authorize>
<div id="commentListContainer"></div>
</div>97.4 view - 2
수정버튼을 본인일때만 가능하도록 해주자.
Comment에 private Boolean editable; 새로운 필드를 추가해줘서
true일때만 수정버튼이 보이게 해주자.
서비스에서 아이디 세팅해주는 것을 처리해주고 view에서는 editable값을 받아 있으면 버튼이 보이게 없읍면안보이게 바꾸어주엇다.
js에서 받아서 사용하는 것이라 이렇게 한듯하다.
for (const comment of comments) {
const editButtons = `<button
id="commentDeleteBtn${comment.id}"
class="commentDeleteButton"
data-comment-id="${comment.id}">삭제</button>
:
<button
id="commentUpdateBtn${comment.id}"
class="commentUpdateButton"
data-comment-id="${comment.id}">수정</button>`
// console.log(comment);
$("#commentListContainer").append(`
<div>
${comment.editable ? editButtons : ''}
: ${comment.content}
: ${comment.memberId}
: ${comment.inserted}
</div>
`);
};public List<Comment> list(Integer boardId, Authentication authentication) {
List<Comment> comments = mapper.selectAllByBoardId(boardId);
if (authentication != null) {
/*
* List<Comment> commentsWithEditbale = comments.stream().map(c -> {
* c.setEditable(c.getMemberId().equals(authentication.getName())); return c; })
* .toList();
*/
for (Comment comment : comments) {
comment.setEditable(comment.getMemberId().equals(authentication.getName()));
}
}
return comments;
}97.5 컨트롤러 수정
눈으로만 안보이게 하는 것이 아니라 혹시 모르니 컨트롤러에서도 막아줘야한다.
@DeleteMapping("id/{id}")
@ResponseBody
@PreAuthorize("authenticated and @customSecurityChecker.checkCommentWriter(authentication, #id)")
public ResponseEntity<Map<String, Object>> remove(@PathVariable("id") Integer id) {
Map<String, Object> res = service.remove(id);
return ResponseEntity.ok().body(res);
}98 css
https://getbootstrap.com/docs/5.3/components/list-group/
<div class="container-lg">
<!-- .row.justify-content-center>.col-12.col-md-8.col-lg-6 -->
<div class="row justify-content-center">
<div class="col-12 col-md-8 col-lg-6">
<div class="d-flex mb-5">
<div>
<a class="btn btn-secondary" href="/detail/${board.prevId}">이전글</a>
</div>
<div class="me-auto ms-auto">
<a class="btn btn-secondary" href="/list">목록으로가기</a>
</div>
<div>
<a class="btn btn-secondary" href="/detail/${board.nextId}">다음글</a>
</div>
</div>
</div>
</div>
</div>const editButtons = `
<button
id="commentDeleteBtn${comment.id}"
class="commentDeleteButton btn btn-danger"
data-bs-toggle="modal"
data-bs-target="#deleteCommentConfirmModal"
data-comment-id="${comment.id}">
<i class="fa-regular fa-trash-can"></i>
</button>
<button
id="commentUpdateBtn${comment.id}"
class="commentUpdateButton btn btn-secondary"
data-bs-toggle="modal" data-bs-target="#commentUpdateModal"
data-comment-id="${comment.id}">
<i class="fa-regular fa-pen-to-square"></i>
</button>
`;
// console.log(comment);
$("#commentListContainer").append(`
<li class="list-group-item d-flex justify-content-between align-items-start">
<div class="ms-2 me-auto">
<div class="fw-bold"> <i class="fa-regular fa-user"></i> ${comment.memberId}</div>
<div style="white-space: pre-wrap;">${comment.content}</div>
</div>
<div>
<span class="badge bg-primary rounded-pill">${comment.inserted}</span>
<div class="text-end mt-2">
${comment.editable ? editButtons : ''}
</div>
</div>
</li>
`);99. RestController
comment컨트롤러의 모든 메소드가 모두 ResponseBody이다.
RestController를 붙이면 생략할 수 있다.
@RestController
@RequestMapping("comment")
public class CommentController {
@Autowired
private CommentService service;
@PutMapping("update")
@PreAuthorize("authenticated and @customSecurityChecker.checkCommentWriter(authentication, #comment.id)")
public ResponseEntity<Map<String, Object>> update(@RequestBody Comment comment) {
Map<String, Object> res = service.update(comment);
return ResponseEntity.ok().body(res);
}
@GetMapping("id/{id}")
public Comment get(@PathVariable("id") Integer id) {
return service.get(id);
}
@DeleteMapping("id/{id}")
@PreAuthorize("authenticated and @customSecurityChecker.checkCommentWriter(authentication, #id)")
public ResponseEntity<Map<String, Object>> remove(@PathVariable("id") Integer id) {
Map<String, Object> res = service.remove(id);
return ResponseEntity.ok().body(res);
}
@PostMapping("add")
public ResponseEntity<Map<String, Object>> add(@RequestBody Comment comment, Authentication authentication) {
if (authentication == null) {
Map<String, Object> res = Map.of("message", "로그인 후 댓글을 작성해주세요.");
return ResponseEntity.status(401).body(res);
} else {
Map<String, Object> res = service.add(comment, authentication);
return ResponseEntity.ok().body(res);
}
}
@GetMapping("list")
//@ResponseBody
public List<Comment> list(@RequestParam("board") Integer boardId, Authentication authentication) {
return service.list(boardId, authentication);
}
}'국비 > Project - 1 게시판' 카테고리의 다른 글
| 2023.05.19 80일차 Project (0) | 2023.05.19 |
|---|---|
| 2023.05.16 77일차-1 Project (0) | 2023.05.16 |
| 2023.05.15 76일차 Project (0) | 2023.05.16 |
| 2023.05.12 75일차 Project (0) | 2023.05.12 |
| 2023.05.11 74일차 Project (0) | 2023.05.11 |