2021-12-28 22:46:31 +00:00
|
|
|
import React, { useEffect, lazy, Suspense } from 'react';
|
2021-08-04 06:48:57 +00:00
|
|
|
import { Switch, Route } from 'react-router-dom';
|
|
|
|
import { useAuthorizer } from '@authorizerdev/authorizer-react';
|
2022-03-15 03:23:48 +00:00
|
|
|
import SetupPassword from './pages/setup-password';
|
2021-12-28 22:46:31 +00:00
|
|
|
|
|
|
|
const ResetPassword = lazy(() => import('./pages/rest-password'));
|
|
|
|
const Login = lazy(() => import('./pages/login'));
|
|
|
|
const Dashboard = lazy(() => import('./pages/dashboard'));
|
2021-08-04 06:48:57 +00:00
|
|
|
|
2022-03-09 04:40:39 +00:00
|
|
|
export default function Root({
|
|
|
|
globalState,
|
|
|
|
}: {
|
|
|
|
globalState: Record<string, string>;
|
|
|
|
}) {
|
2021-08-06 13:47:52 +00:00
|
|
|
const { token, loading, config } = useAuthorizer();
|
2021-08-04 06:48:57 +00:00
|
|
|
|
2021-08-06 13:47:52 +00:00
|
|
|
useEffect(() => {
|
2021-08-09 03:16:07 +00:00
|
|
|
if (token) {
|
2022-03-08 07:06:26 +00:00
|
|
|
let redirectURL = config.redirectURL || '/app';
|
2022-03-09 04:40:39 +00:00
|
|
|
let params = `access_token=${token.access_token}&id_token=${token.id_token}&expires_in=${token.expires_in}&state=${globalState.state}`;
|
|
|
|
if (token.refresh_token) {
|
|
|
|
params += `&refresh_token=${token.refresh_token}`;
|
|
|
|
}
|
2022-03-08 07:06:26 +00:00
|
|
|
const url = new URL(redirectURL);
|
|
|
|
if (redirectURL.includes('?')) {
|
|
|
|
redirectURL = `${redirectURL}&${params}`;
|
|
|
|
} else {
|
|
|
|
redirectURL = `${redirectURL}?${params}`;
|
|
|
|
}
|
|
|
|
|
2021-08-09 03:16:07 +00:00
|
|
|
if (url.origin !== window.location.origin) {
|
2022-03-07 18:14:19 +00:00
|
|
|
sessionStorage.removeItem('authorizer_state');
|
2022-03-08 07:06:26 +00:00
|
|
|
window.location.replace(redirectURL);
|
2021-08-09 03:16:07 +00:00
|
|
|
}
|
2021-08-06 13:47:52 +00:00
|
|
|
}
|
|
|
|
return () => {};
|
|
|
|
}, [token]);
|
2021-08-04 06:48:57 +00:00
|
|
|
|
2021-08-06 13:47:52 +00:00
|
|
|
if (loading) {
|
|
|
|
return <h1>Loading...</h1>;
|
|
|
|
}
|
2021-08-04 06:48:57 +00:00
|
|
|
|
2021-08-06 13:47:52 +00:00
|
|
|
if (token) {
|
|
|
|
return (
|
2021-12-28 22:46:31 +00:00
|
|
|
<Suspense fallback={<></>}>
|
|
|
|
<Switch>
|
|
|
|
<Route path="/app" exact>
|
|
|
|
<Dashboard />
|
|
|
|
</Route>
|
|
|
|
</Switch>
|
|
|
|
</Suspense>
|
2021-08-06 13:47:52 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
2021-12-28 22:46:31 +00:00
|
|
|
<Suspense fallback={<></>}>
|
|
|
|
<Switch>
|
|
|
|
<Route path="/app" exact>
|
|
|
|
<Login />
|
|
|
|
</Route>
|
|
|
|
<Route path="/app/reset-password">
|
|
|
|
<ResetPassword />
|
|
|
|
</Route>
|
2022-03-15 03:23:48 +00:00
|
|
|
<Route path="/app/setup-password">
|
|
|
|
<SetupPassword />
|
|
|
|
</Route>
|
2021-12-28 22:46:31 +00:00
|
|
|
</Switch>
|
|
|
|
</Suspense>
|
2021-08-06 13:47:52 +00:00
|
|
|
);
|
2021-08-04 06:48:57 +00:00
|
|
|
}
|