Full-Stack Web Development with Vue.js and Node

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

As you can see in the preceding code, if there is a failure in the request, we will send a
message saying Something went wrong. We can also display different types of message


depending on the server's response.


Setting up the user login


Now that we have successfully implemented the login process for a user, let's start building


the functionality to log users in to our app.


Modifying the User model


To log in users to the app, we will take the following two parameters: the user's email and
their password. We will need to query the database to find the record with their given


email; so, let's add a method that will extract the user according to the username:


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

module.exports.getUserByEmail = (email, callback) => {
const query = { email };
User.findOne(query, callback);
};

The preceding method will return the user that has the given email.

Free download pdf