Nodejs + Passport:如何添加更多用户信息

Ryo*_*Ryo 8 node.js passport.js

我是Nodejs的新手,正在寻找用户凭证管理,我认为Passport是个不错的选择.

但在Passport的注册策略中,我只看到保存的用户信息是电子邮件和密码.

我需要更多的用户信息,如全名,工作,注册时间,上次活动时间等.

那么我怎样才能在Passport中做到这一点?

Cha*_*ish 7

在Passport.js注册/注册策略中,您应该能够将请求对象作为该函数的第一个参数传递,Passport将负责将您的请求传递给您的函数.

因此,您应该能够使用该req.body对象,从该表单获取数据并将其存储到您的数据库中.

下面是一个如何工作的更详细的例子.

passport.use('signup', new LocalStrategy({
    passReqToCallback : true
  },
  function(req, username, password, done) {
    findOrCreateUser = function(){
      // find a user in Mongo with provided username
      User.findOne({'username':username},function(err, user) {
        // In case of any error return
        if (err){
          console.log('Error in Signup: ' + err);
          return done(err);
        }
        // already exists
        if (user) {
          console.log('User already exists');
          return done(null, false, 
             req.flash('message','User Already Exists'));
        } else {
          // if there is no user with that email
          // create the user
          var newUser = new User();
          // set the user's local credentials
          newUser.username = username;
          newUser.password = createHash(password);
          newUser.firstName = req.body.firstName;
          newUser.lastName = req.body.lastName;

          // save the user
          newUser.save(function(err) {
            if (err){
              console.log('Error in Saving user: '+err);  
              throw err;  
            }
            console.log('User Registration succesful');    
            return done(null, newUser);
          });
        }
      });
    };

    // Delay the execution of findOrCreateUser and execute 
    // the method in the next tick of the event loop
    process.nextTick(findOrCreateUser);
  });
);
Run Code Online (Sandbox Code Playgroud)

这是一个教程,更详细地介绍它.我确实将params中的firstName和lastName参数更改为正文中的变量.但您可以使用params或body将这些数据导入您的本地策略.