Skip to content

Commit e59e7e1

Browse files
committed
Done with the auth part
1 parent 11763fc commit e59e7e1

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

routes/comments.js

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ router.get("/index/:id/comments/new", isLoggedIn, function (req, res) {
5555
});
5656

5757
//Comment edit and delete
58-
router.get("/index/:id/comments/:comment_id/edit", function(req, res){
58+
router.get("/index/:id/comments/:comment_id/edit",checkCommentOwnership, function(req, res){
5959
Campground.findById(req.params.id, function (err, foundCampground) {
6060
if(err){
6161
console.log(err);
@@ -74,7 +74,7 @@ router.get("/index/:id/comments/:comment_id/edit", function(req, res){
7474
});
7575

7676
//Post route for editing the comment
77-
router.put("/index/:id/comments/:comment_id", function (req, res) {
77+
router.put("/index/:id/comments/:comment_id",checkCommentOwnership, function (req, res) {
7878
Campground.findById(req.params.id, function(err, foundCampground){
7979
if(err){
8080
console.log(err);
@@ -96,7 +96,7 @@ router.put("/index/:id/comments/:comment_id", function (req, res) {
9696

9797

9898
//Delete a comment
99-
router.delete("/index/:id/comments/:comment_id", function (req, res) {
99+
router.delete("/index/:id/comments/:comment_id",checkCommentOwnership, function (req, res) {
100100
Comment.findByIdAndRemove(req.params.comment_id, function (err) {
101101
if (err) {
102102
res.redirect("back");
@@ -116,5 +116,24 @@ function isLoggedIn(req, res, next) {
116116
}
117117
}
118118

119+
function checkCommentOwnership(req,res, next) {
120+
if(req.isAuthenticated()){
121+
Comment.findById(req.params.comment_id, function(err, foundComment){
122+
if(err){
123+
res.redirect("back");
124+
} else {
125+
// does user own the comment?
126+
if(foundComment.author.id.equals(req.user._id)) {
127+
next();
128+
} else {
129+
res.redirect("back");
130+
}
131+
}
132+
});
133+
} else {
134+
res.redirect("back");
135+
}
136+
}
137+
119138
module.exports = router;
120139

views/campgrounds/show.ejs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,12 @@
4141
<p class="mb-0">
4242
<%= comment.content %>
4343
</p>
44-
44+
<% if(currentUser && comment.author.id.equals(currentUser._id)){ %>
4545
<a class="btn btn-sm btn-warning" href="/index/<%= campground._id %>/comments/<%= comment._id%>/edit ">Edit</a>
4646
<form action="/index/<%=campground._id%>/comments/<%= comment._id %>?_method=DELETE" method="POST" id="delete-form" style="display: inline" class="form-inline" >
4747
<button class="btn btn-sm btn-danger">Delete</button>
4848
</form>
49-
49+
<% } %>
5050
</div>
5151
</div>
5252
<% }) %>

0 commit comments

Comments
 (0)