371273
371273

Reputation: 5446

How to authenticate a user server-side with Passport JS?

I want to automatically generate user accounts by generating a random username and password, and then the user is logged in automatically (the user doesn't know his username/password, his browser just stores the session cookie).

Passport functions as middleware, so how can I authenticate the user I just generated? Or, would it be better to somehow redirect to my app.post('/login') route and send those variables? (But somehow sending those to the browser, just to be sent back to the server doesn't seem very secure or efficient).

app.get('/signup', function(req, res) {
if(req.isAuthenticated()) { res.redirect('/'); }
else {
    var today = new Date();
    var weekDate = new Date();
    weekDate.setDate(today.getDate() + 7);

    var key1 = Math.random().toString();
    var key2 = Math.random().toString();
    var hash1 = crypto.createHmac('sha1', key1).update(today.valueOf().toString()).digest('hex');
    var hash2 = crypto.createHmac('sha1', key2).update(weekDate.valueOf().toString()).digest('hex');

    var newUser = new models.User({
        username: hash1,
        password: hash2,
        signupDate: today,
        accountStatus: 0,
        expirationDate: weekDate,
    });

    newUser.save(function(err) {
        if(err) {}
        console.log("New user created.");

        //HOW CAN I PASS USERNAME AND PASSWORD ARGUMENTS???
        passport.authenticate('local')();
        res.redirect('/login');
    })
}
});

Upvotes: 5

Views: 2730

Answers (2)

newbie
newbie

Reputation: 11

the answer by rdrey was very helpful. One detail that might be obvious to most but was not to me is that model .save () gets err and the record in the callback. So the pattern in its entirety is

newuser.save(function(err,user) {
req.logIn(user, function(err) {
if (err) { return next(err); }
//copied from the docs, you might want to send the user somewhere else ;)
return res.redirect('/users/' + user.username); 
});

Upvotes: 1

rdrey
rdrey

Reputation: 9529

Replace your call to passport.authenticate('local')(); with

req.logIn(user, function(err) {
  if (err) { return next(err); }
  //copied from the docs, you might want to send the user somewhere else ;)
  return res.redirect('/users/' + user.username); 
});

and let me know how that goes.

Upvotes: 6

Related Questions