且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何知道用户是否使用passport.js 登录?

更新时间:2023-12-04 11:09:46

如果用户已登录,passport.js 将在 requser 对象/code> 用于 express.js 中的每个请求,您可以检查它是否存在于任何中间件中:

If user is logged in, passport.js will create user object in req for every request in express.js, which you can check for existence in any middleware:

if (req.user) {
    // logged in
} else {
    // not logged in
}

您可以为此创建简单的 express.js 中间件,它会检查用户是否已登录,如果没有 - 将重定向到 /login 页面:>

You can create simple express.js middleware for that, that will check if user is logged in, and if not - will redirect to /login page:

function loggedIn(req, res, next) {
    if (req.user) {
        next();
    } else {
        res.redirect('/login');
    }
}

并使用它:

app.get('/orders', loggedIn, function(req, res, next) {
    // req.user - will exist
    // load user orders and render them
});