All files / src/auth session.ts

87.5% Statements 56/64
81.48% Branches 22/27
100% Functions 6/6
87.5% Lines 56/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78              1x   1x 26x 11x 11x 15x 15x 26x 1x 1x 13x 13x 26x 26x 26x 1x 1x 26x   45x 45x 9x 9x 36x 45x 45x     45x   1x 20x 20x     20x 20x 20x 1x 1x 20x   1x 15x 15x     15x 15x 15x 1x 1x 15x   1x 10x 10x     10x 10x 10x 1x 1x 10x   1x 24x 24x  
export type Role = "operator" | "viewer";
 
export interface Session {
  role: Role;
  apiKey: string;
}
 
export const SESSION_KEY = "dispatch.session";
 
export function parseSession(raw: string | null): Session | null {
  if (!raw) {
    return null;
  }
  try {
    const value = JSON.parse(raw) as { role?: unknown; apiKey?: unknown };
    if (value.role !== "operator" && value.role !== "viewer") {
      return null;
    }
    return {
      role: value.role,
      apiKey: typeof value.apiKey === "string" ? value.apiKey : "",
    };
  } catch {
    return null;
  }
}
 
function resolveStorage(storage?: Storage): Storage | null {
  if (storage) {
    return storage;
  }
  try {
    return globalThis.sessionStorage ?? null;
  } catch {
    return null;
  }
}
 
export function loadSession(storage?: Storage): Session | null {
  const target = resolveStorage(storage);
  if (!target) {
    return null;
  }
  try {
    return parseSession(target.getItem(SESSION_KEY));
  } catch {
    return null;
  }
}
 
export function saveSession(session: Session, storage?: Storage): void {
  const target = resolveStorage(storage);
  if (!target) {
    return;
  }
  try {
    target.setItem(SESSION_KEY, JSON.stringify(session));
  } catch {
    return;
  }
}
 
export function clearSession(storage?: Storage): void {
  const target = resolveStorage(storage);
  if (!target) {
    return;
  }
  try {
    target.removeItem(SESSION_KEY);
  } catch {
    return;
  }
}
 
export function roleLabel(role: Role): string {
  return role === "operator" ? "Оператор" : "Наблюдатель";
}