Full-Stack Web Development with Vue.js and Node

(singke) #1
Building Authentication with passport.js Chapter 6

Now, when we save a user, we should create our own method to add users to the
database, as we want to encrypt their passwords. So, let's add the following code


to models/User.js:


const User = mongoose.model('User', UserSchema);
module.exports = User;

module.exports.createUser = (newUser, callback) => {
bcryptjs.genSalt(10, (err, salt) => {
bcryptjs.hash(newUser.password, salt, (error, hash) => {
// store the hashed password
const newUserResource = newUser;
newUserResource.password = hash;
newUserResource.save(callback);
});
});
};

In the preceding code, we have used the bcrypt library, which uses a genSalt mechanism


to convert a password into an encrypted string. The preceding method—createUser—in


the User model takes the user object, converts the user-provided password into a bcrypted


password, and then saves it to the database.


Adding API endpoint to register a user


Now that we have our model ready, let's move on to creating an endpoint to create a user.


For that, let's first create a controller called users.js in the controllers folder to


manage all user related requests. Since we have added a code block to initialize all the files


inside the controllers directory in server.js, we do not need to require those files


here.


In users.js, replace the file's contents with the following code:


const User = require('../models/User.js');

module.exports.controller = (app) => {
// register a user
app.post('/users/register', (req, res) => {
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
const newUser = new User({
Free download pdf