All files / utils storage.js

87.09% Statements 27/31
70.83% Branches 17/24
100% Functions 10/10
89.28% Lines 25/28

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 79 80    4x                 12x 12x             103x 103x 57x   46x               5x 5x 3x 3x   1x 1x         7x       26x       5x       1x 1x       1x 1x 1x 1x 1x             21x             55x    
import jwtDecode from "jwt-decode";
 
const SESSION_KEYS = Object.freeze({
  token: "token",
  userProfile: "userInfo",
  authIntroSeen: "auth-intro-seen",
  noticeOperation: "noticeOperation",
  noticeDraft: "noticeInfo",
});
 
function read(key) {
  try {
    return sessionStorage.getItem(key);
  } catch {
    return null;
  }
}
 
function write(key, value) {
  try {
    if (value === null || value === undefined || value === "") {
      sessionStorage.removeItem(key);
    } else {
      sessionStorage.setItem(key, value);
    }
  } catch {
    // Storage may be disabled; the current view can continue in memory.
  }
}
 
function readJson(key) {
  const raw = read(key);
  if (!raw) return null;
  try {
    return JSON.parse(raw);
  } catch {
    write(key, null);
    return null;
  }
}
 
export function getToken() {
  return read(SESSION_KEYS.token);
}
 
export function setToken(token) {
  write(SESSION_KEYS.token, typeof token === "string" ? token.trim() : null);
}
 
export function getUserProfile() {
  return readJson(SESSION_KEYS.userProfile);
}
 
export function getSessionUserRole() {
  const profile = getUserProfile();
  Iif (profile && profile.role !== null && profile.role !== undefined) {
    return Number(profile.role);
  }
 
  const token = getToken();
  Iif (!token) return null;
  try {
    const role = jwtDecode(token)?.role;
    return role === null || role === undefined ? null : Number(role);
  } catch {
    return null;
  }
}
 
export function setUserProfile(profile) {
  write(
    SESSION_KEYS.userProfile,
    profile && typeof profile === "object" ? JSON.stringify(profile) : null
  );
}
 
export function clearAuthSession() {
  Object.values(SESSION_KEYS).forEach((key) => write(key, null));
}