@@ -62,18 +62,14 @@ router.post("/", isLoggedIn, function(req, res) {
62
62
} ) ;
63
63
64
64
// EDIT Campground route
65
- router . get ( "/:id/edit" , function ( req , res ) {
65
+ router . get ( "/:id/edit" , checkCampgroundOwnership , function ( req , res ) {
66
66
Campground . findById ( req . params . id , function ( err , foundCampground ) {
67
- if ( err ) {
68
- res . redirect ( "/campgrounds" ) ;
69
- } else {
70
- res . render ( "campgrounds/edit" , { campground : foundCampground } ) ;
71
- }
67
+ res . render ( "campgrounds/edit" , { campground : foundCampground } ) ;
72
68
} ) ;
73
69
} ) ;
74
70
75
71
// UPDATE Campground route
76
- router . put ( "/:id" , function ( req , res ) {
72
+ router . put ( "/:id" , checkCampgroundOwnership , function ( req , res ) {
77
73
// find and update the correct campground
78
74
Campground . findByIdAndUpdate ( req . params . id , req . body . campground , function ( err , updatedCamground ) {
79
75
if ( err ) {
@@ -86,7 +82,7 @@ router.put("/:id", function(req, res) {
86
82
} ) ;
87
83
88
84
// DESTROY Campground Route
89
- router . delete ( "/:id/" , function ( req , res ) {
85
+ router . delete ( "/:id/" , checkCampgroundOwnership , function ( req , res ) {
90
86
Campground . findByIdAndRemove ( req . params . id , function ( err ) {
91
87
if ( err ) {
92
88
res . redirect ( "/campgrounds" ) ;
@@ -96,7 +92,27 @@ router.delete("/:id/", function(req, res) {
96
92
} ) ;
97
93
} ) ;
98
94
99
- // middleware function to check if user is logged in
95
+ // middleware
96
+ function checkCampgroundOwnership ( req , res , next ) {
97
+ if ( req . isAuthenticated ( ) ) {
98
+ Campground . findById ( req . params . id , function ( err , foundCampground ) {
99
+ if ( err ) {
100
+ res . redirect ( "/campgrounds" ) ;
101
+ } else {
102
+ // does user own the camground?
103
+ if ( foundCampground . author . id . equals ( req . user . _id ) ) {
104
+ next ( ) ;
105
+ } else {
106
+ res . redirect ( "back" ) ;
107
+ }
108
+ }
109
+ } ) ;
110
+ } else {
111
+ res . redirect ( "back" ) ;
112
+ }
113
+ }
114
+
115
+ // middleware
100
116
function isLoggedIn ( req , res , next ) {
101
117
if ( req . isAuthenticated ( ) ) {
102
118
return next ( ) ;
0 commit comments