Seth
update
f21322e
/**
* Authentication service for Firebase and OTP authentication
*/
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "";
/**
* Get the current authenticated user
* @returns {Promise<Object>} User object
*/
export async function getCurrentUser() {
const token = localStorage.getItem("auth_token");
if (!token) {
throw new Error("No token found");
}
const response = await fetch(`${API_BASE_URL}/api/auth/me`, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
if (response.status === 401) {
localStorage.removeItem("auth_token");
}
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || "Failed to get user");
}
return await response.json();
}
/**
* Login with Firebase ID token
* @param {string} idToken - Firebase ID token
* @returns {Promise<Object>} Response with token and user
*/
export async function firebaseLogin(idToken) {
const response = await fetch(`${API_BASE_URL}/api/auth/firebase/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id_token: idToken }),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || "Firebase login failed");
}
return await response.json();
}
/**
* Request OTP for email login
* @param {string} email - Email address
* @returns {Promise<Object>} Response with success message
*/
export async function requestOTP(email) {
const response = await fetch(`${API_BASE_URL}/api/auth/otp/request`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email }),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || "Failed to send OTP");
}
return await response.json();
}
/**
* Verify OTP and login
* @param {string} email - Email address
* @param {string} otp - OTP code
* @returns {Promise<Object>} Response with token and user
*/
export async function verifyOTP(email, otp) {
const response = await fetch(`${API_BASE_URL}/api/auth/otp/verify`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, otp }),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || "OTP verification failed");
}
return await response.json();
}
/**
* Logout the current user
* @returns {Promise<void>}
*/
export async function logout() {
// For JWT tokens, logout is handled client-side by removing the token
// No server-side logout needed
return Promise.resolve();
}