|
| 1 | +// src/firebase/auth.js |
| 2 | + |
| 3 | +import { |
| 4 | + createUserWithEmailAndPassword, |
| 5 | + signInWithEmailAndPassword, |
| 6 | + signOut, |
| 7 | + onAuthStateChanged,} from 'firebase/auth' |
| 8 | +import { auth } from './firebase-init.js' |
| 9 | + |
| 10 | +/** |
| 11 | + * Creates a new user with email and password. |
| 12 | + * @param {string} email |
| 13 | + * @param {string} password |
| 14 | + * @returns {Promise<User>} The created user object. |
| 15 | + */ |
| 16 | +export async function signUp(email, password) { |
| 17 | + try { |
| 18 | + const userCredential = await createUserWithEmailAndPassword(auth, email, password) |
| 19 | + console.log('Successfully created user:', userCredential.user.uid) |
| 20 | + return userCredential.user |
| 21 | + } catch (error) { |
| 22 | + console.error('Error signing up:', error.message) |
| 23 | + throw error // Re-throw the error to be handled by the caller |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * Signs in an existing user. |
| 29 | + * @param {string} email |
| 30 | + * @param {string} password |
| 31 | + * @returns {Promise<User>} The signed-in user object. |
| 32 | + */ |
| 33 | +export async function signIn(email, password) { |
| 34 | + try { |
| 35 | + const userCredential = await signInWithEmailAndPassword(auth, email, password) |
| 36 | + console.log('Successfully signed in:', userCredential.user.uid) |
| 37 | + return userCredential.user |
| 38 | + } catch (error) { |
| 39 | + console.error('Error signing in:', error.message) |
| 40 | + throw error |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Signs out the current user. |
| 46 | + */ |
| 47 | +export function logOut() { |
| 48 | + return signOut(auth) |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Listens for changes in the user's authentication state. |
| 53 | + * @param {function} callback - A function to call with the user object (or null). |
| 54 | + * @returns {function} An unsubscribe function. |
| 55 | + */ |
| 56 | +export function onAuthStateChange(callback) { |
| 57 | + return onAuthStateChanged(auth, callback) |
| 58 | +} |
0 commit comments