-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
94 lines (83 loc) · 2.91 KB
/
index.js
File metadata and controls
94 lines (83 loc) · 2.91 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect, useLocation, useNavigate } from 'react-router-dom';
import { useAuthState } from '@rainbow-modules/firebase-hooks';
import { isRouterV6 } from '@rainbow-modules/app';
import getRedirectTo from '../../helpers/getRedirectTo';
const Private = (props) => {
// eslint-disable-next-line react/prop-types
const { location, component: Component, redirect, children, ...rest } = props;
const isAuth = useAuthState();
if (isAuth) {
if (Component) {
// eslint-disable-next-line react/jsx-props-no-spreading
return <Component location={location} {...rest} />;
}
return <div>{children}</div>;
}
if (isAuth === false) {
return (
<Redirect
to={getRedirectTo({
redirect,
location,
})}
/>
);
}
return null;
};
const WhenAuthenticatedV6 = (props) => {
// eslint-disable-next-line react/prop-types
const { component: Component, redirect, children, ...rest } = props;
const location = useLocation();
const navigate = useNavigate();
const isAuth = useAuthState();
useEffect(() => {
if (redirect && isAuth === false) {
navigate(redirect);
}
}, [isAuth, navigate, redirect]);
if (isAuth) {
if (Component) {
// eslint-disable-next-line react/jsx-props-no-spreading
return <Component location={location} {...rest} />;
}
return <div>{children}</div>;
}
return null;
};
const WhenAuthenticatedV5 = (props) => {
// eslint-disable-next-line react/prop-types
const { path, redirect, component, children } = props;
return (
<Route
path={path}
render={(...rest) => (
// eslint-disable-next-line react/jsx-props-no-spreading
<Private {...rest} redirect={redirect} component={component}>
{children}
</Private>
)}
/>
);
};
const WhenAuthenticated = isRouterV6 ? WhenAuthenticatedV6 : WhenAuthenticatedV5;
WhenAuthenticated.propTypes = {
/** The route path the component will used to match against the browser URL. */
path: PropTypes.string.isRequired,
/** The component class or function that will be rendered if the application is
* authenticated. */
component: PropTypes.func,
/** The route where the component should redirect if the application ins't authenticated. It can also be an
* object with the same shape of the `to` prop in the react router Redirect component.
*/
redirect: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
children: PropTypes.node,
};
WhenAuthenticated.defaultProps = {
component: undefined,
redirect: undefined,
children: null,
};
export default WhenAuthenticated;