Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 47 additions & 17 deletions layouts/partials/navbar.html
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@

const cloudAppUrl = "{{ $cloudAppUrl }}";
let isUserAuthenticated = false;
let isCheckingAuth = false;
let expiredToken = "";

function removeCookie(cookieName) {
Expand All @@ -293,25 +294,51 @@
return null;
}

const checkUserAuth = async () => {
function getAccessToken() {
const tokenCookie = getCookieValue("provider_token");
if (!tokenCookie) {
return null;
}

try {
const token = getCookieValue("provider_token");
if (!token || token === expiredToken) { // cookie doesn't exist or has expired (due to user logout)
if (isUserAuthenticated) {
showSignInButton();
isUserAuthenticated = false;
}
throw new Error("missing or expired cookie");
const parsedToken = JSON.parse(atob(tokenCookie));
return parsedToken?.access_token || tokenCookie;
} catch (error) {
return tokenCookie;
}
const re = await fetch(`${cloudAppUrl}/api/identity/users/profile`, {
}

const checkUserAuth = async () => {
if (isCheckingAuth) {
return;
}

isCheckingAuth = true;
try {
const accessToken = getAccessToken();

const requestOptions = {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
},
});
credentials: 'include',
};

if (accessToken && accessToken !== expiredToken) {
requestOptions.headers = {
'Authorization': `Bearer ${accessToken}`,
};
}

let re = await fetch(`${cloudAppUrl}/api/identity/users/profile`, requestOptions);

if (re.status === 401 && accessToken && accessToken !== expiredToken) {
expiredToken = accessToken;
re = await fetch(`${cloudAppUrl}/api/identity/users/profile`, {
method: 'GET',
credentials: 'include',
});
}

if (re.status === 401) { // cookie has expired
expiredToken = token;
if (re.status === 401) {
throw new Error("unauthorized");
}
if (re.status !== 200) {
Expand All @@ -322,8 +349,9 @@
updateUI(response);

} catch (error) {
// console.error("could not set user details.", error);
showSignInButton();
} finally {
isCheckingAuth = false;
}
};
function getAvatarUrl(response) {
Expand All @@ -333,7 +361,7 @@
}

function getUserProfileUrl(response) {
const userId = response?.id;
const userId = response?.userId || response?.id;
if (userId) {
return `${cloudAppUrl}/user/${encodeURIComponent(userId)}`;
}
Expand Down Expand Up @@ -372,5 +400,7 @@
checkUserAuth();

document.addEventListener('visibilitychange', handleVisibilityChange);
window.addEventListener('focus', handleVisibilityChange);
window.addEventListener('pageshow', handleVisibilityChange);
Comment thread
Sbragul26 marked this conversation as resolved.
</script>
</header>
Loading