[FIX] Enable Production Auth
This commit is contained in:
parent
40b3a42c73
commit
f405f2bbe0
1 changed files with 22 additions and 14 deletions
|
@ -2,6 +2,9 @@ import { useState, useContext, useEffect } from "react";
|
|||
import { useSearchParams, useNavigate } from "react-router-dom";
|
||||
import SettingsContext from "@mcl/settings";
|
||||
|
||||
const tokenStorageName = "cairoAuthToken";
|
||||
const tokenQuery = "cairoAuthToken";
|
||||
|
||||
const verifyAuth = (authToken) =>
|
||||
fetch("/api/auth/verify", {
|
||||
headers: { Authorization: `Bearer ${authToken}` },
|
||||
|
@ -10,29 +13,34 @@ const verifyAuth = (authToken) =>
|
|||
.catch(() => false);
|
||||
|
||||
export function useCairoAuth() {
|
||||
const { state: settings, updateSettings } = useContext(SettingsContext);
|
||||
const [auth, setAuth] = useState(!!settings.cairoAuth);
|
||||
const [searchParams] = useSearchParams();
|
||||
const nav = useNavigate();
|
||||
const [authToken, setAuthToken] = useState(
|
||||
localStorage.getItem(tokenStorageName),
|
||||
);
|
||||
const [auth, setAuth] = useState(false);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
useEffect(() => {
|
||||
const webToken = searchParams.get("cairoAuthToken");
|
||||
if (!authToken) return;
|
||||
verifyAuth(authToken).then((authorized) => {
|
||||
if (!authorized) localStorage.removeItem(tokenStorageName);
|
||||
setAuth(authorized);
|
||||
});
|
||||
}, [authToken]);
|
||||
|
||||
useEffect(() => {
|
||||
const webToken = searchParams.get(tokenQuery);
|
||||
if (!webToken) return;
|
||||
verifyAuth(webToken).then(setAuth);
|
||||
updateSettings({ cairoAuth: webToken });
|
||||
nav("/");
|
||||
localStorage.setItem(tokenStorageName, webToken);
|
||||
searchParams.delete(tokenQuery);
|
||||
setAuthToken(webToken);
|
||||
setSearchParams(searchParams);
|
||||
}, [searchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
verifyAuth(settings.cairoAuth).then(setAuth);
|
||||
nav("/");
|
||||
}, [settings.cairoAuth]);
|
||||
|
||||
return auth;
|
||||
}
|
||||
|
||||
export function getAuthTokenFromStorage() {
|
||||
return JSON.parse(localStorage.getItem("settings")).cairoAuth;
|
||||
return localStorage.getItem(tokenStorageName);
|
||||
}
|
||||
|
||||
export function cairoAuthHeader() {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue