且构网

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

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

更新时间:2023-12-04 11:22:34

如果用户登录, passport.js 将为 req 中的用户对象$ c> 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
});