Full-Stack Web Development with Vue.js and Node

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

As I mentioned, another thing that we will need to check is the password. Let's add method
that compares the password provided by the user while logging in to the password that is


saved in our database:


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

module.exports.comparePassword = (candidatePassword, hash, callback) => {
bcryptjs.compare(candidatePassword, hash, (err, isMatch) => {
if (err) throw err;
callback(null, isMatch);
});
};

The preceding method takes both user-provided password and the saved password and


returns true or false depending on whether the passwords match or not.


Now we are all set to jump into the controller part.


Adding an API endpoint to log a user in


We have added the methods required for a user to be able to log in. Now, the most


important part of this chapter lies here. We need to set up the JWT auth mechanism to


enable a user to log in.


In users.js, add the following lines of code:


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

const passportJWT = require('passport-jwt');
const jwt = require('jsonwebtoken');

const ExtractJwt = passportJWT.ExtractJwt;
const jwtOptions = {};
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
jwtOptions.secretOrKey = 'thisisthesecretkey';

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