diff --git a/backend/src/services/sinusbot.service.ts b/backend/src/services/sinusbot.service.ts index f2b9620..177b2e8 100644 --- a/backend/src/services/sinusbot.service.ts +++ b/backend/src/services/sinusbot.service.ts @@ -28,11 +28,7 @@ export class SinusBotService { if (this.bearer == null) { logger.info(`Hey! I'm trying to get my Bearer token!`); await this.login() - .then(token => this.bearer = token) - .catch(error => { - logger.error(`Oh oh! Something went wrong while fetching Bearer token.`, error); - throw this.createHttpException(HttpStatus.UNAUTHORIZED, `Fetching Bearer token for Sinusbot failed.`); - }); + .then(token => this.bearer = token); logger.debug( `Seems like I have my Bearer token! Looks like it's ${this.bearer == null ? 'undefined' : 'not undefined'}` @@ -46,7 +42,14 @@ export class SinusBotService { .then(data => this.consumeTunakillResponse(data)) .catch(error => { logger.error(`I couldn't fetch user data.`, error); - throw this.createHttpException(HttpStatus.INTERNAL_SERVER_ERROR, error.message); + + if (error instanceof RequestError && error.response && error.response.status === 401) { + logger.info(`Trying to refresh token...`); + this.bearer = undefined; + this.login().then(token => this.bearer = token); + } else { + throw this.createHttpException(HttpStatus.INTERNAL_SERVER_ERROR, error.message); + } }); } @@ -78,7 +81,11 @@ export class SinusBotService { return await fetch(this.loginURL, this.requestConfig(JSON.stringify(body))) .then(res => this.checkStatus(res)) .then(res => res.json()) - .then(data => data.token); + .then(data => data.token) + .catch(error => { + logger.error(`Oh oh! Something went wrong while fetching Bearer token.`, error); + throw this.createHttpException(HttpStatus.UNAUTHORIZED, `Fetching Bearer token for Sinusbot failed.`); + }); } private async fetchDefaultBotId(): Promise {