Authentication

To authenticate a user, we need to implement an endpoint. Follow these steps to implement the authentication process:

  1. Define router inside server/api/index.js:
router.post('/users/signin', User.signin);
  1. Define the signin method inside the user controller inside server/api/user.js:
signin: (req, res) => {
Model.users
.authenticate(req.body.user)
.then(user => handleSuccess(res, { user }))
.catch(errors =>
handleFailure(res, { errors, message: errors.message, status: 401 }),
);
},
  1. Define the authenticate method inside the users model (server/models/users.js):
Schema.statics.authenticate = function(params = {}) {
return new Promise((resolve, reject) => {
try {
const emptries = ['email', 'password'].filter(key =>
[undefined].includes(params[key]),
);

if (emptries.length) {
throw emptries.reduce(
(obj, key) => ({
...obj,
[key]: `${key.humanize()} can't be blank`,
}),
{},
);
}

this.findOne({ email: params.email, deleted: [false, null] }).then(
user => {
if (!user || !bcrypt.compareSync(params.password, user.password)) {
reject(
new Error('Authentication failed. Invalid user or password.'),
);
} else {
resolve(
user.toJson({
token: generateToken({ loginKey: user.loginKey }),
}),
);
}
},
);
} catch (e) {
reject(e);
}
});
};

The authenticate method takes email and password as arguments and checks with the database. If the user is valid, a token is generated token: generateToken({ loginKey: user.loginKey }) and returned as the response. 

  1. We need to define the generateToken function. Create a jwt.js file inside server/helpers/jwt.js. Define two functions: generateToken, to generate a new token, and verifyToken, to verify whether an existing token is valid:
const jwt = require('jsonwebtoken');

const JWT_SECRET = process.env.SECRET || 'somethingkey';

const generateToken = data =>
jwt.sign(data, JWT_SECRET, { expiresIn: process.env.EXPIRED_LOGIN || '1d' });

const verifyToken = token =>
new Promise((resolve, reject) => {
if (!token) {
return reject(new Error('Token is null or expired'));
}

return jwt.verify(
token,
JWT_SECRET,
(err, decoded) => (err || !decoded ? reject(err) : resolve(decoded)),
);
});

module.exports = { generateToken, verifyToken };
  1. Use Rested to test the authentication endpoint. If you check out the following screenshot, valid credentials generate token:

Figure 8.3: Request/Response using the HTTP client for the /api/users/signin endpoint
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset