Files
goldenChart/packages/shared/src/auth.ts
T
2026-05-28 14:44:19 +09:00

50 lines
1.5 KiB
TypeScript

import { storageGetSync, storageRemove, storageSetSync } from './storage/index.js';
export type UserRole = 'ADMIN' | 'USER';
export interface AuthSession {
userId: number;
username: string;
displayName: string;
role: UserRole;
}
const USER_ID_KEY = 'gc_user_id';
const USERNAME_KEY = 'gc_username';
const DISPLAY_NAME_KEY = 'gc_display_name';
const ROLE_KEY = 'gc_user_role';
function normalizeRole(role: string): UserRole {
return role === 'ADMIN' ? 'ADMIN' : 'USER';
}
export function getAuthSession(): AuthSession | null {
const id = storageGetSync(USER_ID_KEY);
if (!id) return null;
const userId = Number(id);
if (!Number.isFinite(userId) || userId <= 0) return null;
const username = storageGetSync(USERNAME_KEY) ?? '';
const displayName = storageGetSync(DISPLAY_NAME_KEY) ?? username;
const storedRole = storageGetSync(ROLE_KEY);
const role = normalizeRole(storedRole ?? 'USER');
return { userId, username, displayName, role };
}
export function setAuthSession(session: AuthSession): void {
storageSetSync(USER_ID_KEY, String(session.userId));
storageSetSync(USERNAME_KEY, session.username);
storageSetSync(DISPLAY_NAME_KEY, session.displayName);
storageSetSync(ROLE_KEY, session.role);
}
export async function clearAuthSession(): Promise<void> {
await storageRemove(USER_ID_KEY);
await storageRemove(USERNAME_KEY);
await storageRemove(DISPLAY_NAME_KEY);
await storageRemove(ROLE_KEY);
}
export function isLoggedIn(): boolean {
return getAuthSession() !== null;
}