freeCodeCamp/server/utils/middleware.js

56 lines
1.2 KiB
JavaScript
Raw Normal View History

export function ifNoUserRedirectTo(url, message, type = 'danger') {
2015-06-20 11:43:12 -07:00
return function(req, res, next) {
2015-10-06 00:13:51 -07:00
const { path } = req;
2015-06-20 11:43:12 -07:00
if (req.user) {
return next();
}
2015-10-06 00:13:51 -07:00
req.flash(type, {
msg: message || `You must be signed in to access ${path}`
2015-10-06 00:13:51 -07:00
});
2015-06-20 11:43:12 -07:00
return res.redirect(url);
};
2015-10-02 11:47:36 -07:00
}
2015-06-20 11:43:12 -07:00
2015-10-02 11:47:36 -07:00
export function ifNoUserSend(sendThis) {
return function(req, res, next) {
if (req.user) {
return next();
}
return res.status(200).send(sendThis);
};
2015-10-02 11:47:36 -07:00
}
2015-10-02 11:47:36 -07:00
export function ifNoUser401(req, res, next) {
if (req.user) {
return next();
}
return res.status(401).end();
2015-10-02 11:47:36 -07:00
}
export function ifNotVerifiedRedirectToSettings(req, res, next) {
const { user } = req;
if (!user) {
return next();
}
if (!user.emailVerified) {
req.flash('danger', {
msg: 'We do not have your verified email address on record, '
+ 'please add it in the settings to continue with your request.'
});
return res.redirect('/settings');
}
return next();
}
export function ifUserRedirectTo(path = '/', status) {
status = status === 302 ? 302 : 301;
return (req, res, next) => {
if (req.user) {
return res.status(status).redirect(path);
}
return next();
};
}