A JWT token can not be revoked . JWT is used mainly for authentication of a system, not as an identifier of some process. You can do your thing in two ways:
Generating a record in a table with a field that represents the date when the password restoration was requested.
Generating a token with an expiration date and, when updating your password, deleting the token.
Using a table
The following example is using sequelize and moment :
let email = req.params.email;
let now = Date.now();
models.RecoveryPwd.create({ email, now });
When you enter a password restoration request, check if the deadline has expired:
models.RecoveryPwd.findOne({
email: req.params.email,
state: 'active'
})
.then((request) => {
if (request) {
let now = moment();
let requestTime = moment(request.date);
if (now.diff(requestTime, 'days') >= 1) {
res.jsonp({
success: false,
message: 'El tiempo límite ha expirado. Intente de nuevo'
});
} else {
res.jsonp({ success: true });
}
}
});
Using a token
Using a token is similar, when the password restoration request is made, you generate the token with a maximum time.
jwt.sign(
{
email // guardamos el email en el token
},
'supersecreto',
{
expiresIn: '1d' // tiempo máximo 1d
}
);
This token is saved in sessionStorage
:
sessionStorage.setItem('pwdRecovery', token);
And when the recovery button is clicked, the request is sent to the frontend to send the request to the backend sending the token.
fetch('/url', {
body: sessionStorage.getItem('pwdRecovery');
})
.then((res) => res.json())
.then(({ success, email }) => {
if(success) {
window.location = '/recovery/{email}';
} else {
alert(res.message);
}
});
Upon receiving the backend the token, it is checked if it has not yet expired:
let token = req.body.token;
try {
let decode = jwt.verify(token);
res.jsonp({
success: true,
email: decode.email
});
} catch(e) {
// expiró
res.jsonp({
success: false,
message: 'El tiempo límite ha expirado. Intente de nuevo'
});
}
At the end of this process, if the token has not expired it will be redirected to: http://tuapp.com/[email protected]
, where you must put a form to update the password and send the query email
.
It should be noted that the token must be removed from sessionStorage
if it has already expired or if the password has already been changed.