File size: 2,815 Bytes
1d68698 852bda9 1d68698 852bda9 1d68698 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | /**
* 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();
}
|