Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create firebase auth utils #4

Merged
merged 1 commit into from
Jan 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 52 additions & 3 deletions utils/firebaseAuthUtils.js
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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}`);
});
};
Loading