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) {
|
2024-06-20 21:28:11 +00:00
|
|
|
let createTokenOptions = {};
|
|
|
|
let token; let isNotExceeded;
|
2024-06-20 11:49:25 +00:00
|
|
|
try {
|
|
|
|
token = ctx.req.accessToken;
|
2024-06-20 21:28:11 +00:00
|
|
|
|
2024-06-20 11:49:25 +00:00
|
|
|
const {courtesyTime} = await models.AccessTokenConfig.findOne({
|
|
|
|
fields: ['courtesyTime']
|
|
|
|
});
|
2024-06-20 21:28:11 +00:00
|
|
|
isNotExceeded = await Self.validateToken(ctx);
|
2024-06-20 11:49:25 +00:00
|
|
|
if (isNotExceeded)
|
|
|
|
return token;
|
2023-05-24 13:01:59 +00:00
|
|
|
|
2024-06-20 11:49:25 +00:00
|
|
|
// Schedule to remove current token
|
2024-08-27 05:24:10 +00:00
|
|
|
setTimeout(async() => {
|
2024-08-27 08:07:09 +00:00
|
|
|
try {
|
2024-08-27 05:24:10 +00:00
|
|
|
await Self.logout(token.id);
|
2024-08-27 08:07:09 +00:00
|
|
|
} catch (error) {
|
|
|
|
// FIXME: Crash if do throw new Error(error)
|
|
|
|
}
|
2024-06-20 11:49:25 +00:00
|
|
|
}, courtesyTime * 1000);
|
2023-05-24 13:01:59 +00:00
|
|
|
|
2024-06-20 11:49:25 +00:00
|
|
|
// Get scopes
|
|
|
|
const {scopes} = token;
|
|
|
|
if (scopes)
|
|
|
|
createTokenOptions = {scopes: [scopes[0]]};
|
|
|
|
// Create new accessToken
|
|
|
|
const user = await Self.findById(token.userId);
|
2024-06-20 21:28:11 +00:00
|
|
|
const accessToken = await user.accessTokens.create(createTokenOptions);
|
2023-05-24 13:01:59 +00:00
|
|
|
|
2024-06-20 11:49:25 +00:00
|
|
|
return {id: accessToken.id, ttl: accessToken.ttl};
|
|
|
|
} catch (error) {
|
2024-08-26 10:04:03 +00:00
|
|
|
const body = {
|
|
|
|
error: error.message,
|
|
|
|
userId: token?.userId ?? null,
|
|
|
|
token: token?.id,
|
|
|
|
scopes: token?.scopes,
|
|
|
|
createTokenOptions,
|
|
|
|
isNotExceeded
|
|
|
|
};
|
|
|
|
await handleError(JSON.stringify(body));
|
2024-06-20 11:49:25 +00:00
|
|
|
throw new Error(error);
|
|
|
|
}
|
2023-05-24 13:01:59 +00:00
|
|
|
};
|
|
|
|
};
|
2024-06-20 11:49:25 +00:00
|
|
|
|
2024-08-26 10:04:03 +00:00
|
|
|
async function handleError(body) {
|
|
|
|
await models.Application.rawSql('CALL util.debugAdd(?,?);', ['renewToken', body]);
|
2024-06-20 11:49:25 +00:00
|
|
|
}
|