2022-03-06 19:46:59 -05:00
|
|
|
import { useRouter } from "next/router";
|
2022-03-10 02:46:59 -05:00
|
|
|
import { useCallback, useEffect } from "react"
|
2022-03-09 17:57:44 -05:00
|
|
|
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 }) => {
|
2022-03-09 17:57:44 -05:00
|
|
|
const [isSignedIn, setSignedIn] = useSharedState('isSignedIn', false)
|
|
|
|
const [isLoading, setLoading] = useSharedState('isLoading', true)
|
2022-03-10 02:46:59 -05:00
|
|
|
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) {
|
2022-03-11 21:48:40 -05:00
|
|
|
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()
|
2022-03-10 02:46:59 -05:00
|
|
|
}, 10000);
|
2022-03-06 19:46:59 -05:00
|
|
|
|
|
|
|
return () => clearInterval(interval);
|
2022-03-09 17:57:44 -05:00
|
|
|
}, [setLoading, setSignedIn])
|
2022-03-06 19:46:59 -05:00
|
|
|
|
2022-03-10 02:46:59 -05:00
|
|
|
return { isSignedIn, isLoading, signout }
|
2022-03-06 19:46:59 -05:00
|
|
|
}
|
|
|
|
|
2022-03-09 17:57:44 -05:00
|
|
|
export default useSignedIn
|