如何知道用户是否使用passport.js登录? [英] How to know if user is logged in with passport.js?

查看:115
本文介绍了如何知道用户是否使用passport.js登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读 passport.js 信息和样本两天,但我不知道之后,我做了所有的认证过程。

I've been reading passport.js info and samples for two days, but I'm not sure after that I did all the process of authenticating.

我如何知道我是否登录,例如,我将有一个带有登录或注销按钮的导航栏,是否有一些变量,如下面的代码?

How do I know if I'm logged in, for example, I'll have a navigation bar with a login or logout button, is there some variable like code below?

if (login)
   <button>logout</button>
else 
   <button>login</button>


推荐答案

如果用户登录, passport.js 将为<$ c中的每个请求创建 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
});

这篇关于如何知道用户是否使用passport.js登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆