salix/back/methods/vn-user/renew-token.js

49 lines
1.6 KiB
JavaScript

module.exports = Self => {
Self.remoteMethodCtx('renewToken', {
description: 'Send email to the user',
accepts: [],
http: {
path: `/renewToken`,
verb: 'POST'
}
});
Self.renewToken = async function(ctx, options) {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const created = ctx.req.accessToken.created;
// const tokenId = ctx.req.accessToken.id;
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const now = new Date();
const differenceMilliseconds = now - created;
const differenceSeconds = Math.floor(differenceMilliseconds / 1000); // Convertir la diferencia a segundos
const accessTokenConfig = await models.AccessTokenConfig.findOne();
if (differenceSeconds <= accessTokenConfig.renewPeriod) {
const response = {
statusCode: 200,
data: {
message: 'Token is active',
}
};
return response;
}
const accessToken = await models.AccessToken.create({userId: userId}, myOptions);
await models.AccessToken.destroyAll({userId: userId}, myOptions);
// await models.AccessToken.destroyById(tokenId, myOptions);
return {token: accessToken.id, created: accessToken.created};
};
};