如何使用护照JS身份验证用户服务器端



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

护照作为中间件的功能,那么如何验证我刚刚生成的用户?或者,以某种方式重定向到我的app.post('/login')路线并发送这些变量会更好吗?(但是以某种方式将它们发送到浏览器,只是将其发送回服务器似乎并不是很安全或有效)。

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

将您的调用替换为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()获取错误和回调中的记录。因此,整体模式为

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

最新更新