2023-06-07 08:28:29 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
|
2023-05-24 13:01:59 +00:00
|
|
|
module.exports = Self => {
|
|
|
|
Self.remoteMethodCtx('renewToken', {
|
2023-06-07 08:28:29 +00:00
|
|
|
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',
|
2023-05-24 13:01:59 +00:00
|
|
|
accepts: [],
|
2023-05-25 07:51:56 +00:00
|
|
|
returns: {
|
|
|
|
type: 'Object',
|
|
|
|
root: true
|
|
|
|
},
|
2023-05-24 13:01:59 +00:00
|
|
|
http: {
|
|
|
|
path: `/renewToken`,
|
|
|
|
verb: 'POST'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-05-24 13:16:04 +00:00
|
|
|
Self.renewToken = async function(ctx) {
|
2023-05-24 13:01:59 +00:00
|
|
|
const models = Self.app.models;
|
|
|
|
const userId = ctx.req.accessToken.userId;
|
|
|
|
const created = ctx.req.accessToken.created;
|
2023-05-25 07:51:56 +00:00
|
|
|
const tokenId = ctx.req.accessToken.id;
|
2023-05-24 13:01:59 +00:00
|
|
|
|
|
|
|
const now = new Date();
|
2023-06-27 06:24:31 +00:00
|
|
|
const differenceMilliseconds = now - new Date(created);
|
2023-05-24 13:16:04 +00:00
|
|
|
const differenceSeconds = Math.floor(differenceMilliseconds / 1000);
|
2023-05-24 13:01:59 +00:00
|
|
|
|
2023-06-07 08:28:29 +00:00
|
|
|
const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod']});
|
|
|
|
|
|
|
|
if (differenceSeconds <= accessTokenConfig.renewPeriod)
|
|
|
|
throw new UserError(`The renew period has not been exceeded`);
|
2023-05-24 13:01:59 +00:00
|
|
|
|
2023-05-25 08:09:38 +00:00
|
|
|
await Self.logout(tokenId);
|
|
|
|
const user = await Self.findById(userId);
|
|
|
|
const accessToken = await user.createAccessToken();
|
2023-05-24 13:01:59 +00:00
|
|
|
|
|
|
|
return {token: accessToken.id, created: accessToken.created};
|
|
|
|
};
|
|
|
|
};
|