Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if user is logged in with 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> 
like image 938
RMontes13 Avatar asked Sep 11 '13 11:09

RMontes13


People also ask

What does Passport authenticate () do?

In this route, passport. authenticate() is middleware which will authenticate the request. By default, when authentication succeeds, the req. user property is set to the authenticated user, a login session is established, and the next function in the stack is called.

Does Passport js use session?

Passport uses serializeUser function to persist user data (after successful authentication) into session. The function deserializeUser is used to retrieve user data from session and perform some condition-based operations.

What is Passport login in node js?

Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.


1 Answers

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 } 

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');     } } 

And use it:

app.get('/orders', loggedIn, function(req, res, next) {     // req.user - will exist     // load user orders and render them }); 
like image 140
moka Avatar answered Oct 07 '22 11:10

moka