2020-06-10 15:52:10 +02:00
|
|
|
import React, { useEffect, useRef, useState } from 'react';
|
2020-06-10 14:37:43 +02:00
|
|
|
import { Redirect } from 'react-router-dom';
|
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
import useUser from '../../hooks/useUser';
|
|
|
|
import hasPermissions from '../../utils/hasPermissions';
|
|
|
|
import LoadingIndicatorPage from '../LoadingIndicatorPage';
|
|
|
|
|
|
|
|
const WithPagePermissions = ({ permissions, children }) => {
|
|
|
|
const userPermissions = useUser();
|
|
|
|
const [state, setState] = useState({ isLoading: true, canAccess: false });
|
2020-06-10 15:52:10 +02:00
|
|
|
const isMounted = useRef(true);
|
2020-06-10 14:37:43 +02:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const checkPermission = async () => {
|
|
|
|
try {
|
|
|
|
const canAccess = await hasPermissions(userPermissions, permissions);
|
|
|
|
|
2020-06-10 15:52:10 +02:00
|
|
|
if (isMounted.current) {
|
|
|
|
setState({ isLoading: false, canAccess });
|
|
|
|
}
|
2020-06-10 14:37:43 +02:00
|
|
|
} catch (err) {
|
2020-06-10 15:52:10 +02:00
|
|
|
if (isMounted.current) {
|
|
|
|
console.error(err);
|
2020-06-10 14:37:43 +02:00
|
|
|
|
2020-06-10 15:52:10 +02:00
|
|
|
strapi.notification.error('notification.error');
|
|
|
|
|
|
|
|
setState({ isLoading: false });
|
|
|
|
}
|
2020-06-10 14:37:43 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
checkPermission();
|
2020-06-10 15:52:10 +02:00
|
|
|
|
|
|
|
return () => {
|
|
|
|
isMounted.current = false;
|
|
|
|
};
|
2020-06-10 14:37:43 +02:00
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
if (state.isLoading) {
|
|
|
|
return <LoadingIndicatorPage />;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!state.canAccess) {
|
|
|
|
return <Redirect to="/" />;
|
|
|
|
}
|
|
|
|
|
|
|
|
return children;
|
|
|
|
};
|
|
|
|
|
|
|
|
WithPagePermissions.defaultProps = {
|
|
|
|
permissions: [],
|
|
|
|
};
|
|
|
|
|
|
|
|
WithPagePermissions.propTypes = {
|
|
|
|
children: PropTypes.node.isRequired,
|
|
|
|
permissions: PropTypes.array,
|
|
|
|
};
|
|
|
|
|
|
|
|
export default WithPagePermissions;
|