LCOV - code coverage report
Current view: top level - utils/spotifyAuthGuard.js - spotifyAuthGuard.js (source / functions) Hit Total Coverage
Test: feature-lcov.info Lines: 44 44 100.0 %
Date: 2025-11-22 00:01:46 Functions: 2 2 100.0 %

          Line data    Source code
       1           1 : // Minimal helper that asks backend if Spotify is connected.
       2           1 : // If /auth/session returns 401, attempt one refresh (/auth/refresh) then retry once.
       3           1 : export async function ensureSpotifyConnected(baseUrl = "") {
       4           8 :   const root = String(baseUrl).replace(/\/$/, ""); // strip trailing slash
       5           8 : 
       6           8 :   async function sessionProbe() {
       7          11 :     const r = await fetch(`${root}/auth/session`, { credentials: "include" });
       8          11 :     if (!r.ok) return { ok: false, status: r.status };
       9           5 :     const { connected } = await r.json().catch(() => ({ connected: false }));
      10           5 :     return { ok: true, connected };
      11          11 :   }
      12           8 : 
      13           8 :   try {
      14           8 :     let s = await sessionProbe();
      15           8 :     if (s.ok && s.connected) return { shouldRedirect: false };
      16           6 : 
      17           6 :     // If not ok and specifically 401, try one refresh then retry session once.
      18           8 :     if (!s.ok && s.status === 401) {
      19           5 :       try {
      20           5 :         const rr = await fetch(`${root}/auth/refresh`, { method: "POST", credentials: "include" });
      21           4 :         if (rr.ok) {
      22           3 :           s = await sessionProbe();
      23           3 :           if (s.ok && s.connected) return { shouldRedirect: false };
      24           3 :         }
      25           5 :       } catch {/* fall through */}
      26           5 :     }
      27           4 : 
      28           4 :     // Either not connected or failed refresh → go to connect flow
      29           4 :     return { shouldRedirect: true, to: `${root}/auth/start` };
      30           8 :   } catch {
      31           1 :     // Network or other error: safest is to try to reconnect
      32           1 :     return { shouldRedirect: true, to: `${root}/auth/start` };
      33           1 :   }
      34           8 : }
      35           1 : 
      36           1 : // ESM exports (for UI tests / Vite)
      37           1 : export default ensureSpotifyConnected;
      38           1 : export { ensureSpotifyConnected };
      39           1 : 
      40           1 : // CJS exports (for unit tests using require)
      41           1 : try {
      42           1 :   module.exports = ensureSpotifyConnected;
      43           1 :   module.exports.ensureSpotifyConnected = ensureSpotifyConnected;
      44           1 : } catch {}

Generated by: LCOV version 1.15.alpha0w