Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Removed feature to allow async permissions resolution #1142

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/group/components/GroupSharedDataUpload.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ const GroupSharedDataUpload = () => {
navigate(`/groups/${slug}`);
}, [navigate, slug]);

const { loading } = usePermissionRedirect(
usePermissionRedirect(
'sharedData.add',
group,
useMemo(() => `/groups/${group?.slug}`, [group?.slug])
);

if (fetching || loading) {
if (fetching) {
return <PageLoader />;
}

Expand Down
9 changes: 3 additions & 6 deletions src/group/membership/components/GroupMembers.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,15 @@ const Header = props => {
)
);

const { loading: loadingPermissions, allowed } = usePermission(
'group.manageMembers',
group
);
const { allowed } = usePermission('group.manageMembers', group);

const { loading } = usePermissionRedirect(
usePermissionRedirect(
'group.viewMembers',
group,
useMemo(() => `/groups/${group?.slug}`, [group?.slug])
);

if (fetching || loading || loadingPermissions) {
if (fetching) {
return null;
}

Expand Down
7 changes: 2 additions & 5 deletions src/landscape/components/LandscapeProfile/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,7 @@ const LandscapeProfile = () => {
const dispatch = useDispatch();
const { landscape, fetching } = useSelector(state => state.landscape.profile);
const { slug } = useParams();
const { loading: loadingPermissions, allowed } = usePermission(
'landscape.change',
landscape
);
const { allowed } = usePermission('landscape.change', landscape);

const [isEmptySections, setIsEmptySections] = useState({
developmentStrategy: false,
Expand Down Expand Up @@ -117,7 +114,7 @@ const LandscapeProfile = () => {
dispatch(refreshLandscapeView(slug));
}, [dispatch, slug]);

if (fetching || loadingPermissions) {
if (fetching) {
return <PageLoader />;
}

Expand Down
4 changes: 2 additions & 2 deletions src/landscape/components/LandscapeSharedDataUpload.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,13 @@ const LandscapeSharedDataUpload = () => {
});
}, [navigate, slug]);

const { loading } = usePermissionRedirect(
usePermissionRedirect(
'sharedData.add',
landscape?.defaultGroup,
useMemo(() => `/landscapes/${landscape?.slug}`, [landscape?.slug])
);

if (fetching || loading) {
if (fetching) {
return <PageLoader />;
}

Expand Down
9 changes: 1 addition & 8 deletions src/landscape/membership/components/LandscapeMembers.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,7 @@ const MemberLeaveButton = withProps(LandscapeMemberLeave, {

const Header = ({ landscape, fetching }) => {
const { t } = useTranslation();
const { loading: loadingPermissions, allowed } = usePermission(
'group.manageMembers',
landscape
);
const { allowed } = usePermission('group.manageMembers', landscape);

useDocumentTitle(
t('landscape.members_document_title', {
Expand All @@ -69,10 +66,6 @@ const Header = ({ landscape, fetching }) => {
)
);

if (loadingPermissions) {
return null;
}

return (
<>
<PageHeader
Expand Down
14 changes: 1 addition & 13 deletions src/permissions/components/Restricted.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,33 +16,21 @@
*/
import React from 'react';
import { usePermission } from 'permissions';
import { useTranslation } from 'react-i18next';
import { CircularProgress } from '@mui/material';

const Restricted = props => {
const { t } = useTranslation();
const {
permission,
resource,
toDisallowedUsers = false,
FallbackComponent,
LoadingComponent,
children,
} = props;
const { loading, allowed } = usePermission(permission, resource);
const { allowed } = usePermission(permission, resource);

if (!resource) {
return null;
}

if (loading) {
return LoadingComponent ? (
<LoadingComponent />
) : (
<CircularProgress aria-label={t('common.loader_label')} />
);
}

if (toDisallowedUsers ? !allowed : allowed) {
return <>{children}</>;
}
Expand Down
43 changes: 4 additions & 39 deletions src/permissions/components/Restricted.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,41 +39,9 @@ const setup = async (props, rules) => {
);
};

test('Restricted: Display default loader', async () => {
const rules = {
'resource.action': () => new Promise(() => {}),
};
await setup(
{
resource: {},
permission: 'resource.action',
children: <div>Restricted content</div>,
},
rules
);
expect(screen.queryByText('Restricted content')).not.toBeInTheDocument();
expect(screen.getByRole('progressbar')).toBeInTheDocument();
});
test('Restricted: Display custom loader', async () => {
const rules = {
'resource.action': () => new Promise(() => {}),
};
await setup(
{
resource: {},
permission: 'resource.action',
LoadingComponent: () => <div>Loading...</div>,
children: <div>Restricted content</div>,
},
rules
);
expect(screen.queryByText('Restricted content')).not.toBeInTheDocument();
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
test('Restricted: Display allowed component', async () => {
const rules = {
'resource.action': () => Promise.resolve(true),
'resource.action': () => true,
};
await setup(
{
Expand All @@ -87,7 +55,7 @@ test('Restricted: Display allowed component', async () => {
});
test('Restricted: Hide denied component', async () => {
const rules = {
'resource.action': () => Promise.resolve(false),
'resource.action': () => false,
};
await setup(
{
Expand All @@ -98,11 +66,10 @@ test('Restricted: Hide denied component', async () => {
rules
);
expect(screen.queryByText('Restricted content')).not.toBeInTheDocument();
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
});
test('Restricted: Display component for unallowed users', async () => {
const rules = {
'resource.action': () => Promise.resolve(false),
'resource.action': () => false,
};
await setup(
{
Expand All @@ -117,7 +84,7 @@ test('Restricted: Display component for unallowed users', async () => {
});
test('Restricted: Hide component for allowed users', async () => {
const rules = {
'resource.action': () => Promise.resolve(true),
'resource.action': () => true,
};
await setup(
{
Expand All @@ -129,7 +96,6 @@ test('Restricted: Hide component for allowed users', async () => {
rules
);
expect(screen.queryByText('Restricted content')).not.toBeInTheDocument();
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
});
test('Restricted: Display fallback component', async () => {
await setup({
Expand All @@ -139,6 +105,5 @@ test('Restricted: Display fallback component', async () => {
children: <div>Restricted content</div>,
});
expect(screen.queryByText('Restricted content')).not.toBeInTheDocument();
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
expect(screen.getByText('Fallback content')).toBeInTheDocument();
});
64 changes: 23 additions & 41 deletions src/permissions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,32 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
import React, { useContext, useEffect, useRef, useState } from 'react';
import React, { useCallback, useContext, useEffect, useMemo } from 'react';
import _ from 'lodash/fp';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

const defaultBehaviour = {
isAllowedTo: () => Promise.resolve(false),
isAllowedTo: () => false,
};

export const PermissionsContext = React.createContext(defaultBehaviour);

export const PermissionsProvider = ({ rules, children }) => {
const isAllowedTo = (permission, user, resource) => {
const ruleResolver = _.getOr(
defaultBehaviour.isAllowedTo,
permission,
rules
);
return !resource
? Promise.resolve(false)
: ruleResolver({ user, resource });
};
const isAllowedTo = useCallback(
(permission, user, resource) => {
const ruleResolver = _.getOr(
defaultBehaviour.isAllowedTo,
permission,
rules
);
return !resource ? false : ruleResolver({ user, resource });
},
[rules]
);

return (
<PermissionsContext.Provider value={{ isAllowedTo }}>
<PermissionsContext.Provider value={isAllowedTo}>
{children}
</PermissionsContext.Provider>
);
Expand All @@ -47,45 +48,26 @@ export const PermissionsProvider = ({ rules, children }) => {
export const usePermissionRedirect = (permission, resource, path) => {
const navigate = useNavigate();

const { loading, allowed } = usePermission(permission, resource);
const { allowed } = usePermission(permission, resource);

useEffect(() => {
if (loading) {
return;
}

if (!allowed && path) {
navigate(path);
}
}, [allowed, loading, navigate, path]);
}, [allowed, navigate, path]);

return { loading };
return { allowed };
};

export const usePermission = (permission, resource) => {
const isMounted = useRef(false);
const [loading, setLoading] = useState(true);
const [allowed, setAllowed] = useState();
const { data: user } = useSelector(state => state.account.currentUser);

const { isAllowedTo } = useContext(PermissionsContext);
const isAllowedTo = useContext(PermissionsContext);

useEffect(() => {
if (!resource) {
return;
}
isMounted.current = true;
setLoading(true);
isAllowedTo(permission, user, resource).then(allowed => {
if (isMounted.current) {
setLoading(false);
setAllowed(allowed);
}
});
return () => {
isMounted.current = false;
};
}, [isAllowedTo, permission, resource, user]);
const allowed = useMemo(
() => isAllowedTo(permission, user, resource),
[isAllowedTo, permission, resource, user]
);

return { loading, allowed };
return { allowed };
};
22 changes: 11 additions & 11 deletions src/permissions/rules.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const isAllowedToEditSharedData = ({
}) => {
const isManager = hasRole({ group, role: ROLE_MANAGER });
const isOwner = _.get('createdBy.id', dataEntry) === _.get('id', user);
return Promise.resolve(isManager || isOwner);
return isManager || isOwner;
};

const isAllowedToDeleteSharedData = ({ resource, user }) => {
Expand All @@ -71,56 +71,56 @@ const isAllowedToDeleteVisualization = ({
const isManager = hasRole({ group, role: ROLE_MANAGER });
const isOwner =
_.get('createdBy.id', visualizationConfig) === _.get('id', user);
return Promise.resolve(isManager || isOwner);
return isManager || isOwner;
};

const isAllowedToDownloadSharedData = ({ resource: group }) => {
const isMember = isApprovedMember(group);
return Promise.resolve(isMember);
return isMember;
};

const isAllowedToAddSharedData = ({ resource: group }) => {
const isMember = isApprovedMember(group);
return Promise.resolve(isMember);
return isMember;
};

const isAllowedToChangeGroup = ({ resource: group }) => {
const isManager = hasRole({ group, role: ROLE_MANAGER });
return Promise.resolve(isManager);
return isManager;
};

// is open group or closed + you are a member
const isAllowedToViewGroupMembers = ({ resource: group }) => {
const isOpenGroup = group.membershipType === MEMBERSHIP_OPEN;
if (isOpenGroup) {
return Promise.resolve(true);
return true;
}

const isMember = isApprovedMember(group);
return Promise.resolve(isMember);
return isMember;
};

const isAllowedToManageGroupMembers = ({ resource: group }) => {
const isManager = hasRole({ group, role: ROLE_MANAGER });
return Promise.resolve(isManager);
return isManager;
};

const isAllowedToViewGroupSharedData = ({ resource: group }) => {
const isMember = isApprovedMember(group);
return Promise.resolve(isMember);
return isMember;
};

const isAllowedToChangeLandscape = ({ resource: landscape }) => {
const isManager = hasRole({
group: landscape.defaultGroup,
role: ROLE_MANAGER,
});
return Promise.resolve(isManager);
return isManager;
};

const isAllowedToChangeStoryMap = ({ resource: storyMap, user }) => {
const isOwner = _.get('createdBy.id', storyMap) === _.get('id', user);
return Promise.resolve(isOwner);
return isOwner;
};

const rules = {
Expand Down
Loading