432a1dec6a
I noticed a problem with the example - when you leave it logged in for more than an hour it breaks. The example API call starts to fail with `auth/id-token-expired`. Looking at the code I saw that we never update the id token after signing in, but firebase automatically updates it every hour, meaning our `verifyIdToken` fails after an hour. So I used the `onIdTokenChanged` function from firebase to update the cookie every time the id token changes. I'm open to suggestions on refactoring the code I've added.
63 lines
1.3 KiB
JavaScript
63 lines
1.3 KiB
JavaScript
import useSWR from 'swr'
|
|
import Link from 'next/link'
|
|
import { useUser } from '../utils/auth/useUser'
|
|
|
|
const fetcher = (url, token) =>
|
|
fetch(url, {
|
|
method: 'GET',
|
|
headers: new Headers({ 'Content-Type': 'application/json', token }),
|
|
credentials: 'same-origin',
|
|
}).then((res) => res.json())
|
|
|
|
const Index = () => {
|
|
const { user, logout } = useUser()
|
|
const { data, error } = useSWR(
|
|
user ? ['/api/getFood', user.token] : null,
|
|
fetcher
|
|
)
|
|
if (!user) {
|
|
return (
|
|
<>
|
|
<p>Hi there!</p>
|
|
<p>
|
|
You are not signed in.{' '}
|
|
<Link href={'/auth'}>
|
|
<a>Sign in</a>
|
|
</Link>
|
|
</p>
|
|
</>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<div>
|
|
<div>
|
|
<p>You're signed in. Email: {user.email}</p>
|
|
<p
|
|
style={{
|
|
display: 'inline-block',
|
|
color: 'blue',
|
|
textDecoration: 'underline',
|
|
cursor: 'pointer',
|
|
}}
|
|
onClick={() => logout()}
|
|
>
|
|
Log out
|
|
</p>
|
|
</div>
|
|
<div>
|
|
<Link href={'/example'}>
|
|
<a>Another example page</a>
|
|
</Link>
|
|
</div>
|
|
{error && <div>Failed to fetch food!</div>}
|
|
{data && !error ? (
|
|
<div>Your favorite food is {data.food}.</div>
|
|
) : (
|
|
<div>Loading...</div>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export default Index
|