-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
78 lines (54 loc) · 1.94 KB
/
middleware.js
File metadata and controls
78 lines (54 loc) · 1.94 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
71
72
73
74
75
76
const Product = require('./models/product');
const { productSchema,reviewSchema } = require('./schemas');
module.exports.isLoggedIn = (req, res, next) => {
if (req.xhr && !req.isAuthenticated()) {
if (req.session.returnUrl) {
delete req.session.returnUrl;
}
req.flash('error', 'Please login to continue');
return res.status(401).json({msg:'You need to login first'})
}
req.session.returnUrl = req.originalUrl;
if (!req.isAuthenticated()) {
req.flash('error', 'You need to login first to do that!');
return res.redirect('/login');
}
next();
}
module.exports.validateProduct = (req, res, next) => {
const { id } = req.params;
const { name, img, desc, price } = req.body;
const { error} = productSchema.validate({ name, img, price, desc });
if (error) {
const msg = error.details.map((err)=>err.message).join(',')
return res.render('error', { err: msg });
}
next();
}
module.exports.validateReview = (req,res,next) => {
const { rating, comment } = req.body;
const { error } = reviewSchema.validate({ rating, comment });
if (error) {
const msg = error.details.map((err)=>err.message).join(',')
// console.log(msg);
return res.render('error', { err: msg });
}
next();
}
module.exports.isSeller = (req, res, next) => {
if (!(req.user.role && req.user.role === 'seller')) {
req.flash('error', 'You dont have permissions to do that');
return res.redirect('/products');
}
next();
}
module.exports.isProductAuthor = async(req, res, next) => {
// Getting a product id
const { id } = req.params;
const product = await Product.findById(id);
if (!(product.author && product.author.equals(req.user._id))) {
req.flash('error', 'You dont have permissions to do that');
return res.redirect(`/products/${id}`);
}
next();
}