如何知道用户是否使用passport.js 登录? [英] How to know if user is logged in with 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
将在 req<中创建
user
对象/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
});
这篇关于如何知道用户是否使用passport.js 登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!