39 lines
1.3 KiB
JavaScript
39 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 token = ctx.req.accessToken;
|
|
|
|
const now = new Date();
|
|
const differenceMilliseconds = now - token.created;
|
|
const differenceSeconds = Math.floor(differenceMilliseconds / 1000);
|
|
|
|
const fields = ['renewPeriod', 'courtesyTime'];
|
|
const accessTokenConfig = await models.AccessTokenConfig.findOne({fields});
|
|
|
|
if (differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime)
|
|
throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded');
|
|
|
|
await Self.logout(token.id);
|
|
const user = await Self.findById(token.userId);
|
|
const accessToken = await user.createAccessToken();
|
|
|
|
return {id: accessToken.id, ttl: accessToken.ttl};
|
|
};
|
|
};
|