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');
})
}
});
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.
This module lets you authenticate using OAuth 2.0 in your Node. js applications. By plugging into Passport, OAuth 2.0 authentication can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.
A Passport strategy for authenticating with a JSON Web Token. This module lets you authenticate endpoints using a JSON web token. It is intended to be used to secure RESTful endpoints without sessions.
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.
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);
});
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