Files
periodic-table/frontend/src/services/authService.ts
2025-11-28 12:33:37 -03:00

68 lines
1.6 KiB
TypeScript

import type { User } from '@/types'
const API_BASE_URL = '/api'
class AuthService {
/**
* Get the current authenticated user from the session cookie.
* Returns null if not authenticated.
*/
async getCurrentUser(): Promise<User | null> {
try {
const response = await fetch(`${API_BASE_URL}/auth/me`, {
method: 'GET',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
})
if (!response.ok) {
if (response.status === 401) {
return null
}
throw new Error(`HTTP error! status: ${response.status}`)
}
const user: User = await response.json()
return user
} catch (error) {
console.error('Failed to get current user:', error)
return null
}
}
/**
* Logout the current user by clearing the session cookie.
*/
async logout(): Promise<void> {
try {
const response = await fetch(`${API_BASE_URL}/auth/logout`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
} catch (error) {
console.error('Logout failed:', error)
throw error
}
}
/**
* Redirect to the login endpoint to initiate OAuth flow.
*/
login(): void {
// In development with Vite proxy, we can use relative URL
// In production, this will be proxied by nginx
window.location.href = `${API_BASE_URL}/login`
}
}
export const authService = new AuthService()