Spaces:
Running
Running
File size: 1,995 Bytes
c569d1a |
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 |
export const AUTH_STORAGE_KEY = 'authUser';
const FAKE_ACCOUNTS = [
{ username: 'admin', password: 'admin123', displayName: 'Admin' },
{
username: 'editor',
password: 'editor123',
displayName: 'Editor',
},
{
username: 'viewer',
password: 'viewer123',
displayName: 'Viewer',
},
];
function normalizeIdentifier(identifier = '') {
return String(identifier || '')
.trim()
.toLowerCase();
}
export function getFakeAccounts() {
return [...FAKE_ACCOUNTS];
}
export function findAccount(username, password) {
const normalizedUser = normalizeIdentifier(username);
return FAKE_ACCOUNTS.find(
(account) =>
normalizeIdentifier(account.username) === normalizedUser &&
account.password === String(password || '')
);
}
export function getAuthUser() {
try {
const raw = localStorage.getItem(AUTH_STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
if (!parsed?.username) return null;
return parsed;
} catch (error) {
console.error('Failed to read auth user', error);
return null;
}
}
export function saveAuthUser(account) {
if (!account) return null;
const payload = {
username: account.username,
displayName: account.displayName || account.username,
loggedInAt: Date.now(),
};
localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(payload));
return payload;
}
export function clearAuthUser() {
localStorage.removeItem(AUTH_STORAGE_KEY);
}
export function ensureAuthenticated(redirectOnMissing = true) {
const user = getAuthUser();
if (!user && redirectOnMissing && typeof window !== 'undefined') {
window.location.href = 'login.html';
}
return user;
}
export function startAuthWatcher(intervalMs = 5000) {
if (typeof window === 'undefined') return () => {};
const timerId = window.setInterval(() => {
if (!getAuthUser()) {
window.location.href = 'login.html';
}
}, intervalMs);
return () => window.clearInterval(timerId);
}
|