All files / utils authValidation.js

78.57% Statements 22/28
79.16% Branches 19/24
50% Functions 1/2
81.48% Lines 22/27

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            2x     4x       4x 4x   4x     4x 4x 4x       3x       3x 3x 1x 1x   2x 1x     1x 1x 1x       1x               1x   1x   4x      
import { buildApiUrl } from "@/utils/fileUrl.js";
import {
  clearAuthSession,
  setUserProfile,
} from "@/utils/storage.js";
 
const AUTH_TIMEOUT_MS = 8000;
 
export async function resolveAuthorizedRole(token, tokenRole) {
  Iif (import.meta.env.VITE_DEMO_MODE === "true") {
    return Number(tokenRole);
  }
 
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), AUTH_TIMEOUT_MS);
  const fallbackRole =
    tokenRole === null || tokenRole === undefined || tokenRole === ""
      ? Number.NaN
      : Number(tokenRole);
  const retainedRole = Number.isInteger(fallbackRole) ? fallbackRole : null;
  try {
    const response = await fetch(buildApiUrl("/user/auth"), {
      headers: { Authorization: `Bearer ${token}` },
      signal: controller.signal,
    });
    Iif (response.status === 401 || response.status === 403) {
      clearAuthSession();
      return null;
    }
    const payload = await response.json();
    if (payload?.code === 401 || payload?.code === 403) {
      clearAuthSession();
      return null;
    }
    if (!response.ok || payload?.code !== 200 || !payload?.data) {
      return retainedRole;
    }
 
    const user = payload.data;
    const role = Number(user.userRole);
    Iif (!Number.isInteger(role)) {
      clearAuthSession();
      return null;
    }
    setUserProfile({
      id: user.id,
      name: user.userName,
      email: user.userEmail,
      url: user.userAvatar,
      role,
      isCoordinatorAdmin: Boolean(user.isCoordinatorAdmin),
    });
    return role;
  } catch {
    return retainedRole;
  } finally {
    clearTimeout(timeout);
  }
}