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?
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.
Passport exposes a login() function on req (also aliased as logIn() ) that can be used to establish a login session.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With