node.js 如何知道用户是否使用passport.js 登录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18739725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to know if user is logged in with passport.js?
提问by RMontes13
I've been reading passport.jsinfo and samples for two days, but I'm not sure after that I did all the process of authenticating.
我已经阅读passport.js了两天的信息和样本,但我不确定在那之后我完成了所有的身份验证过程。
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>
回答by moka
If user is logged in, passport.jswill create userobject in reqfor every request in express.js, which you can check for existence in any middleware:
如果用户已登录,passport.js将为user中req的每个请求创建对象in express.js,您可以在任何中间件中检查该对象是否存在:
if (req.user) {
// logged in
} else {
// not logged in
}
You can create simple express.jsmiddleware for that, that will check if user is logged in, and if not - will redirect to /loginpage:
您可以express.js为此创建简单的中间件,它将检查用户是否已登录,如果没有 - 将重定向到/login页面:
function loggedIn(req, res, next) {
if (req.user) {
next();
} else {
res.redirect('/login');
}
}
And use it:
并使用它:
app.get('/orders', loggedIn, function(req, res, next) {
// req.user - will exist
// load user orders and render them
});
回答by cyberwombat
If you would like to use it in your templates as your code sample seems to indicate you can create some middleware such as this:
如果您想在模板中使用它,因为您的代码示例似乎表明您可以创建一些中间件,例如:
app.use(function (req, res, next) {
res.locals.login = req.isAuthenticated();
next();
});
Place that code somewhere after you have setup passport.
设置通行证后,将该代码放在某处。
And then use it in your template (swig example)
然后在您的模板中使用它(swig 示例)
{% if login %}
<button>logout</button>
{% else %}
<button>login</button>
{% endif %}
回答by Zeni
I was searching such solution and came across this page. Question is how to check login status on client side.
我正在搜索这样的解决方案并遇到了这个页面。问题是如何在客户端检查登录状态。
After logging I hide the Login button and show the logout button. On page refresh I again see the login button instead of logout button. The only solution is to save an item in sessionStorage if you are using session (and localStorage if you are using JWT). Delete this item when you logout. Then in every page load check this sessionStorage item and do accordingly.
登录后,我隐藏了登录按钮并显示了注销按钮。在页面刷新时,我再次看到登录按钮而不是注销按钮。唯一的解决方案是在 sessionStorage 中保存一个项目,如果你使用 session(如果你使用 JWT,localStorage)。注销时删除此项。然后在每个页面加载中检查这个 sessionStorage 项目并执行相应的操作。
if (sessionStorage.getItem('status')) {
$("#btnlogout").show();
$("#btnlogin").hide();
// or what ever you want to do
} else {
$("#btnlogout").hide();
$("#btnlogin").show();
}
function Login() {
var data = {
username: $("#myModal #usr").val(),
password: $("#myModal #pw").val()
};
$.ajax({
type: 'POST',
url: '/login',
contentType: 'application/JSON; charset=utf-8',
data: JSON.stringify(data),
success: funcSuccess,
error: funcFail
});
function funcSuccess(res) {
sessionStorage.setItem('status', 'loggedIn');
$("#btnlogout").show();
$("#btnlogin").hide();
}
function funcFail() { $("#pp").text('Login Failed'); };
};
function Logout() {
$.ajax({
type: 'GET',
url: '/logout',
contentType: 'application/JSON; charset=utf-8',
success: funcSuccess,
error: funcFail,
});
function funcSuccess(res) {
$("#btnlogout").hide();
$("#btnlogin").show();
sessionStorage.removeItem("status");
};
function funcFail() { alert('Login method Failed'); };
};
回答by Pankaj
use below code inside app.get() or router.get()
在 app.get() 或 router.get() 中使用以下代码
router.get('/edit/:id', (req, res)=>{
if(req.isAuthenticated()){
if(req.isAuthenticated()){
//
}
else{
res.redirect('/users/login');//your particular login routes
}
});
回答by Hasan Sefa Ozalp
It is not explicitly documented but there is a isAuthenticated()method which is inserted into reqby passport.
Can be used as follows,
它没有明确记录,但有一种isAuthenticated()方法是req由Passport插入的。
可以如下使用,
req.isAuthenticated() // returns true if auth, false if not
// auth.js
module.exports = {
ensureAuthenticated: (req, res, next) => {
if (req.isAuthenticated()) {
return next()
}
res.redirect('/login') // if not auth
},
forwardAuthenticated: (req, res, next) => {
if (!req.isAuthenticated()) {
return next()
}
res.redirect('/dashboard'); // if auth
}
}
// app.js
app.get('/dashboard', ensureAuthenticated, (req, res) => res.render('dashboard'))
app.get('/login', forwardAuthenticated, (req, res) => res.render('login'))
app.get('/register', forwardAuthenticated, (req, res) => res.render('register'))

