2023-12-04 13:46:05 +00:00
|
|
|
const {models} = require('vn-loopback/server/server');
|
|
|
|
|
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'
|
2024-04-19 09:36:34 +00:00
|
|
|
},
|
|
|
|
accessScopes: ['DEFAULT', 'read:multimedia']});
|
2023-05-24 13:01:59 +00:00
|
|
|
|
2023-05-24 13:16:04 +00:00
|
|
|
Self.renewToken = async function(ctx) {
|
2023-11-04 15:51:25 +00:00
|
|
|
const {accessToken: token} = ctx.req;
|
2023-05-24 13:01:59 +00:00
|
|
|
|
2024-05-02 08:36:18 +00:00
|
|
|
const {courtesyTime} = await models.AccessTokenConfig.findOne({
|
|
|
|
fields: ['courtesyTime']
|
|
|
|
});
|
2024-04-30 09:35:30 +00:00
|
|
|
const isNotExceeded = await Self.validateToken(ctx);
|
2023-12-22 14:19:45 +00:00
|
|
|
if (isNotExceeded)
|
|
|
|
return token;
|
2023-06-07 08:28:29 +00:00
|
|
|
|
2023-11-04 13:39:26 +00:00
|
|
|
// Schedule to remove current token
|
2023-12-22 14:19:45 +00:00
|
|
|
setTimeout(async() => {
|
|
|
|
try {
|
2024-04-15 06:47:49 +00:00
|
|
|
const exists = await models.AccessToken.findById(token.id);
|
|
|
|
exists && await Self.logout(token.id);
|
2023-12-22 14:19:45 +00:00
|
|
|
} catch (err) {
|
|
|
|
// eslint-disable-next-line no-console
|
|
|
|
console.error(err);
|
|
|
|
}
|
|
|
|
}, courtesyTime * 1000);
|
2023-05-24 13:01:59 +00:00
|
|
|
|
2024-04-15 06:47:27 +00:00
|
|
|
// Get scopes
|
|
|
|
|
|
|
|
let createTokenOptions = {};
|
|
|
|
const {scopes} = token;
|
|
|
|
if (scopes)
|
|
|
|
createTokenOptions = {scopes: [scopes[0]]};
|
2023-11-04 13:39:26 +00:00
|
|
|
// Create new accessToken
|
2023-06-29 10:11:16 +00:00
|
|
|
const user = await Self.findById(token.userId);
|
2024-04-15 06:47:27 +00:00
|
|
|
const accessToken = await user.accessTokens.create(createTokenOptions);
|
2023-05-24 13:01:59 +00:00
|
|
|
|
2023-06-29 10:11:16 +00:00
|
|
|
return {id: accessToken.id, ttl: accessToken.ttl};
|
2023-05-24 13:01:59 +00:00
|
|
|
};
|
|
|
|
};
|