bradtraversy / node_passport_login

Node.js login, registration and access control using Express and Passport
1.74k stars 1.3k forks source link

Entry in database #12

Closed harshittpandey closed 5 years ago

harshittpandey commented 7 years ago

image

many people can register with same username.

Saspect-IO commented 7 years ago

That's because there are no params set for username. You can set it to unique in the model schema and drop duplicate. See link below. You can also setup a search function to check the database by username and if input is in database then alert user to enter new username.

https://stackoverflow.com/questions/28649593/how-to-ensure-a-unique-email-username-will-enter-into-mongodb-using-mongoose

chia7 commented 7 years ago

Can I use customize express-validator to do that? I've try a few ways but they do not work out. The User.findOne function would not return instantly, cause the registration success.

Saspect-IO commented 7 years ago

You need to use a promise, Try this code below, modified from this link :https://stackoverflow.com/questions/35008433/i-am-using-node-js-promise-for-validating-either-username-exist-in-db-or-not

function findUser() {
  return User.findOne({"username": req.body.username}).then(function(user) {
    if (user.username) {
console.log(user.username);
req.flash('success_msg', 'Username Already Exist, Please Enter a different username');
 res.redirect('/users/register');
      throw new Error('Username already exists!');
    }

    // user doesn't exist, all is good in your case
  }, function(err) {
    // handle mongoose errors here if needed

    // rethrow an error so the caller knows about it
    throw new Error('Some Mongoose error happened!');
    // or throw err; if you want the caller to know exactly what happened
  });
}

Then you call the find user function here.

findUser().then(function() { // user doesn't exist, do your stuff User.createUser(newUser, function(err, user){ f(err){ } }); req.flash('success_msg', 'You are registered and can now login'); res.redirect('/users/login'); }).catch(function(err) { // here, you'll have Mongoose errors or 'User already exists!' error console.log(err.message); });

Really hope this helps