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

67 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

const {models} = require('vn-loopback/server/server');
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'
},
accessScopes: ['DEFAULT', 'read:multimedia']});
Self.renewToken = async function(ctx) {
let createTokenOptions = {};
let token; let isNotExceeded;
2024-06-20 11:49:25 +00:00
try {
token = ctx.req.accessToken;
2024-06-20 11:49:25 +00:00
const {courtesyTime} = await models.AccessTokenConfig.findOne({
fields: ['courtesyTime']
});
isNotExceeded = await Self.validateToken(ctx);
2024-06-20 11:49:25 +00:00
if (isNotExceeded)
return token;
2024-06-20 11:49:25 +00:00
// Schedule to remove current token
setTimeout(async() => {
let exists;
2024-06-20 11:49:25 +00:00
try {
exists = await models.AccessToken.findById(token.id);
2024-06-20 11:49:25 +00:00
exists && await Self.logout(token.id);
} catch (error) {
// eslint-disable-next-line no-console
2024-06-20 11:49:25 +00:00
console.error(error);
const body = {error: error.message, now: Date.now(), userId: token?.userId ?? null, exists};
2024-06-20 11:49:25 +00:00
await handleError(body);
throw new Error(error);
}
}, courtesyTime * 1000);
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);
const accessToken = await user.accessTokens.create(createTokenOptions);
2024-06-20 11:49:25 +00:00
return {id: accessToken.id, ttl: accessToken.ttl};
} catch (error) {
const body = {error: error.message, now: Date.now(), userId: token?.userId ?? null, createTokenOptions, isNotExceeded};
2024-06-20 11:49:25 +00:00
await handleError(body);
throw new Error(error);
}
};
};
2024-06-20 11:49:25 +00:00
async function handleError(body, tag = 'renewToken') {
body = JSON.stringify(body);
2024-06-20 11:49:25 +00:00
await models.Application.rawSql('CALL util.debugAdd(?,?);', [tag, body]);
}