Files
ophion/dashboard/src/lib/auth.ts

36 lines
820 B
TypeScript

export function getToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem('token');
}
export function setToken(token: string) {
localStorage.setItem('token', token);
}
export function removeToken() {
localStorage.removeItem('token');
}
export function isAuthenticated(): boolean {
return !!getToken();
}
export async function fetchWithAuth(url: string, options: RequestInit = {}) {
const token = getToken();
const headers = {
...options.headers,
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
const res = await fetch(url, { ...options, headers });
if (res.status === 401) {
removeToken();
window.location.href = '/login';
throw new Error('Unauthorized');
}
return res;
}