40 lines
1.3 KiB
JavaScript
40 lines
1.3 KiB
JavaScript
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',
|
|
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();
|
|
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};
|
|
};
|
|
};
|