const axios = require("axios"); const shared = require("./shared.js"); let userID; async function TokenRenew() { setInterval(async () => { shared.eventEmitter.emit("tokenRenewalStart"); try { // ottieni l'ID dell'utente associato al token userID = await getUserID(); // ottieni l'ID del token corrente const tokenID = await getCurrentTokenID(); // crea nuovo token const newToken = await getNewToken(); shared.setToken(newToken); // cancella il token precedente await deleteToken(tokenID); shared.eventEmitter.emit("tokenRenewalEnd"); } catch (error) { console.error("Errore nel rinnovo del token:", error); } }, day - hour); } async function getUserID() { const response = await axios.get("https://api.netbird.io/api/users/current", { headers: { Accept: "application/json", Authorization: `Token ${shared.getToken()}`, }, }); console.log(`UserID: ${response.data.id}`); return response.data.id; } async function deleteToken(tokenID) { await axios.delete( `https://api.netbird.io/api/users/${userID}/tokens/${tokenID}`, { headers: { Authorization: `Token ${shared.getToken()}`, }, } ); console.log(`Token con ID ${tokenID} cancellato con successo`); } async function getCurrentTokenID() { const response = await axios.get( `https://api.netbird.io/api/users/${userID}/tokens`, { headers: { Accept: "application/json", Authorization: `Token ${shared.getToken()}`, }, } ); const token = response.data.find((t) => t.name === "Uptime Kuma"); if (!token) throw new Error("Token 'Uptime Kuma' non trovato"); console.log(`CurrentTokenID: ${token.id}`); return token.id; } async function getNewToken() { const response = await axios.post( `https://api.netbird.io/api/users/${userID}/tokens`, { name: "Uptime Kuma", expires_in: 2, }, { headers: { Accept: "application/json", Authorization: `Token ${shared.getToken()}`, "Content-Type": "application/json", }, } ); console.log(`Nuovo token creato: ${response.data.plain_token}`); return response.data.plain_token; } module.exports = { TokenRenew, };