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: add firebase authentication #49

Merged
merged 3 commits into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
90 changes: 45 additions & 45 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 14 additions & 15 deletions web/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
import { initializeApp } from 'firebase/app'
import { Database, getDatabase } from 'firebase/database'

import { RecoilRoot } from 'recoil'

import { ChatWrapper as Chat, Header } from '@/components'

import './App.css'
import { firebaseConfig } from './firebase'

import { Toaster } from 'react-hot-toast'

initializeApp(firebaseConfig)
import { AuthWrapper } from './components/Auth/AuthWrapper'

const db: Database = getDatabase()

const App = () => {
return (
<RecoilRoot>
<div
id="primary-container"
className="h-screen relative container flex flex-col max-w-[1370px] p-[1.25rem]"
>
<Toaster position="top-right" reverseOrder={false} />
<Header />
<div className="container py-8 flex flex-1 overflow-y-auto justify-start h-full">
<Chat rtdbRef={db} />
<AuthWrapper>
<RecoilRoot>
<div
id="primary-container"
className="h-screen relative container flex flex-col max-w-[1370px] p-[1.25rem]"
>
<Toaster position="top-right" reverseOrder={false} />
<Header />
<div className="container py-8 flex flex-1 overflow-y-auto justify-start h-full">
<Chat rtdbRef={db} />
</div>
</div>
</div>
</RecoilRoot>
</RecoilRoot>
</AuthWrapper>
)
}

Expand Down
29 changes: 29 additions & 0 deletions web/src/components/Auth/AuthWrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useAuth } from '@/contexts/auth-context'
import React from 'react'
import { Header } from '../Header/Header'
import { Login } from './Login'

export const AuthWrapper: React.FC<{ children: React.ReactNode }> = ({
children
}) => {
const { currentUser } = useAuth()

return currentUser ? (
children
) : (
<div
id="primary-container"
className="h-screen relative container flex flex-col max-w-[1370px] p-[1.25rem]"
>
<Header />
<div className="container py-8 flex flex-1 overflow-y-auto justify-start h-full">
<div className="flex flex-col items-center self-center max-w-md">
<h1 className="text-2xl font-bold mb-4">
Please sign in to continue
</h1>
<Login />
</div>
</div>
</div>
)
}
14 changes: 14 additions & 0 deletions web/src/components/Auth/Login.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useAuth } from '@/contexts/auth-context'

export const Login = () => {
const { signInWithGoogle, authLoading } = useAuth()
return (
<button
disabled={authLoading}
onClick={signInWithGoogle}
className="bg-primary text-white text-sm font-medium py-2 px-4 rounded-lg w-full mx-auto"
>
Sign in with Google
</button>
)
}
13 changes: 13 additions & 0 deletions web/src/components/Auth/UserActions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useAuth } from '@/contexts/auth-context'

export const UserActions = () => {
const { logOut } = useAuth()
return (
<button
onClick={logOut}
className="text-sm font-medium py-2 px-4 rounded-lg w-full mx-auto"
>
Log out
</button>
)
}
2 changes: 1 addition & 1 deletion web/src/components/Chatroom/Chatroom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ export const ChatWrapper: FC<ChatWrapperProps> = ({ rtdbRef }) => {
onClick={handleLeave}
>
<BiArrowBack className="inline-block align-middle mt-[-3px]" />
Back
<p className="inline-block px-2">Back</p>
</button>
<h2 className="chat-name text-normal font-normal">
{chatroom?.name}
Expand Down
6 changes: 5 additions & 1 deletion web/src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { Branding } from './branding'
import { useAuth } from '@/contexts/auth-context'
import { GitHubIcon } from '../../icons/github-icon'
import { UserActions } from '../Auth/UserActions'
import { Branding } from './branding'

export function Header() {
const { currentUser } = useAuth()
return (
<div className="flex flex-auto flex-col items-start justify-between space-y-2 py-4 sm:flex-row sm:items-center sm:space-y-0 md:h-16 w-full mb-3">
<Branding />
Expand All @@ -13,6 +16,7 @@ export function Header() {
rel="noopener noreferrer"
>
<GitHubIcon />
{currentUser && <UserActions />}
</a>
radomird marked this conversation as resolved.
Show resolved Hide resolved
</div>
</div>
Expand Down
76 changes: 76 additions & 0 deletions web/src/contexts/auth-context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { User, signInWithPopup, signOut } from 'firebase/auth'
import React, {
createContext,
useContext,
useEffect,
useMemo,
useState
} from 'react'
import { auth, googleProvider } from '../firebase'

interface AuthContextType {
currentUser: User | undefined
authLoading: boolean
signInWithGoogle: () => void
logOut: () => void
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export const useAuth = () => {
const context = useContext(AuthContext)

if (!context) {
throw new Error('useAuth must be used within an AuthProvider')
}

return context
}

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
children
}) => {
const [currentUser, setCurrentUser] = useState<User | undefined>()
const [authLoading, setAuthLoading] = useState<boolean>(true)

const signInWithGoogle = async () => {
try {
setAuthLoading(true)
await signInWithPopup(auth, googleProvider)
} catch (err) {
console.error(err)
} finally {
setAuthLoading(false)
}
}
const logOut = async () => {
try {
await signOut(auth)
} catch (err) {
console.error(err)
}
}

useEffect(() => {
auth.onAuthStateChanged(user => {
setAuthLoading(false)
if (user) {
setCurrentUser(user)
} else {
setCurrentUser(undefined)
}
})
}, [])

const value = useMemo(
() => ({
currentUser,
authLoading,
signInWithGoogle,
logOut
}),
[currentUser, authLoading]
)

return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
Loading
Loading