2022-03-23 18:34:23 -04:00
|
|
|
import Cookies from "js-cookie"
|
2022-04-02 03:46:39 -04:00
|
|
|
import { useEffect } from "react"
|
2022-03-23 18:34:23 -04:00
|
|
|
import useSharedState from "./use-shared-state"
|
2022-03-06 19:46:59 -05:00
|
|
|
|
2022-04-09 02:29:31 -04:00
|
|
|
|
2022-03-21 04:36:31 -04:00
|
|
|
const useSignedIn = () => {
|
2022-03-23 18:42:22 -04:00
|
|
|
const [signedIn, setSignedIn] = useSharedState(
|
|
|
|
"signedIn",
|
|
|
|
typeof window === "undefined" ? false : !!Cookies.get("drift-token")
|
|
|
|
)
|
|
|
|
const token = Cookies.get("drift-token")
|
|
|
|
const signin = (token: string) => {
|
|
|
|
setSignedIn(true)
|
2022-04-02 03:45:26 -04:00
|
|
|
// TODO: investigate SameSite / CORS cookie security
|
2022-03-23 18:42:22 -04:00
|
|
|
Cookies.set("drift-token", token)
|
|
|
|
}
|
2022-03-06 19:46:59 -05:00
|
|
|
|
2022-04-09 02:29:31 -04:00
|
|
|
useEffect(() => {
|
|
|
|
const attemptSignIn = async () => {
|
|
|
|
// If header auth is enabled, the reverse proxy will add it between this fetch and the server.
|
|
|
|
// Otherwise, the token will be used.
|
2022-05-07 00:57:59 -04:00
|
|
|
const res = await fetch("/server-api/auth/verify-signed-in", {
|
2022-04-09 02:29:31 -04:00
|
|
|
method: "GET",
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
"Authorization": `Bearer ${token}`
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
if (res.status !== 200) {
|
|
|
|
setSignedIn(false)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
attemptSignIn()
|
|
|
|
}, [setSignedIn, token])
|
|
|
|
|
|
|
|
|
2022-03-23 18:42:22 -04:00
|
|
|
useEffect(() => {
|
|
|
|
if (token) {
|
|
|
|
setSignedIn(true)
|
|
|
|
} else {
|
|
|
|
setSignedIn(false)
|
|
|
|
}
|
|
|
|
}, [setSignedIn, token])
|
2022-03-06 19:46:59 -05:00
|
|
|
|
2022-04-02 03:46:39 -04:00
|
|
|
return { signedIn, signin, token }
|
2022-03-06 19:46:59 -05:00
|
|
|
}
|
|
|
|
|
2022-03-23 18:34:23 -04:00
|
|
|
export default useSignedIn
|