@@ -79,7 +79,7 @@ router.get("/index/new",isLoggedIn, function (req, res) {
79
79
} ) ;
80
80
81
81
//Edit campground----->>>
82
- router . get ( "/index/:id/edit" , function ( req , res ) {
82
+ router . get ( "/index/:id/edit" , checkCampgroundOwnership , function ( req , res ) {
83
83
Campground . findById ( req . params . id , function ( err , foundCampground ) {
84
84
if ( err ) {
85
85
console . log ( err ) ;
@@ -92,7 +92,7 @@ router.get("/index/:id/edit", function (req, res) {
92
92
} ) ;
93
93
94
94
// UPDATE CAMPGROUND ROUTE
95
- router . put ( "/index/:id" , function ( req , res ) {
95
+ router . put ( "/index/:id" , checkCampgroundOwnership , function ( req , res ) {
96
96
// find and update the correct campground
97
97
Campground . findByIdAndUpdate ( req . params . id , req . body . campground , function ( err , updatedCampground ) {
98
98
if ( err ) {
@@ -105,6 +105,19 @@ router.put("/index/:id" , function(req, res){
105
105
} ) ;
106
106
} ) ;
107
107
108
+ //Destroy campground rote
109
+ router . delete ( "/index/:id" , checkCampgroundOwnership , function ( req , res ) {
110
+ console . log ( "I'm here" ) ;
111
+ Campground . findByIdAndRemove ( req . params . id , function ( err ) {
112
+ if ( err ) {
113
+ console . log ( err ) ;
114
+ res . redirect ( "/index" ) ;
115
+ } else {
116
+ res . redirect ( "/index" ) ;
117
+ }
118
+ } ) ;
119
+ } ) ;
120
+
108
121
109
122
function isLoggedIn ( req , res , next ) {
110
123
if ( req . isAuthenticated ( ) ) {
@@ -114,5 +127,25 @@ router.put("/index/:id" , function(req, res){
114
127
}
115
128
}
116
129
130
+ //Check campground ownership
131
+ function checkCampgroundOwnership ( req , res , next ) {
132
+ if ( req . isAuthenticated ( ) ) {
133
+ Campground . findById ( req . params . id , function ( err , foundCampground ) {
134
+ if ( err ) {
135
+ res . redirect ( "back" ) ;
136
+ } else {
137
+ // does user own the campground?
138
+ if ( foundCampground . Author . id . equals ( req . user . _id ) ) {
139
+ next ( ) ;
140
+ } else {
141
+ res . redirect ( "back" ) ;
142
+ }
143
+ }
144
+ } ) ;
145
+ } else {
146
+ res . redirect ( "back" ) ;
147
+ }
148
+ }
149
+
117
150
module . exports = router ;
118
151
0 commit comments