aboutsummaryrefslogtreecommitdiff
path: root/src/pages/PrivateRoute.tsx
blob: cdee67bf12f585802de159432c107f0905e60f6f (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
30
31
32
33
34
35
36
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';

const urls = {
  home: '/',
  login: '/login',
  registration: '/registration',
  profile: '/profile',
  feed: '/feed',
  notifications: '/notifications'
};

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;