我使用Passport进行授权,我的Express应用程序设置。当新用户注册时,我想要进行电子邮件验证。因此,在用户发布凭据后,/ signup路由获取请求并成功重定向到/ sendmail进行验证。
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/sendmail',
failureRedirect : '/signup'
}));
此外,为了防止未经授权的会话,在/注册路由中,用户将被注销并且会话被破坏。
app.get('/sendmail', function(req, res) {
res.render('mailsent.ejs', {
message: 'An email with verification link has been sent to ' + req.user.email + '. Please follow the link in your mail to verify your account before logging in.'
});
/* From keeping user authenticated after signup (not verfied yet)*/
req.logOut();
req.session.destroy();
}
});
我的问题是,由于会话已被破坏,当最终用户刷新浏览器或直接访问/ sendmail路由时,浏览器不会返回任何内容。如何防止这种情况。换句话说,在app.get(&#39; / sendmail&#39;)路线中,我如何检查会话是否开启(有效的请求对象),否则重定向到&#39; /&#39;。< / p>
答案 0 :(得分:1)
您可以像这样使用中间件路由:
app.use('/sendmail', function(req, res, next) { // Middleware for only the `/sendmail` route
if (req.session.authenticated) {
next();
} else {
res.redirect("/");
}
});
或者只是把它放到你的路线上:
app.get('/sendmail', function(req, res) {
if (!req.session.authenticated) {
return res.redirect("/"); // Redirect to home page if not authenticated
}
res.render('mailsent.ejs', {
message: 'An email with verification link has been sent to ' + req.user.email + '. Please follow the link in your mail to verify your account before logging in.'
});
/* From keeping user authenticated after signup (not verfied yet)*/
req.logOut();
req.session.destroy();
}
});