2019-12-23 12:16:33 +00:00
|
|
|
import React from "react";
|
2019-12-16 08:49:10 +00:00
|
|
|
import { Route } from "react-router-dom";
|
2019-12-23 12:16:33 +00:00
|
|
|
import { useDispatch } from "react-redux";
|
|
|
|
|
import { useSelector } from "store";
|
|
|
|
|
import { hasAuthExpired } from "utils/storage";
|
|
|
|
|
import { User } from "constants/userConstants";
|
2020-01-03 08:49:47 +00:00
|
|
|
import { setCurrentUserDetails } from "actions/userActions";
|
2019-12-23 12:16:33 +00:00
|
|
|
|
|
|
|
|
export const checkAuth = (dispatch: any, currentUser?: User) => {
|
|
|
|
|
return hasAuthExpired().then(hasExpired => {
|
|
|
|
|
if (!currentUser || hasExpired) {
|
2020-01-03 08:49:47 +00:00
|
|
|
dispatch(setCurrentUserDetails());
|
2019-12-23 12:16:33 +00:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const WrappedComponent = (props: any) => {
|
|
|
|
|
const dispatch = useDispatch();
|
|
|
|
|
const currentUser = useSelector(state => state.ui.users.current);
|
|
|
|
|
checkAuth(dispatch, currentUser);
|
|
|
|
|
return currentUser ? props.children : null;
|
|
|
|
|
};
|
2019-09-02 15:36:24 +00:00
|
|
|
|
2019-09-09 10:30:22 +00:00
|
|
|
const ProtectedRoute = ({
|
|
|
|
|
component: Component,
|
|
|
|
|
...rest
|
|
|
|
|
}: {
|
|
|
|
|
path: string;
|
|
|
|
|
component: React.ReactType;
|
2019-11-22 14:02:55 +00:00
|
|
|
exact?: boolean;
|
2019-09-09 10:30:22 +00:00
|
|
|
}) => {
|
2019-12-23 12:16:33 +00:00
|
|
|
return (
|
|
|
|
|
<Route
|
|
|
|
|
{...rest}
|
|
|
|
|
render={props => (
|
|
|
|
|
<WrappedComponent {...props}>
|
|
|
|
|
<Component {...props} />
|
|
|
|
|
</WrappedComponent>
|
|
|
|
|
)}
|
|
|
|
|
/>
|
|
|
|
|
);
|
2019-09-09 10:30:22 +00:00
|
|
|
};
|
2019-09-02 14:50:01 +00:00
|
|
|
|
2019-09-09 10:30:22 +00:00
|
|
|
export default ProtectedRoute;
|