Radish alpha
r
Radicle web interface
Radicle
Git (anonymous pull)
Log in to clone via SSH
Poll session every minute to make sure we are still connected
Rūdolfs Ošiņš committed 3 years ago
commit e0e51b234ac352b2c0b2b9bdc9713921f26dce8d
parent a0f0cc549a9c04d71c66471f45e368d1839d70f3
2 files changed +60 -7
modified src/lib/session.ts
@@ -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();
}
modified src/lib/utils.ts
@@ -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(),