-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
75 lines (67 loc) · 2.8 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
const Activity = require('./models/activity');
const Review = require('./models/review');
const { activitySchema, reviewSchema } = require('./schemas');
const ExpressError = require('./utils/ExpressError');
// check if user is logged in
const isLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
// use session to store the url that triggers login
req.session.returnTo = req.originalUrl;
req.flash('error', 'You must be signed in first.');
return res.redirect('/login');
}
next();
}
// check if user is author of activity
const isActivityAuthor = async (req, res, next) => {
const activity = await Activity.findById(req.params.id);
if (!req.user || !activity.author.equals(req.user._id)) {
// prohibit editing/deleting if user is not the activity's author
req.flash("error", "You are not authorized to modify this activity!");
res.redirect(`/activities/${req.params.id}`);
} else {
next();
}
}
// check if user is author of review
const isReviewAuthor = async (req, res, next) => {
const review = await Review.findById(req.params.reviewId);
if (!req.user || !review.author.equals(req.user._id)) {
// prohibit editing/deleting if user is not the review's author
req.flash("error", "You are not authorized to modify this review!");
res.redirect(`/activities/${req.params.id}`);
} else {
next();
}
}
// define a middleware function to validate activity form data on server-side
function validateActivity(req, res, next) {
// The value is validated against the defined joi schema
const { error } = activitySchema.validate(req.body);
// throws error if there is error
if (error) {
// Joi returns an array of error details, each contains a message
const message = error.details.map(ele => ele.message).join(',');
// this will be handled by error handler
throw new ExpressError(message, 400);
} else {
// if no error, then pass control to next middleware/route handler callback
next();
}
};
// define a middleware function to validate review form data on server-side
function validateReview(req, res, next) {
// The value is validated against the defined joi schema
const { error } = reviewSchema.validate(req.body);
// throws error if there is error
if (error) {
// Joi returns an array of error details, each contains a message
const message = error.details.map(ele => ele.message).join(',');
// this will be handled by error handler
throw new ExpressError(message, 400);
} else {
// if no error, then pass control to next middleware/route handler callback
next();
}
};
module.exports = { isLoggedIn, isActivityAuthor, isReviewAuthor, validateActivity, validateReview };