|
| 1 | +import { getEnv } from '@/utils/env'; |
| 2 | + |
| 3 | +export interface User { |
| 4 | + id: string; |
| 5 | + email: string; |
| 6 | + // Add other user properties as needed |
| 7 | +} |
| 8 | + |
| 9 | +export class UserService { |
| 10 | + private static getApiUrl(): string { |
| 11 | + const apiUrl = getEnv('VITE_DEPLOYSTACK_BACKEND_URL'); |
| 12 | + if (!apiUrl) { |
| 13 | + throw new Error('API URL not configured. Make sure VITE_DEPLOYSTACK_BACKEND_URL is set.'); |
| 14 | + } |
| 15 | + return apiUrl; |
| 16 | + } |
| 17 | + |
| 18 | + static async getCurrentUser(): Promise<User | null> { |
| 19 | + try { |
| 20 | + const apiUrl = this.getApiUrl(); |
| 21 | + const response = await fetch(`${apiUrl}/api/users/me`, { |
| 22 | + method: 'GET', |
| 23 | + headers: { |
| 24 | + 'Content-Type': 'application/json', |
| 25 | + }, |
| 26 | + credentials: 'include', // Important for sending session cookies |
| 27 | + }); |
| 28 | + |
| 29 | + if (response.ok) { |
| 30 | + const data = await response.json(); |
| 31 | + if (data.success && data.data) { |
| 32 | + return data.data as User; |
| 33 | + } |
| 34 | + // If success is false or data is missing, treat as not logged in for this check |
| 35 | + return null; |
| 36 | + } |
| 37 | + |
| 38 | + if (response.status === 401) { |
| 39 | + // Unauthorized, user is not logged in |
| 40 | + return null; |
| 41 | + } |
| 42 | + |
| 43 | + // For other errors, we might not want to block navigation, |
| 44 | + // but for the purpose of this check, any error means we can't confirm the user. |
| 45 | + console.error('Failed to fetch current user:', response.status); |
| 46 | + return null; |
| 47 | + } catch (error) { |
| 48 | + console.error('Error in getCurrentUser:', error); |
| 49 | + return null; // Network error or other issues |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments