Poll session every minute to make sure we are still connected

Signed-off-by: Rūdolfs Ošiņš <rudolfs@osins.org>
This commit is contained in:
Rūdolfs Ošiņš
2023-02-14 14:11:53 +01:00
parent a0f0cc549a
commit e0e51b234a
2 changed files with 60 additions and 7 deletions
+60 -2
View File
@@ -4,6 +4,15 @@ interface Session {
id: string;
publicKey: string;
}
interface SessionResponse {
sessionId: string;
status: string;
publicKey: string;
issuedAt: number;
expiresAt: number;
}
const store = writable<Session | undefined>(undefined);
export const sessionStore = derived(store, s => s);
@@ -29,6 +38,38 @@ export async function authenticate(params: {
}
}
let pollSessionHandle: number | undefined = undefined;
function pollSession() {
if (pollSessionHandle) {
return;
}
pollSessionHandle = window.setInterval(async () => {
const session = get(sessionStore);
if (!session) {
return;
}
try {
const resp = await fetch(`${endpoint}/${session.id}`, {
method: "GET",
});
const sess: SessionResponse = await resp.json();
const unixTimeInSeconds = Math.floor(Date.now() / 1000);
if (
sess.status === "unauthorized" ||
sess.expiresAt < unixTimeInSeconds
) {
clear();
}
} catch {
clear();
}
}, 60_000);
}
export async function disconnect() {
const session = get(store);
if (!session) {
@@ -43,8 +84,7 @@ export async function disconnect() {
},
});
window.localStorage.removeItem("session");
store.set(undefined);
clear();
}
function save(id: string, publicKey: string) {
@@ -52,6 +92,11 @@ function save(id: string, publicKey: string) {
store.set({ id, publicKey });
}
function clear() {
window.localStorage.removeItem("session");
store.set(undefined);
}
export function initialize() {
// Sync session state changes with other open tabs and windows.
addEventListener("storage", event => {
@@ -76,4 +121,17 @@ export function initialize() {
store.set({ id: parsed.id, publicKey: parsed.publicKey });
}
}
// Properly clean up setInterval and restart session polling when Vite
// performs hot module reload on file changes.
if (import.meta.hot) {
import.meta.hot.accept();
import.meta.hot.dispose(() => {
clearInterval(pollSessionHandle);
pollSessionHandle = undefined;
pollSession();
});
}
pollSession();
}
-5
View File
@@ -115,11 +115,6 @@ export function parseUsername(input: string): string {
return parts[parts.length - 1];
}
// Return the current unix time.
export function unixTime(): number {
return Math.floor(Date.now() / 1000);
}
export const formatTimestamp = (
timestamp: number,
current = new Date().getTime(),