팀 프로젝트인 뉴스피드 제작하기의 막바지에 들어섰다.
웹페이지 기능을 시연하여 확인하는 중 문제가 있다는 것을 발견하였다.
문제:
현재 로그인한 유저가 다른 유저가 작성한 게시글과 댓글을 모두 수정, 삭제가 가능하다!
=> 이렇게 되면 작성자가 원하지 않는 상황이 발생할 수 있으므로 게시글 작성자 / 댓글 작성자만이 수정/삭제를 할 수 있도록 수정하였다.
바꿔야 하는 부분은 서버쪽 nodejs코드로 기존 코드는 다음과 같았다.
update: async (req, res, next) => {
const { comment } = req.body;
const { commentId } = req.params;
try {
const foundComment = await Comment.findByPk(commentId);
const updatedComment = await foundComment.update({"comment":comment}).then(d=>{return d});
res.status(200).json(updatedComment.toJSON());
} catch (err) {
console.error(err);
res.status(500).json({ message: '서버 에러' });
기존 코드는 댓글 내용을 body로 받아서 commentId와 수정하려는 댓글의 commentId가 일치하면 받아온 body의 comment로 바꾸는 코드였다. 즉 수정하려는 내용만 받고 user와 작성자의 user를 확인하지 않은 것이다.
수정한 코드는 다음과 같다.
update: async (req, res, next) => {
const { comment } = req.body;
const { commentId } = req.params;
const tryUser = res.locals.foundUser;
try {
const foundComment = await Comment.findByPk(commentId);
if(foundComment.dataValues.userId==tryUser.id){
const updatedComment = await foundComment.update({"comment":comment}).then(d=>{return d});
res.status(200).json(updatedComment.toJSON());
}else{
res.status(400).json({
message:"수정 권한이 없습니다."
})
}
} catch (err) {
console.error(err);
res.status(500).json({ message: '서버 에러' });
변수로 로그인한 유저의 정보를 받아오고, 댓글 작성자의 userId와 로그인한 유저의 userId가 일치하면 수정하고 일치하지 않으면 수정 권한이 없다고 메세지가 뜨게끔 수정하였다.