Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport + Node.js / Automatic login after adding user

I am using passport for authentication and session handling. Everything works fine so far. I implemented a "Sign in" form to add new users to the app. After a user is added I would like to log him/her in automatically.

What is the best way to achieve this - should I redirect to "/login" with the user credentials or is there another/better way(call serializeUser) to do that?

So far I think I did not really understand the way the "done" function (in serializeUser and LocalStrategy) is working or what it is doing ...

Here is my code:

passport.serializeUser(function(user, done) {     done(null, user._id); }); passport.deserializeUser(function(id, done) {     authProvider.findUserById('users', id, function (err, user) {         done(err, user);     }); });  passport.use(new LocalStrategy( function(email, password, done) {     authProvider.getUserByEmail('users', email, function(error, user){         if(error) { return done(error); }         if (!user) { return done(null, false, { message: 'Unknown user ' + email });}            if (user.password != password) { return done(null, false);}         return done(null, user);         });     } ));  app.post('/login',      passport.authenticate('local', { failureRedirect: '/login'}),     function(req, res) { res.redirect('/');});  app.post('/sign', function(req, res){     authProvider.saveUser(...do stuff), function(error, user){         if(error){             res.redirect('/sign');         } else {             res.redirect('/');         }     }); }); 

Does someone know how to do this?

like image 286
user937284 Avatar asked May 29 '13 15:05

user937284


People also ask

How does Passport js handle authorization?

Authorization is performed by calling passport. authorize() . If authorization is granted, the result provided by the strategy's verify callback will be assigned to req.account . The existing login session and req.

What does Passport .login do?

Passport exposes a login() function on req (also aliased as logIn() ) that can be used to establish a login session.


1 Answers

Based on the Passport Guide req.login() is intended for this exact purpose.

This function is primarily used when users sign up, during which req.login() can be invoked to automatically log in the newly registered user.

Modifying krasu's code:

app.post('/sign', function(req, res){     authProvider.saveUser(...do stuff), function(error, user){         if ( error ){             res.redirect('/sign');         } else {             req.login(user, function (err) {                 if ( ! err ){                     res.redirect('/account');                 } else {                     //handle error                 }             })         }     }); }); 

The potential error from the login() callback would come from your serializeUser() function.

like image 142
Weston Avatar answered Oct 07 '22 16:10

Weston