-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
62 lines (54 loc) · 1.69 KB
/
middleware.js
File metadata and controls
62 lines (54 loc) · 1.69 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
const passport = require('passport');
const { productSchema, productInputSchema } = require('./schema');
const ExpressError = require('./utils/expressError');
module.exports.validateProduct = (req, res, next)=>{
const { error } = productSchema.validate(req.body);
if(error){
const message = error.details.map(el => el.message).join(',');
throw new ExpressError(message, 400)
}else{
next();
}
};
module.exports.validateProductInput = (req, res, next)=>{
const { error } = productInputSchema.validate(req.body);
if(error){
const message = error.details.map(el => el.message).join(',');
throw new ExpressError(message, 400)
}else{
next();
}
};
module.exports.loginAuthenticate = passport.authenticate('local', {
failureFlash : true,
failureRedirect : '/login'
});
module.exports.isLoggedIn = (req, res, next)=>{
if(!req.isAuthenticated()){
req.session.returnTo = req.originalUrl;
req.flash('error', 'You must be signed in first');
return res.redirect('/login')
}
next()
}
module.exports.storeReturnTo = (req, res, next) => {
// Check if returnTo is in the request body (sent from the form)
if (req.body.returnTo) {
res.locals.returnTo = req.body.returnTo;
}
// Fall back to session if available
else if (req.session.returnTo) {
res.locals.returnTo = req.session.returnTo;
}
// Fall back to referer header
else if (req.get('referer')) {
res.locals.returnTo = req.get('referer');
}
next();
};
module.exports.redirectIfLoggedIn = (req, res, next)=>{
if (req.isAuthenticated()) {
return res.redirect('/');
}
next();
}