session check

This commit is contained in:
Mateusz Gruszczyński
2026-07-26 09:36:23 +02:00
parent e3abc3e7be
commit 5f93d3642b
4 changed files with 58 additions and 4 deletions
+24
View File
@@ -6,6 +6,29 @@ function formatBytes(bytes) {
return `${bytes} B`;
}
function clearExpiredSession() {
localStorage.removeItem("rustpad:auth-token");
sessionStorage.removeItem("rustpad:auth-token");
localStorage.removeItem("rustpad:nickname");
sessionStorage.removeItem("rustpad:nickname");
document.cookie = "rustpad_nickname=; Path=/; SameSite=Lax; Max-Age=0";
window.dispatchEvent(new CustomEvent("rustpad:session-expired"));
}
async function clearSessionIfInvalid() {
const token = localStorage.getItem("rustpad:auth-token") || sessionStorage.getItem("rustpad:auth-token");
if (!token) return;
try {
const response = await fetch("/api/auth/me", {
headers: { Authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(5000),
});
if (response.status === 401) clearExpiredSession();
} catch {
// A network failure does not prove that the session is invalid.
}
}
function validateUploadSize(body) {
if (!(body instanceof FormData)) return;
const maxBytes = Number(window.__RUSTPAD_CONFIG__?.uploadMaxSizeBytes || 0);
@@ -34,6 +57,7 @@ export async function api(path, options = {}) {
const contentType = response.headers.get("content-type") || "";
const data = contentType.includes("application/json") ? await response.json().catch(() => ({})) : {};
if (!response.ok) {
if (response.status === 401) await clearSessionIfInvalid();
const defaults = { 400: "Invalid request.", 401: "Authentication required.", 403: "Access denied.", 404: "The requested resource was not found.", 405: "This operation is not allowed.", 409: "The requested change conflicts with existing data.", 413: "The selected file exceeds the allowed upload limit.", 429: "Too many requests. Try again later.", 500: "Server error. Try again later.", 503: "Service temporarily unavailable." };
const requestError = new Error(data.error || defaults[response.status] || `Request failed (${response.status}).`);
requestError.status = response.status;
+1
View File
@@ -259,6 +259,7 @@ if (identityDialog) {
renderAccount(null);
});
window.addEventListener("rustpad:session-expired", () => renderAccount(null));
renderAccount(null);
validateCurrentSession().then(renderAccount);
}