【问题标题】:How to handle expired routes / sessions in express?如何在快递中处理过期的路线/会话?
【发布时间】:2016-08-12 21:28:26
【问题描述】:

我使用 Passport 设置了我的 Express 应用程序以进行授权。当一个新用户注册时,我想做一个电子邮件验证。因此,在用户发布凭据后,/signup 路由获取请求并成功重定向到 /sendmail 进行验证。

app.post('/signup', passport.authenticate('local-signup', {
    successRedirect : '/sendmail', 
    failureRedirect : '/signup'
}));

另外,为了防止未经授权的会话,在 /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('/sendmail') 路由中,我将如何检查会话是否开启(有效的 req 对象)否则重定向到 '/'。

【问题讨论】:

    标签: node.js session express routes


    【解决方案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();
        }
    });
    

    【讨论】:

    • 这里,req.session.authenticated 是未定义的,因此 '/sendmail' 只是重定向到 '/'
    • 好吧,这只是一个例子,您需要设置某种会话变量来确定是否应该对它们进行身份验证。如果需要,请将 req.session.authenticated 替换为 req.session.email,只要在验证时应设置的任何内容即可
    • 好吧,req.session 总是返回 false。但是req.user 为我工作。我正在测试 MEAN 堆栈,到目前为止我喜欢它。谢谢。
    猜你喜欢
    • 2016-03-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 2016-05-23
    • 1970-01-01
    • 2011-06-26
    相关资源
    最近更新 更多