Fix authenticated routing issues
This commit is contained in:
18
src/components/Routes/AuthRoute.jsx
Normal file
18
src/components/Routes/AuthRoute.jsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import React from 'react';
|
||||
import { Redirect, Route } from 'react-router-dom';
|
||||
|
||||
export const TYPES = {
|
||||
PUBLIC: 0,
|
||||
GUEST: 1,
|
||||
PROTECTED: 2,
|
||||
};
|
||||
|
||||
export const AuthRoute = ({ token, type, ...others }) => {
|
||||
if (!token && type === TYPES.PROTECTED) {
|
||||
return <Redirect to="/" />;
|
||||
}
|
||||
else if (token && type === TYPES.GUEST) {
|
||||
return <Redirect to="/home" />;
|
||||
}
|
||||
return <Route render {...others} />;
|
||||
}
|
||||
@@ -3,7 +3,9 @@ import { Redirect, Route } from 'react-router-dom';
|
||||
import { useUserContext } from '../Contexts/UserContext';
|
||||
|
||||
export const ProtectedRoute = ({ render, ...others }) => {
|
||||
const { token, setError } = useUserContext();
|
||||
const context = useUserContext();
|
||||
const { token, setError } = context;
|
||||
debugger;
|
||||
if (!token) {
|
||||
setError('Please sign in to access');
|
||||
return <Redirect to="/" />;
|
||||
|
||||
34
src/components/Routes/SiteRoutes.jsx
Normal file
34
src/components/Routes/SiteRoutes.jsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import React, { Suspense } from 'react';
|
||||
import {
|
||||
BrowserRouter,
|
||||
Switch,
|
||||
Route
|
||||
} from 'react-router-dom';
|
||||
|
||||
import { AuthRoute, TYPES } from '../Routes/AuthRoute'
|
||||
import { MessageBar } from '../MessageBar';
|
||||
import { useUserContext } from '../Contexts/UserContext';
|
||||
|
||||
const SignInForm = React.lazy(() => import('../SignInForm'));
|
||||
const SignUpForm = React.lazy(() => import('../SignUpForm'));
|
||||
const FileUploadForm = React.lazy(() => import('../FileUploadForm'));
|
||||
|
||||
const SiteRoutes = () => {
|
||||
const { token } = useUserContext();
|
||||
console.log('SiteRoutes', token);
|
||||
return (
|
||||
<Suspense fallback={"Loading..."}>
|
||||
<MessageBar />
|
||||
<BrowserRouter>
|
||||
<Switch>
|
||||
<AuthRoute path="/" exact render={() => <SignInForm />} type={TYPES.GUEST} token={token} />
|
||||
<AuthRoute path="/signup" exact render={() => <SignUpForm />} type={TYPES.GUEST} token={token} />
|
||||
<AuthRoute path="/home" render={() => <FileUploadForm />} type={TYPES.PROTECTED} token={token} />
|
||||
</Switch>
|
||||
</BrowserRouter>
|
||||
</Suspense>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
export default SiteRoutes;
|
||||
Reference in New Issue
Block a user