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

40 lines
1.3 KiB
JavaScript
Raw Normal View History

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('renewToken', {
description: 'Checks if the token has more than renewPeriod seconds to live and if so, renews it',
2023-06-21 12:12:42 +00:00
accessType: 'WRITE',
accepts: [],
returns: {
type: 'Object',
root: true
},
http: {
path: `/renewToken`,
verb: 'POST'
}
});
Self.renewToken = async function(ctx) {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const created = ctx.req.accessToken.created;
const tokenId = ctx.req.accessToken.id;
const now = new Date();
2023-06-27 06:24:31 +00:00
const differenceMilliseconds = now - new Date(created);
const differenceSeconds = Math.floor(differenceMilliseconds / 1000);
const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod']});
if (differenceSeconds <= accessTokenConfig.renewPeriod)
throw new UserError(`The renew period has not been exceeded`);
await Self.logout(tokenId);
const user = await Self.findById(userId);
const accessToken = await user.createAccessToken();
return {token: accessToken.id, created: accessToken.created};
};
};