fe / auth.js
Lucii1's picture
add login page
c569d1a
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);
}