51 lines
1.6 KiB
TypeScript
51 lines
1.6 KiB
TypeScript
import { JWTToken } from "sim-shared/domain/JWT.js";
|
|
import { JWTProvider } from "sim-shared/infrastructure/HTTPClient.js";
|
|
import { LegacyJWTTokenRepository } from "#infrastructure/LegacyJWTTokensRepository.js";
|
|
import { env } from "#config/env/env.js";
|
|
|
|
const tokenDir = String(env.ALAI_CERTIFICATES_DIR)
|
|
const tokenFile = ".debugToken"
|
|
|
|
/**
|
|
* Usa un token guardado a mano en archivo para no gastar tokens de Alai
|
|
*/
|
|
export class DebugTokenManager implements JWTProvider<{}> {
|
|
|
|
isRefreshing: boolean = false;
|
|
authToken: JWTToken<{}> | undefined;
|
|
|
|
private async getNewAuthToken() {
|
|
// TODO: Si no funcionase hay que reprogramar los mensajes para ser
|
|
// consumidos mas tarde.
|
|
const res = LegacyJWTTokenRepository.getTokenFromFile(tokenDir, tokenFile)
|
|
|
|
|
|
if (res.error != undefined) {
|
|
console.error("Error obteniendo el token de ALAI", res.error)
|
|
} else {
|
|
this.authToken = new JWTToken(res.data)
|
|
console.log("[d] Token DEBUG: ", this.authToken)
|
|
}
|
|
}
|
|
|
|
public tryRefreshToken(): Promise<JWTToken<{}>> {
|
|
// En Alai no existe el concepto de refresh, se solicita otro token nuevo
|
|
return this.getAccessToken()
|
|
};
|
|
|
|
public async getAccessToken(): Promise<JWTToken<{}>> {
|
|
// Caso 1: El token actual es valido
|
|
if (this.authToken != undefined && !this.authToken.isExpired()) {
|
|
return this.authToken
|
|
} else {
|
|
// Caso 2: El token actual no existe o ha expirado
|
|
await this.getNewAuthToken()
|
|
}
|
|
|
|
// Si después de todo no se ha generado el token es un error catastrofico
|
|
if (this.authToken == undefined) throw new Error("Error obteniendo tokens de auth")
|
|
|
|
return this.authToken
|
|
};
|
|
}
|