CoastalCommitsPastes/client/lib/hooks/use-signed-in.ts

46 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-03-06 19:46:59 -05:00
import { useRouter } from "next/router";
import { useCallback, useEffect } from "react"
import useSharedState from "./use-shared-state";
2022-03-15 15:15:54 -04:00
import Cookies from 'js-cookie'
2022-03-06 19:46:59 -05:00
const useSignedIn = ({ redirectIfNotAuthed = false }: { redirectIfNotAuthed?: boolean }) => {
const [isSignedIn, setSignedIn] = useSharedState('isSignedIn', false)
const [isLoading, setLoading] = useSharedState('isLoading', true)
const signout = useCallback(() => setSignedIn(false), [setSignedIn])
2022-03-06 19:46:59 -05:00
const router = useRouter();
if (redirectIfNotAuthed && !isLoading && isSignedIn === false) {
router.push('/signin')
}
useEffect(() => {
async function checkToken() {
2022-03-15 15:15:54 -04:00
const token = Cookies.get('drift-token')
2022-03-06 19:46:59 -05:00
if (token) {
const response = await fetch('/server-api/auth/verify-token', {
2022-03-06 19:46:59 -05:00
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
})
if (response.ok) {
setSignedIn(true)
}
}
setLoading(false)
}
setLoading(true)
checkToken()
const interval = setInterval(() => {
checkToken()
}, 10000);
2022-03-06 19:46:59 -05:00
return () => clearInterval(interval);
}, [setLoading, setSignedIn])
2022-03-06 19:46:59 -05:00
return { isSignedIn, isLoading, signout }
2022-03-06 19:46:59 -05:00
}
export default useSignedIn