-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.js
More file actions
70 lines (58 loc) · 2.4 KB
/
Copy pathmiddleware.js
File metadata and controls
70 lines (58 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const Listing = require("./models/listing");
const Review = require("./models/review");
module.exports.isLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
req.session.redirectUrl = req.originalUrl; // Save the current URL to redirect after login
req.flash("error_msg", "You must be logged in");
return res.redirect("/login");
}
next(); // Proceed to the next middleware or route handler
};
module.exports.saveRedirectUrl = (req, res, next) => {
if (req.session.redirectUrl) {
res.locals.redirectUrl = req.session.redirectUrl; // Make the redirect URL available to templates
}
next(); // Continue to the next middleware or route handler
};
module.exports.isOwner = async (req, res, next) => {
const { id } = req.params;
try {
const listing = await Listing.findById(id);
// Handle the case where the listing doesn't exist
if (!listing) {
req.flash("error_msg", "Listing not found.");
return res.redirect("/listings");
}
// Check if the logged-in user is the owner of the listing
if (!listing.owner.equals(req.user._id)) {
req.flash("error_msg", "You don't have access to modify this listing.");
return res.redirect(`/listings/${id}`);
}
next(); // Proceed to the next middleware or route handler
} catch (err) {
console.error("Error in isOwner middleware:", err);
req.flash("error_msg", "An error occurred.");
res.redirect("/listings");
}
};
module.exports.isAuthor = async (req, res, next) => {
const { id, reviewid } = req.params;
try {
const foundReview = await Review.findById(reviewid);
// Handle the case where the review is not found
if (!foundReview) {
req.flash("error_msg", "Review not found.");
return res.redirect(`/listings/${id}`);
}
// Check if the logged-in user is the author of the review
if (!foundReview.author.equals(req.user._id)) {
req.flash("error_msg", "You are not the author of this review.");
return res.redirect(`/listings/${id}`);
}
next(); // Proceed to the next middleware or route handler
} catch (err) {
console.error("Error in isAuthor middleware:", err);
req.flash("error_msg", "An error occurred.");
res.redirect(`/listings/${id}`);
}
};