session check
This commit is contained in:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user