Tute 12.01: Code Split: Separate code from app.js to other file to make it more usable - ariffira/node-basic GitHub Wiki

**From the tute 12 we will change the code: **

open user.js model and add this function, then add code for password hash from tute12 and export it:

// add bcrypt package before

// Add user and hash password before
module.exports.addUser = function (newUser, callback) {
    // Save user data using bcryptjs
    const saltRounds = 5;
    // encrypt password first using salt
    bcrypt.hash(newUser.password, saltRounds, (err, hash) => {
        if(err) throw err;
        // make hash as your new password
        newUser.password = hash;
        // save all data to DB now
        newUser.save(callback);
    });
};

Change your app.js registration routes also and add this code:

    // create new user and save data to DB
    User.addUser(newUser, (err, user) => {
        if (err) {
            res.json({
                success: false,
                msg: 'Failed to register...'
            });
        }
        else {
            res.redirect('/signin');
        }
    });

Now check your registration again.

Works fine! Great.