Moved authentification code into js/auth.js

This commit is contained in:
Josh-Dev-Quest committed 2026-03-28 13:43:05 +01:00
1 parent fec4f513c8
commit e3724a4842
8 files changed
+330 -364

No files matched your search

+2 -55
View File
@@ -220,62 +220,9 @@
</main>
<div id="toast" class="toast"></div>
<script src="js/auth.js"></script>
<script>
// ==================== AUTH ====================
const API_BASE = 'http://127.0.0.1:5000/api';
let currentUser = null;
async function checkAuthAndRedirect() {
try {
const res = await fetch(`${API_BASE}/me`, { credentials: 'include' });
if (res.ok) {
currentUser = await res.json();
return true;
} else {
window.location.href = 'login.html';
return false;
}
} catch (err) {
window.location.href = 'login.html';
return false;
}
}
function updateUserMenu() {
const container = document.getElementById('user-menu');
if (currentUser) {
container.innerHTML = `
<span class="username"><i class="fas fa-user"></i> ${escapeHtml(currentUser.username)}</span>
<button id="logout-btn" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</button>
`;
document.getElementById('logout-btn')?.addEventListener('click', logout);
}
}
async function logout() {
await fetch(`${API_BASE}/logout`, { method: 'POST', credentials: 'include' });
window.location.href = 'login.html';
}
function escapeHtml(str) {
if (!str) return '';
return str.replace(/[&<>]/g, function(m) {
if (m === '&') return '&amp;';
if (m === '<') return '&lt;';
if (m === '>') return '&gt;';
return m;
});
}
function showToast(msg, isError = false) {
const toast = document.getElementById('toast');
toast.textContent = msg;
toast.style.backgroundColor = isError ? 'var(--red-7)' : 'var(--green-7)';
toast.style.display = 'block';
setTimeout(() => { toast.style.display = 'none'; }, 3000);
}
// ==================== BLOG POSTS ====================
async function loadPosts() {
try {