Skip to content

Instantly share code, notes, and snippets.

@ANUPAMCHAUDHARY1117
Created April 17, 2020 05:57
Show Gist options
  • Save ANUPAMCHAUDHARY1117/c2854c053cb6fd0d4183675e10ec7d4b to your computer and use it in GitHub Desktop.
Save ANUPAMCHAUDHARY1117/c2854c053cb6fd0d4183675e10ec7d4b to your computer and use it in GitHub Desktop.
const jwt = require('jsonwebtoken');
const jwtOperation = {
sign: function(id) {
return jwt.sign({ id }, process.env.SECRET_KEY, {
expiresIn: 864,
});
},
verify: function(token) {
return jwt.verify(token, process.env.SECRET_KEY, function(err, decoded) {
if (err) {
throw new Error(err);
}
return decoded;
});
},
};
app.post('/login', (req, res) => {
User.findOne({ email: req.body.email }, function (err, user) {
if (err) {
const { output } = Boom.badImplementation();
return errorReponse(res, output);
}
if (!user) {
const { output } = Boom.notFound('No user found.');
return errorReponse(res, output);
}
const passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
if (!passwordIsValid) {
const { output } = Boom.unauthorized({ auth: false, token: null });
return errorReponse(res, output);
}
const token = jwtOperation.sign(user._id);
return res.status(200).cookie('x-access-token', token, {
httpOnly: true,
expires: new Date(Date.now() + 300000),
signed: true,
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment