如何使用Passport JSvalidation用户服务器端?

我想通过生成随机的用户名和密码自动生成用户帐户,然后用户自动login(用户不知道他的用户名/密码,他的浏览器只是存储会话cookie)。

护照function作为中间件,所以我怎么才能authentication我刚刚生成的用户? 或者,最好是redirect到我的app.post('/login')路线,并发送这些variables? (但不知何故将这些发送到浏览器,只是被发回服务器似乎不是很安全或有效)。

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

将您的电话replace为passport.authenticate('local')();

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

让我知道这是怎么回事

rdrey的回答非常有帮助。 一个细节可能对大多数人来说是显而易见的,但对我来说不是这样的,那就是model .save()会在callback中产生错误和logging。 所以整个模式是

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