Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  75] [ 4]  / answers: 1 / hits: 26101  / 11 Years ago, wed, may 29, 2013, 12:00:00

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?


More From » node.js

 Answers
3

Please use code from the @Weston answer bellow, because it's more universal and straightforward




Should look something like this



app.post('/sign', function(req, res){
authProvider.saveUser(...do stuff), function(error, user){
if(error){
res.redirect('/sign');
} else {
passport.authenticate('local')(req, res, function () {
res.redirect('/account');
})
}
});
});


I don't sure about name of strategy, but by default LocalStrategy should provide 'local' name



http://passportjs.org/guide/authenticate/


[#77937] Tuesday, May 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
malkajillc

Total Points: 652
Total Questions: 107
Total Answers: 98

Location: Finland
Member since Sat, Nov 6, 2021
3 Years ago
malkajillc questions
;