diff --git a/src/App.tsx b/src/App.tsx index 9d9a8cf2fb268834f1755ec0703b0b474d02b9fc..65acb82ffdf9d89f8fa3d5e9298dd221fbc4c0d0 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -3,6 +3,7 @@ import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import { HomePage } from 'components/HomePage/HomePage'; import { AuthUser } from 'components/AuthUser/AuthUser'; import { LandingPage } from 'components/LandingPage/LandingPage'; +import { PrivateRoute } from 'components/utils/PrivateRoute/PrivateRoute'; export const App: FC = () => ( <Router> @@ -10,7 +11,7 @@ export const App: FC = () => ( <Switch> <Route path="/auth" component={AuthUser} /> <Route exact path="/" component={LandingPage} /> - <Route exact path="/home" component={HomePage} /> + <PrivateRoute path="/home" Component={HomePage} /> </Switch> </div> </Router> diff --git a/src/components/utils/PrivateRoute/PrivateRoute.tsx b/src/components/utils/PrivateRoute/PrivateRoute.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9492da915b31623b2f5c226403361f3c10f40078 --- /dev/null +++ b/src/components/utils/PrivateRoute/PrivateRoute.tsx @@ -0,0 +1,38 @@ +import React from 'react'; +import { Route, Redirect, RouteProps } from 'react-router-dom'; + +/** + * A wrapper for <Route> that redirects to the login screen if you're not yet authenticated. + * */ + +type Props = { + Component: React.FC<RouteProps>; + path: string; +}; + +/* eslint-disable react/jsx-props-no-spreading */ +export const PrivateRoute = ({ Component, path }: Props): JSX.Element => { + const isAuthed = false; + const message = 'Please log in to view this page'; + return ( + <Route + exact={false} + path={path} + render={(props: RouteProps) => + isAuthed ? ( + <Component {...props} /> + ) : ( + <Redirect + to={{ + pathname: '/auth', + state: { + message, + requestedPath: path, + }, + }} + /> + ) + } + /> + ); +};