mirror of
https://github.com/Tria-plc/emaui.git
synced 2026-08-27 01:22:49 +00:00
43 lines
1.5 KiB
TypeScript
43 lines
1.5 KiB
TypeScript
let _prefix = 'ema-auth';
|
|
|
|
export function configureAuthStorage(prefix: string) {
|
|
_prefix = prefix;
|
|
}
|
|
|
|
function key(k: string) {
|
|
return `${_prefix}-${k}`;
|
|
}
|
|
|
|
export const authStorage = {
|
|
getToken: () => localStorage.getItem(key('auth-token')) ?? undefined,
|
|
setToken: (token: string) => localStorage.setItem(key('auth-token'), token),
|
|
getRefreshToken: () => localStorage.getItem(key('refresh-token')) ?? undefined,
|
|
setRefreshToken: (t: string) => localStorage.setItem(key('refresh-token'), t),
|
|
getUser: <T = unknown>(): T | null => {
|
|
try {
|
|
return JSON.parse(localStorage.getItem(key('auth-user')) ?? 'null') as T | null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
},
|
|
setUser: <T>(u: T) => localStorage.setItem(key('auth-user'), JSON.stringify(u)),
|
|
getProfileId: () => localStorage.getItem(key('profile-id')) ?? undefined,
|
|
setProfileId: (id: string) => localStorage.setItem(key('profile-id'), id),
|
|
getProfile: <T = unknown>(): T | null => {
|
|
try {
|
|
return JSON.parse(localStorage.getItem(key('current-profile')) ?? 'null') as T | null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
},
|
|
setProfile: <T>(p: T) => localStorage.setItem(key('current-profile'), JSON.stringify(p)),
|
|
removeProfile: () => localStorage.removeItem(key('current-profile')),
|
|
clear: () => {
|
|
[key('auth-token'), key('refresh-token'), key('auth-user'), key('profile-id'), key('current-profile')].forEach((k) =>
|
|
localStorage.removeItem(k),
|
|
);
|
|
document.cookie =
|
|
'auth-token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; SameSite=Lax';
|
|
},
|
|
};
|