bradtraversy / meanauthapp

Complete MEAN stack app with authentication
242 stars 152 forks source link

Check if user with email already exists #39

Open michaelb-01 opened 6 years ago

michaelb-01 commented 6 years ago

Hello, firstly you're tutorials are great and really useful, so thank you!

I wanted to add some validation on the register call to check if a user with the given email already exists. I have this which seems to work but I wanted to check if you think this is the best method or if I should use a preSave hook etc?

module.exports.addUser = function(newUser, callback) {
    // first check if a user with that email already exists
  User.find({email : newUser.email}).exec(function(err, docs) {
    if (docs.length){
        callback('User with email already exists',null);
    } else {
            // encrypt password with bcrypt, then save 
            bcrypt.genSalt(10, (err,salt) => {
                bcrypt.hash(newUser.password, salt, (err, hash) => {
                    if (err) callback('Failed to register user',null);
                    // set password to encrypted password
                    newUser.password = hash;
                    // save new user to the database
                    newUser.save(callback)
                });
            })
    }
  });
}

Then I tweaked the addUser function in the routes/users register method so I can use the message from the callback:

router.post('/register', (req,res,next) => {
    let newUser = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    });

    User.addUser(newUser, (err,user) => {
        console.log(err);
        if (err) {
            res.json({success: false, msg: err}); 
        } else {
            res.json({success: true, msg: err}); 
        }
    })
});

I have validation on the front-end with my form (using angular2 material validation) to specify required fields but do I need to validate that the user has all required fields on the back-end too?

Thanks