50 lines
1.5 KiB
JavaScript
50 lines
1.5 KiB
JavaScript
(() => {
|
|
const loginButton = document.querySelector('#auth-login-button');
|
|
const session = document.querySelector('#auth-session');
|
|
const avatar = document.querySelector('#auth-avatar');
|
|
const username = document.querySelector('#auth-username');
|
|
const token = localStorage.getItem('linklogAccessToken');
|
|
|
|
if (!loginButton || !session || !avatar || !username) return;
|
|
|
|
function showSignedOut() {
|
|
loginButton.classList.remove('hidden');
|
|
session.classList.add('hidden');
|
|
}
|
|
|
|
function showSignedIn(user) {
|
|
loginButton.classList.add('hidden');
|
|
session.classList.remove('hidden');
|
|
username.textContent = user.username || '';
|
|
const initial = (user.username || 'U').slice(0, 1).toUpperCase();
|
|
avatar.textContent = initial;
|
|
if (user.avatar_url) {
|
|
const image = document.createElement('img');
|
|
image.src = user.avatar_url;
|
|
image.alt = `${user.username || 'User'} avatar`;
|
|
image.addEventListener('error', () => {
|
|
image.remove();
|
|
avatar.textContent = initial;
|
|
});
|
|
avatar.textContent = '';
|
|
avatar.appendChild(image);
|
|
}
|
|
}
|
|
|
|
if (!token) {
|
|
showSignedOut();
|
|
return;
|
|
}
|
|
|
|
fetch(`/api/auth/me?token=${encodeURIComponent(token)}`)
|
|
.then((response) => {
|
|
if (!response.ok) throw new Error('Session expired');
|
|
return response.json();
|
|
})
|
|
.then(showSignedIn)
|
|
.catch(() => {
|
|
localStorage.removeItem('linklogAccessToken');
|
|
showSignedOut();
|
|
});
|
|
})();
|