feat: add login page and auth guard
This commit is contained in:
35
dashboard/src/lib/auth.ts
Normal file
35
dashboard/src/lib/auth.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user