#6264 - FIX - Log renewToken when not success #2619

Merged
jsegarra merged 4 commits from 6264_log_tmp_renewToken into master 2024-06-21 05:17:19 +00:00
2 changed files with 61 additions and 29 deletions

View File

@ -16,36 +16,51 @@ module.exports = Self => {
accessScopes: ['DEFAULT', 'read:multimedia']});
Self.renewToken = async function(ctx) {
const {accessToken: token} = ctx.req;
const {courtesyTime} = await models.AccessTokenConfig.findOne({
fields: ['courtesyTime']
});
const isNotExceeded = await Self.validateToken(ctx);
if (isNotExceeded)
return token;
// Schedule to remove current token
setTimeout(async() => {
try {
const exists = await models.AccessToken.findById(token.id);
exists && await Self.logout(token.id);
} catch (err) {
// eslint-disable-next-line no-console
console.error(err);
}
}, courtesyTime * 1000);
// Get scopes
let createTokenOptions = {};
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);
let token; let isNotExceeded;
try {
token = ctx.req.accessToken;
return {id: accessToken.id, ttl: accessToken.ttl};
const {courtesyTime} = await models.AccessTokenConfig.findOne({
fields: ['courtesyTime']
});
isNotExceeded = await Self.validateToken(ctx);
if (isNotExceeded)
return token;
// Schedule to remove current token
setTimeout(async() => {
let exists;
try {
exists = await models.AccessToken.findById(token.id);
exists && await Self.logout(token.id);
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
const body = {error: error.message, now: Date.now(), userId: token?.userId ?? null, exists};
await handleError(body);
throw new Error(error);
}
}, courtesyTime * 1000);
// 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);
return {id: accessToken.id, ttl: accessToken.ttl};
} catch (error) {
const body = {error: error.message, now: Date.now(), userId: token?.userId ?? null, createTokenOptions, isNotExceeded};
await handleError(body);
throw new Error(error);
}
};
};
async function handleError(body, tag = 'renewToken') {
body = JSON.stringify(body);
await models.Application.rawSql('CALL util.debugAdd(?,?);', [tag, body]);
}

View File

@ -61,4 +61,21 @@ describe('Renew Token', () => {
expect(error).toBeUndefined();
expect(response.id).toEqual(ctx.req.accessToken.id);
});
it('throw error', async() => {
let error;
try {
await models.VnUser.renewToken({req: {token: null}});
} catch (e) {
error = e;
}
expect(error).toBeDefined();
const query = 'SELECT * FROM util.debug';
const debugLog = await models.Application.rawSql(query, null);
expect(debugLog.length).toEqual(1);
});
});