40 lines
1.1 KiB
JavaScript
40 lines
1.1 KiB
JavaScript
import { useState, useContext, useEffect } from "react";
|
|
import { useSearchParams, useNavigate } from "react-router-dom";
|
|
import SettingsContext from "@mcl/settings";
|
|
|
|
const verifyAuth = (authToken) =>
|
|
fetch("/api/auth/verify", {
|
|
headers: { Authorization: `Bearer ${authToken}` },
|
|
})
|
|
.then((res) => res.status === 200)
|
|
.catch(() => false);
|
|
|
|
export function useCairoAuth() {
|
|
const { state: settings, updateSettings } = useContext(SettingsContext);
|
|
const [auth, setAuth] = useState(!!settings.cairoAuth);
|
|
const [searchParams] = useSearchParams();
|
|
const nav = useNavigate();
|
|
|
|
useEffect(() => {
|
|
const webToken = searchParams.get("cairoAuthToken");
|
|
if (!webToken) return;
|
|
verifyAuth(webToken).then(setAuth);
|
|
updateSettings({ cairoAuth: webToken });
|
|
nav("/");
|
|
}, [searchParams]);
|
|
|
|
useEffect(() => {
|
|
verifyAuth(settings.cairoAuth).then(setAuth);
|
|
nav("/");
|
|
}, [settings.cairoAuth]);
|
|
|
|
return auth;
|
|
}
|
|
|
|
export function getAuthTokenFromStorage() {
|
|
return JSON.parse(localStorage.getItem("settings")).cairoAuth;
|
|
}
|
|
|
|
export function cairoAuthHeader() {
|
|
return { Authorization: `Bearer ${getAuthTokenFromStorage()}` };
|
|
}
|