-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
98 lines (83 loc) · 2.37 KB
/
middleware.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const { reviewSchema, hotelSchema } = require("./schemas.js");
const ExpressError = require("./utils/ExpressError.js");
const Hotel = require("./model/hotel.js");
const Review = require("./model/review.js");
const isLoggedIn = (req, res, next) => {
// console.log("log");
if (!req.isAuthenticated()) {
req.session.returnTo = req.originalUrl;
req.flash("error", "You must be signed in!");
return res.redirect("/login");
}
next();
};
const storeReturnTo = (req, res, next) => {
if (req.session.returnTo) {
res.locals.returnTo = req.session.returnTo;
}
next();
};
const hotExist = async (req, res, next) => {
const { id } = req.params;
const hotEjs = await Hotel.findById(id);
// console.log("exist");
if (!hotEjs) {
req.flash("error", "No such Hotel Exists!");
return res.redirect("/hotels");
}
next();
};
const isAuthor = async (req, res, next) => {
const { id } = req.params;
const hot = await Hotel.findById(id);
// console.log("below", req.user);
if (!hot.author.equals(req.user._id)) {
req.flash("error", "You do not have Permission for this!");
return res.redirect(`/hotels/${id}`);
}
next();
};
const isReviewAuthor = async (req, res, next) => {
const { id, reviewId } = req.params;
console.log("review id", reviewId);
const review = await Review.findById(reviewId);
console.log("review.author", review.author);
console.log("req.user", req.user);
if (!review.author.equals(req.user._id)) {
req.flash("error", "You do not have Permission for this!");
return res.redirect(`/hotels/${id}`);
}
next();
};
const validateHotel = (req, res, next) => {
// console.log("before", req.body);
const toValidate = { ...req.body };
delete toValidate.deleteImages;
// console.log("after", req.body);
const { error } = hotelSchema.validate(toValidate);
if (error) {
const message = error.details.map((el) => el.message).join(",");
throw new ExpressError(message, 404);
} else {
next();
}
};
const validateReview = (req, res, next) => {
const { error } = reviewSchema.validate(req.body);
if (error) {
const message = error.details.map((el) => el.message).join(",");
throw new ExpressError(message, 404); // Modified line
} else {
next();
}
};
module.exports = {
isLoggedIn,
storeReturnTo,
hotExist,
validateHotel,
isAuthor,
isLoggedIn,
validateReview,
isReviewAuthor,
};