5

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! I wish that was more apparent on the Passport documentation.
I agree, it's quite hidden and I remember also struggling to find it.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.