barta-india.in/public/js/js-0.1.0.js

70 lines
2.0 KiB
JavaScript

function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
const cookieValue = c.substring(name.length, c.length);
// console.log(`Cookie ${cname} found with value: ${cookieValue}`);
return cookieValue;
}
}
// console.log(`Cookie ${cname} not found`);
return "";
}
function makeProtectedRequest(apiUrl, renewUrl, access_token, formData) {
return fetch(apiUrl, {
method: 'POST',
// mode: "cors",
headers: {
// 'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
// credentials: 'same-origin',
body: JSON.stringify(formData),
})
.then(response => {
if (!response.ok) {
throw new Error('Request failed');
} else if(response.status === 204) {
// Token is expired or invalid, trigger refresh
// console.log(access_token)
return renewToken(renewUrl, access_token).then(access_token_new => {
// Retry the original request with the new token
// console.log("formData :" +access_token_new)
formData.access_token=access_token_new;
return fetch(apiUrl, {
method: 'POST',
headers: {
// 'Authorization': `Bearer ${newAccessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
});
}
return response.json();
});
}
function renewToken(renewUrl, access_token) {
return fetch(renewUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ tokenToRenew: access_token }),
})
.then(response => response.json())
.then(data => {
document.cookie = `access_token=${data.access_token}; path=/`;
// console.log('New Access Token:', data);
return data.access_token;
});
}