Files
authorizer/app/src/Root.tsx

67 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-12-29 04:16:31 +05:30
import React, { useEffect, lazy, Suspense } from 'react';
import { Switch, Route } from 'react-router-dom';
import { useAuthorizer } from '@authorizerdev/authorizer-react';
2021-12-29 04:16:31 +05:30
const ResetPassword = lazy(() => import('./pages/rest-password'));
const Login = lazy(() => import('./pages/login'));
const Dashboard = lazy(() => import('./pages/dashboard'));
2022-03-09 10:10:39 +05:30
export default function Root({
globalState,
}: {
globalState: Record<string, string>;
}) {
2021-08-06 19:17:52 +05:30
const { token, loading, config } = useAuthorizer();
2021-08-06 19:17:52 +05:30
useEffect(() => {
2021-08-09 08:46:07 +05:30
if (token) {
let redirectURL = config.redirectURL || '/app';
2022-03-09 10:10:39 +05:30
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}`;
}
const url = new URL(redirectURL);
if (redirectURL.includes('?')) {
redirectURL = `${redirectURL}&${params}`;
} else {
redirectURL = `${redirectURL}?${params}`;
}
2021-08-09 08:46:07 +05:30
if (url.origin !== window.location.origin) {
2022-03-07 23:44:19 +05:30
sessionStorage.removeItem('authorizer_state');
window.location.replace(redirectURL);
2021-08-09 08:46:07 +05:30
}
2021-08-06 19:17:52 +05:30
}
return () => {};
}, [token]);
2021-08-06 19:17:52 +05:30
if (loading) {
return <h1>Loading...</h1>;
}
2021-08-06 19:17:52 +05:30
if (token) {
return (
2021-12-29 04:16:31 +05:30
<Suspense fallback={<></>}>
<Switch>
<Route path="/app" exact>
<Dashboard />
</Route>
</Switch>
</Suspense>
2021-08-06 19:17:52 +05:30
);
}
return (
2021-12-29 04:16:31 +05:30
<Suspense fallback={<></>}>
<Switch>
<Route path="/app" exact>
<Login />
</Route>
<Route path="/app/reset-password">
<ResetPassword />
</Route>
</Switch>
</Suspense>
2021-08-06 19:17:52 +05:30
);
}