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

45 lines
1.4 KiB
JavaScript
Raw Normal View History

const UserError = require('vn-loopback/util/user-error');
const handlePromiseLogout = (Self, {id}, courtesyTime = 60) => {
new Promise(res => {
setTimeout(() => {
res(Self.logout(id));
}
, courtesyTime * 1000);
});
};
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 token = ctx.req.accessToken;
// Check if current token is valid
const isValid = await Self.validateToken(token);
if (!isValid) throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded');
const fields = ['courtesyTime'];
const {courtesyTime} = await models.AccessTokenConfig.findOne({fields});
// Schedule to remove current token
handlePromiseLogout(Self, token, courtesyTime);
// Create new accessToken
const user = await Self.findById(token.userId);
const accessToken = await user.createAccessToken();
return {id: accessToken.id, ttl: accessToken.ttl};
};
};