I am working on a Node.JS project with express. I want to send to my users emails with reset password links. Those links have a jwt token thaat expires f.e. 15 minutes after the creation.How can i force-expire the token if the user change his password?
My purpose is to avoid rechange the password many times.
My code until now is:
exports.resetPasswordRequest = async (req, res) =>{
res.status(200).json({status: 'success', message: "Your request was successfully submitted" });
if(req.body.email){
const email = req.body.email;
const user = await User.findOne({ where: { email: email } });
if(user){
if(user.acc_status === 1){
//Create Token
const payload = {
email: user.email,
id: user.id
}
const token = jwt.sign(payload, config.secret,{
expiresIn: config.jwtResetPasswordExpiration,
});
const link = FE_LINK + '/auth/reset-password/'+ token + '?source=email'
sendPasswordResetEmail(email, link)
}
}
}
}
and for the change password functionality:
exports.updatePassword = async (req, res) =>{
const {id, oldPassword, newPassword, resetPasswordToken} = req.body
//Check if token is valid
const secret = config.secret
jwt.verify(req.body.resetPasswordToken, secret, (err, decoded)=>{
if (err) {
return res.status(200).json({ message: 'INVALID' });
}
let user_id = decoded.id
User.findOne({
where: {
id: user_id
}
}).then(async (user) => {
if(oldPassword){
if(bcrypt.compareSync(oldPassword,user.password) == false){
return res.status(200).json({ error:"true",message: 'Your current password is wrong' });
}
}
user.password = bcrypt.hashSync(newPassword, 8)
user.password_changedAt = new Date()
user.new_password_required = false
await user.save();
return res.status(200).json({ error:"false",message: 'You changed your password successfully' });
}).catch(err => {
res.status(500).send({ error:"true",message: err.message });
});
})
};
How do you suggest I proceed? Thanks
You can't force expire a jwt once it's already created.
You can do either set the token expire for small amount of time as possible or save the token on your Database and tag it as invalid then check it in your backend