@@ -55,7 +55,7 @@ router.get("/index/:id/comments/new", isLoggedIn, function (req, res) {
55
55
} ) ;
56
56
57
57
//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 ) {
59
59
Campground . findById ( req . params . id , function ( err , foundCampground ) {
60
60
if ( err ) {
61
61
console . log ( err ) ;
@@ -74,7 +74,7 @@ router.get("/index/:id/comments/:comment_id/edit", function(req, res){
74
74
} ) ;
75
75
76
76
//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 ) {
78
78
Campground . findById ( req . params . id , function ( err , foundCampground ) {
79
79
if ( err ) {
80
80
console . log ( err ) ;
@@ -96,7 +96,7 @@ router.put("/index/:id/comments/:comment_id", function (req, res) {
96
96
97
97
98
98
//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 ) {
100
100
Comment . findByIdAndRemove ( req . params . comment_id , function ( err ) {
101
101
if ( err ) {
102
102
res . redirect ( "back" ) ;
@@ -116,5 +116,24 @@ function isLoggedIn(req, res, next) {
116
116
}
117
117
}
118
118
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
+
119
138
module . exports = router ;
120
139
0 commit comments