aboutsummaryrefslogtreecommitdiff
path: root/src/pages/PrivateRoute.tsx
blob: 685e53d8c66ffb9ebf5334cf52626645ebf437c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';
import urls from './urls';


const PrivateRoute: React.FC<any> = ({ component: ProtectedComponent, ...rest }) => {
  const { isAuthenticated } = useAuth();

  const getComponent: React.FC<any> = (props) => {
    if (props.match.path === urls.login || props.match.path === urls.registration) {
      return isAuthenticated() ? (
        <Redirect to={urls.profile} />
      ) : (
        <ProtectedComponent {...props} />
      );
    }

    return isAuthenticated() ? (
      <ProtectedComponent {...props} />
    ) : (
      <Redirect to={{ pathname: urls.login, state: { from: props.location } }} />
    );
  }

  return <Route {...rest} render={getComponent} />;
};

export default PrivateRoute;