All files / utils storage.js
90%
Statements
36/40
75%
Branches
21/28
100%
Functions
13/13
91.42%
Lines
32/35
Press n or j to go to the next uncovered block, b, p or k for the previous block.
Filter:
| 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | 4x 26x 26x 131x 131x 72x 59x 7x 7x 5x 5x 1x 1x 19x 34x 7x 1x 1x 1x 1x 1x 1x 1x 26x 8x 3x 1x 1x 70x 4x 2x 2x | 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 isCurrentToken(expectedToken) {
return getToken() === expectedToken;
}
export function setUserProfileIfToken(expectedToken, profile) {
if (!isCurrentToken(expectedToken)) return false;
setUserProfile(profile);
return true;
}
export function clearAuthSession() {
Object.values(SESSION_KEYS).forEach((key) => write(key, null));
}
export function clearAuthSessionIfToken(expectedToken) {
if (!isCurrentToken(expectedToken)) return false;
clearAuthSession();
return true;
}
|