fix: use bearer tokens instead of cookies for cross-origin auth

This commit is contained in:
2026-01-28 21:33:53 +00:00
parent b23e5ef801
commit ab402da7fd
2 changed files with 32 additions and 1 deletions

View File

@@ -8,10 +8,30 @@ const AUTH_BASE = import.meta.env.PROD
? 'https://api.thenetwork.donovankelly.xyz'
: '';
const TOKEN_KEY = 'network-auth-token';
class ApiClient {
private getToken(): string | null {
return localStorage.getItem(TOKEN_KEY);
}
setToken(token: string | null) {
if (token) {
localStorage.setItem(TOKEN_KEY, token);
} else {
localStorage.removeItem(TOKEN_KEY);
}
}
private authHeaders(): HeadersInit {
const token = this.getToken();
return token ? { Authorization: `Bearer ${token}` } : {};
}
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const headers: HeadersInit = {
'Content-Type': 'application/json',
...this.authHeaders(),
...options.headers,
};
@@ -43,23 +63,33 @@ class ApiClient {
const error = await response.json().catch(() => ({ message: 'Login failed' }));
throw new Error(error.message || 'Login failed');
}
// Capture bearer token from response header
const authToken = response.headers.get('set-auth-token');
if (authToken) {
this.setToken(authToken);
}
return response.json();
}
async logout() {
await fetch(`${AUTH_BASE}/api/auth/sign-out`, {
method: 'POST',
headers: this.authHeaders(),
credentials: 'include',
});
this.setToken(null);
}
async getSession(): Promise<{ user: User } | null> {
try {
const response = await fetch(`${AUTH_BASE}/api/auth/get-session`, {
headers: this.authHeaders(),
credentials: 'include',
});
if (!response.ok) return null;
return response.json();
const data = await response.json();
if (!data || !data.user) return null;
return data;
} catch {
return null;
}