Ryo
Ryo

Reputation: 1035

Nodejs + Passport: How to add more user information

I'm new to Nodejs and looking for a user credential management, I see that Passport a good option.

But in Passport's registration strategy, I only see that user information saved is email and password.

I need more user information like full name, job, registration time, last activity time, etc.

So how can I do this in Passport?

Upvotes: 9

Views: 5136

Answers (3)

Tha Truth
Tha Truth

Reputation: 11

when making a request for the newUser args other params should be requested from the form body like so newUser.local.fname = req.body.fname

Upvotes: 1

Charlie Fish
Charlie Fish

Reputation: 20496

Inside of your Passport.js signup/register strategy you should be able to just pass the request object in as the first parameter of that function and Passport will take care of passing your request into your function for you.

So you should be able to use the req.body object, get the data from your form that way and store that to your database.

Below is a more detailed example of how this would work.

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

Here is a tutorial that covers it in a bit more detail. I did change the firstName and lastName parameters from params to variables in the body. But you can either use params or body to get that data into your local strategy.

Upvotes: 7

Cory Kertz
Cory Kertz

Reputation: 1

I found that this worked better. It seemed to be key that the done be after the req, username, password but before the other variables your desired to pass into the function. If done was placed at the end then:

events.js:160 throw er; // Unhandled 'error' event TypeError: done is not a function

would be returned.

// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'

passport.use('local-signup', new LocalStrategy({
    // by default, local strategy uses username and password, we will override with email
    usernameField : 'username',
    passwordField : 'password',
    passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req,  username, password, done, fname, lname, email, security_question, security_answer) {

    // asynchronous
    // User.findOne wont fire unless data is sent back
    process.nextTick(function() {

    // find a user whose email is the same as the forms email
    // we are checking to see if the user trying to login already exists

          User.findOne({ 'local.username' :  username }, function(err, user) {
              // if there are any errors, return the error
              if (err)
                  return done(err);

              // check to see if theres already a user with that email
              if (user) {
                  return done(null, false, req.flash('signupMessage', 'That username is already taken.'));
              } else {

                  // if there is no user with that email
                  // create the user
                  var newUser            = new User();

                  // set the user's local credentials
                  newUser.local.fname    = fname;
                  newUser.local.lname    = lname;
                  newUser.local.username = username;
                  newUser.local.email    = email;
                  newUser.local.password = newUser.generateHash(password);
                  newUser.local.security_question    = security_question;
                  newUser.local.security_answer = newUser.generateHash(security_answer);

                  // save the user
                  newUser.save(function(err) {
                      if (err)
                          throw err;
                      return done(null, newUser);
                  });
              }
          });




    });
}));

Upvotes: -1

Related Questions