diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 5581d19ac..ae554d398 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -16,36 +16,50 @@ module.exports = Self => { accessScopes: ['DEFAULT', 'read:multimedia']}); Self.renewToken = async function(ctx) { - const {accessToken: token} = ctx.req; + let accessToken; + let token; + try { + token = ctx.req.accessToken; + const {courtesyTime} = await models.AccessTokenConfig.findOne({ + fields: ['courtesyTime'] + }); + const isNotExceeded = await Self.validateToken(ctx); + if (isNotExceeded) + return token; - 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) { + // Schedule to remove current token + setTimeout(async() => { + try { + const exists = await models.AccessToken.findById(token.id); + exists && await Self.logout(token.id); + } catch (error) { // eslint-disable-next-line no-console - console.error(err); - } - }, courtesyTime * 1000); + console.error(error); + const body = JSON.stringify({err: error, token}); + await handleError(body); + throw new Error(error); + } + }, courtesyTime * 1000); - // Get scopes + // 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 createTokenOptions = {}; + const {scopes} = token; + if (scopes) + createTokenOptions = {scopes: [scopes[0]]}; + // Create new accessToken + const user = await Self.findById(token.userId); + accessToken = await user.accessTokens.create(createTokenOptions); - return {id: accessToken.id, ttl: accessToken.ttl}; + return {id: accessToken.id, ttl: accessToken.ttl}; + } catch (error) { + const body = JSON.stringify({error: error.message, token, accessToken}); + await handleError(body); + throw new Error(error); + } }; }; + +async function handleError(body, tag = 'renewToken') { + await models.Application.rawSql('CALL util.debugAdd(?,?);', [tag, body]); +}