import {HttpService, Injectable, Logger} from '@nestjs/common'; import {Cron, CronExpression} from '@nestjs/schedule'; import {AuthService} from '../auth/auth.service'; import {ConfigService} from '@nestjs/config'; import {SocketService} from '../socket/socket.service'; @Injectable() export class AuthCron { private logger: Logger = new Logger('AuthCron'); constructor( private readonly http: HttpService, private readonly authService: AuthService, private readonly socketService: SocketService, private readonly config: ConfigService ) { } @Cron(CronExpression.EVERY_MINUTE) async handleCron() { const tokenLife = await this.authService.tokenLife(); this.logger.debug(`Check token life ${String(tokenLife)}%`); if (tokenLife < 50) { const isActive = await this.authService.isActive(); this.logger.debug(`Is Active Token ${isActive}`); if (isActive) { await this.authService.refresh().then(() => { this.http.axiosRef.defaults = { baseURL: this.config.get('CLOUD_ENDPOINT'), headers: { Authorization: `Bearer ${this.authService.accessToken}` } }; }); } else { await this.authService.login().then(() => { this.http.axiosRef.defaults = { baseURL: this.config.get('CLOUD_ENDPOINT'), headers: { Authorization: `Bearer ${this.authService.accessToken}` } }; }); } } } }