How with Node - Express - Passport do I use "/" for login and logged-in homepage?

时间:2015-06-25 18:55:22

标签: javascript node.js express login passport.js

I would like to make an application, with Node.js, Express.js, and Passport.js, which on the homepage, if you are not logged in, presents a login form (for now, and maybe later a page offering multiple strategies for authentication). But if you are logged-in, it loads the homepage. The Passport.js docs seem to make it very clear how to have segregated login and homepage URLs, so one need do little more than copy code to have a login form at "/login" that will redirect to itself at "/login" with a flash message if a login failure occurs and will redirect to "/" if your credentials check out. However, I don't see how to serve integrated service from one URL, where the site homepage renders a "Please authenticate yourself by one of these strategies" page (or possibly links to one login page per strategy, but I am not interested in that question now) if you are not logged in, and renders the actual logged-in homepage content if a user is logged in. How should I be doing that? Let's say I'm using the username-password strategy from passport-local for now while I'm trying to nail down a couple of details on being established with Facebook.

1 个答案:

答案 0 :(得分:1)

You can check for req.user on your main route and redirect accordingly. app.get('/', function mainRoute(req, res, next) { if (!req.user) res.redirect('/login'); else res.render('home'); });