function parseJwt() {
const token = pm.environment.get("token");
if (!token) {
console.log('Token is empty or not defined.');
return null; // Devuelve null si el token no está presente o es vacío
}
try {
let base64Url = token.split('.')[1];
let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
let jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
} catch (error) {
console.error('Error parsing JWT:', error);
return null; // Devuelve null si hay un error al decodificar el token
}
}
function getTokenExpirationDate() {
const decoded = parseJwt();
// Verificar si decoded es null o undefined
if (!decoded || decoded.exp === undefined) {
console.log('Token is not present or could not be parsed.');
return null;
}
const date = new Date(0);
date.setUTCSeconds(decoded.exp);
return date;
}
function isTokenValid() {
const expirationDate = getTokenExpirationDate();
if (expirationDate === null) {
console.log('Token does not have an expiration date.');
return false;
}
const currentDate = new Date();
if (currentDate < expirationDate) {
console.log('Token is valid.');
return true;
} else {
console.log('Token has expired.');
return false;
}
}
function login() {
pm.sendRequest({
url: pm.environment.get("url") + "/api/login",
method: 'POST',
header: {
'Content-Type': 'application/json'
},
body: {
mode: 'raw',
raw: JSON.stringify({
email: pm.environment.get("username"),
password: pm.environment.get("password")
})
}
}, function (err, res) {
if (err) {
console.error(err);
} else {
const body = res.json();
const token = body.data?.token;
pm.environment.set("token", token);
console.log('New token acquired and set in environment.', token);
// Retry the original request after obtaining the new token
pm.request.headers.upsert({ key: 'Authorization', value: 'Bearer ' + token });
pm.sendRequest(pm.request, function (err, res) {
if (err) {
console.error('Retrying request failed:', err);
} else {
console.log('Original request retried successfully after refreshing token.');
}
});
}
});
}
// First, check if the token is valid
const valid = isTokenValid();
async function obtainSection() {
try {
const response = await new Promise((resolve, reject) => {
pm.sendRequest({
url: pm.environment.get("url") + "/api/sections",
method: 'GET',
header: {
'Authorization': 'Bearer ' + pm.environment.get("token")
}
}, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
const body = response.json();
const sections = body.data.sections;
if (sections.length === 0) {
throw new Error("No sections found.");
}
const section = sections[0];
pm.variables.set("idSection", section.id);
} catch (error) {
console.error(error);
}
}
// Function to get details of a section
async function detailSection() {
try {
const sectionId = pm.variables.get("idSection");
if (!sectionId) {