From b26735003e4e4ebcf7f61c6b8fb905a059200e7b Mon Sep 17 00:00:00 2001 From: Kevin Wu Date: Tue, 5 Dec 2023 19:07:34 -0800 Subject: [PATCH] feat: create firebase auth utils --- utils/firebaseAuthUtils.js | 55 +++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/utils/firebaseAuthUtils.js b/utils/firebaseAuthUtils.js index 67d58d5..7bb4053 100644 --- a/utils/firebaseAuthUtils.js +++ b/utils/firebaseAuthUtils.js @@ -1,5 +1,5 @@ import { initializeApp } from 'firebase/app'; -import { getAuth } from 'firebase/auth'; +import { getAuth, signInWithEmailAndPassword, signOut } from 'firebase/auth'; const firebaseConfig = { apiKey: import.meta.env.VITE_FIREBASE_APIKEY, @@ -12,7 +12,56 @@ const firebaseConfig = { }; const app = initializeApp(firebaseConfig); -// eslint-disable-next-line no-unused-vars const auth = getAuth(app); -// Don't forget to export your functions! +/** + * + * @param {string} email Email for login + * @param {string} password Password for login + * @param {string} redirect Link to redirect to after successful login + * @param {hook} navigate useNavigate hook + */ +export const logInWithEmailAndPassWord = async (email, password, redirect, navigate) => { + signInWithEmailAndPassword(auth, email, password) + .then(() => { + navigate(redirect); + }) + .catch(error => { + console.log(`${error.code}: ${error.message}`); + }); +}; + +/** + * Returns details about the currently logged in user, or null if the user is not logged in. + * @see https://firebase.google.com/docs/auth/web/manage-users for more info + * @see https://firebase.google.com/docs/reference/js/auth.user for returned user type properties + * @returns {null|Object} The logged-in user's details (represented by Firebase object), or null if not logged in + */ +export const getLoginDetails = async () => { + // Get current user - https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth#currentuser + const user = auth.currentUser; + + if (user !== null) { + // User will be of type https://firebase.google.com/docs/reference/js/auth.user + return user; + } + + // No user is logged in + return null; +}; + +/** + * Logs out the current user, optionally taking a redirect path to redirect to upon successful logout + * @param {string} redirect Link to redirect to after successful logou + * @param {hook} navigate useNavigate hook + * @see https://firebase.google.com/docs/auth/web/password-auth + */ +export const logout = async (redirect, navigate) => { + signOut(auth) + .then(() => { + navigate(redirect); + }) + .catch(error => { + console.log(`${error.code}: ${error.message}`); + }); +};