Fix: validate session on every page load

This commit is contained in:
hyzen
2026-06-09 12:33:00 +05:30
parent 9fdcfdd885
commit 84f84f773a
67 changed files with 130 additions and 69 deletions

View File

@@ -110,11 +110,13 @@
</header>
<main class="main">{{ block "main" . }}{{ end }}</main>
<footer class="footer">{{ partial "footer.html" . }}</footer>
{{ partial "body/body-end.html" . }}
{{ partial "body/body-end.html" . }} {{ partial "body/body-end.html" . }}
<script>
(function () {
var path = window.location.pathname;
if (path === '/login/' || path === '/signup/') return;
// ── Save current page before navigating to login/signup ──
document
.querySelectorAll('a[href="/login/"], a[href="/signup/"]')
.forEach(function (a) {
@@ -122,6 +124,61 @@
sessionStorage.setItem('f4_login_next', path);
});
});
// ── Validate session on every page load ──
if (!localStorage.getItem('f4_username')) return;
// Skip check if we just logged in (5 second grace period)
var _loginTime = parseInt(localStorage.getItem('f4_login_time') || '0', 10);
if (Date.now() - _loginTime < 5000) return;
fetch('https://backend.freedoms4.org/auth.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ action: 'check_session' }),
})
.then(function (r) {
return r.json();
})
.then(function (data) {
if (!data.valid) {
if (data.db_error) {
// DB error — count consecutive failures, force logout after 3
var fails =
parseInt(localStorage.getItem('f4_session_fails') || '0', 10) +
1;
localStorage.setItem('f4_session_fails', fails);
if (fails >= 3) {
localStorage.removeItem('f4_username');
localStorage.removeItem('f4_login_time');
localStorage.removeItem('f4_session_fails');
window.location.reload();
}
} else {
// Session truly invalid — log out immediately
localStorage.removeItem('f4_username');
localStorage.removeItem('f4_login_time');
localStorage.removeItem('f4_session_fails');
window.location.reload();
}
} else {
// Valid session — reset failure counter
localStorage.removeItem('f4_session_fails');
}
})
.catch(function () {
// Network/404 error — count failures, force logout after 3
var fails =
parseInt(localStorage.getItem('f4_session_fails') || '0', 10) + 1;
localStorage.setItem('f4_session_fails', fails);
if (fails >= 3) {
localStorage.removeItem('f4_username');
localStorage.removeItem('f4_login_time');
localStorage.removeItem('f4_session_fails');
window.location.reload();
}
});
})();
</script>
</body>