Skip to content

Commit

Permalink
Merge pull request #32 from luisaugusto/main
Browse files Browse the repository at this point in the history
Set Up Firebase Auth
  • Loading branch information
thetrend authored Nov 12, 2023
2 parents 274287e + 97583db commit 43e28e2
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
.env.test.local
.env.production.local
.eslintcache
/.idea

npm-debug.log*
yarn-debug.log*
Expand Down
2 changes: 2 additions & 0 deletions src/api/config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { getAuth } from 'firebase/auth';

// Your web app's Firebase configuration
const firebaseConfig = {
Expand All @@ -15,3 +16,4 @@ const firebaseConfig = {
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth(app);
28 changes: 28 additions & 0 deletions src/api/useAuth.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useEffect, useState } from 'react';
import { auth } from './config.js';
import { GoogleAuthProvider, signInWithRedirect } from 'firebase/auth';

export const SignInButton = () => (
<button
type="button"
onClick={() => signInWithRedirect(auth, new GoogleAuthProvider())}
>
Sign In
</button>
);

export const SignOutButton = () => (
<button type="button" onClick={() => auth.signOut()}>
Sign Out
</button>
);

export const useAuth = () => {
const [user, setUser] = useState(null);

useEffect(() => {
auth.onAuthStateChanged((user) => setUser(user));
}, []);

return { user };
};
11 changes: 11 additions & 0 deletions src/views/Layout.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Outlet } from 'react-router-dom';

import './Layout.css';
import { auth } from '../api/config.js';
import { useAuth, SignInButton, SignOutButton } from '../api/useAuth.jsx';

/**
* TODO: The links defined in this file don't work!
Expand All @@ -11,11 +13,20 @@ import './Layout.css';
*/

export function Layout() {
const { user } = useAuth();
return (
<>
<div className="Layout">
<header className="Layout-header">
<h1>Smart shopping list</h1>
{!!user ? (
<div>
<span>Signed in as {auth.currentUser.displayName}</span> (
<SignOutButton />)
</div>
) : (
<SignInButton />
)}
</header>
<main className="Layout-main">
<Outlet />
Expand Down

0 comments on commit 43e28e2

Please sign in to comment.