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

Permissions enhancements #605

Merged
merged 35 commits into from
Jul 11, 2023
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
d3c5e31
Add sticky headers to PermissionsView
MariusDoe Jul 3, 2023
999d0b9
Replace plural header archives with singular for archive specific per…
MariusDoe Jul 3, 2023
5390860
Improve filter input visibility
MariusDoe Jul 3, 2023
df107a8
Fix save state not showing when user can't edit picture
MariusDoe Jul 3, 2023
9fe07ac
Disable map when user can't update location coordinates
MariusDoe Jul 3, 2023
b65b584
Refactor LocationManagementDialog buttons
MariusDoe Jul 3, 2023
60508f3
Merge remote-tracking branch 'origin/staging' into permissions-enhanc…
MariusDoe Jul 4, 2023
87a6664
Only show editable archives in ArchivesView
MariusDoe Jul 4, 2023
990031b
Fix Unauthorized error on MyAccountView when user can't run getUser
MariusDoe Jul 4, 2023
84255eb
Remove ability to login via resetPassword
MariusDoe Jul 5, 2023
94326b7
Fix error handling again
MariusDoe Jul 5, 2023
bc3ba93
Extract location specific permissions into own section
MariusDoe Jul 5, 2023
26deafc
Improve translation for withoutArchive
MariusDoe Jul 5, 2023
acd3a56
Clarify getUser and updateUser translations
MariusDoe Jul 5, 2023
d0850ac
Split off updateCollectionParents from updateCollection
MariusDoe Jul 5, 2023
7337cf7
Adapt ListItemButtons for users according to permissions
MariusDoe Jul 5, 2023
341a505
Translate error messages in QueryErrorDisplay
MariusDoe Jul 5, 2023
7e80678
Merge branch 'staging' into permissions-enhancements
MariusDoe Jul 5, 2023
a5beb0a
Default to pictures and texts when logged in
MariusDoe Jul 7, 2023
fd3ff59
Merge branch 'staging' into permissions-enhancements
MariusDoe Jul 7, 2023
f8b3c17
Extract PresentationModeButton
MariusDoe Jul 7, 2023
f4dd938
Add noDistractionModeStyle to PresentationModeButton
MariusDoe Jul 7, 2023
2edaa3e
Batch addPermission and deleteParameterizedPermission
MariusDoe Jul 10, 2023
8d1e6fb
Manually refetch permissions
MariusDoe Jul 10, 2023
afca54b
Extend public preset to basic preset
MariusDoe Jul 10, 2023
aa70f94
Make section titles toggle accordions instead of checkboxes
MariusDoe Jul 10, 2023
6083649
Extract SaveStatus
MariusDoe Jul 10, 2023
484d301
Add SaveStatus to PermissionsView
MariusDoe Jul 10, 2023
b39157b
Fix tests
MariusDoe Jul 10, 2023
27ea78b
Fix a5beb0a298298ea0fd4b4a3721bd0ee473b4fd4c for delayed auth loading
MariusDoe Jul 10, 2023
17735be
Fix text filter tests
MariusDoe Jul 10, 2023
6f586b6
Merge branch 'staging' into permissions-enhancements
MariusDoe Jul 11, 2023
16f6a53
Serialize picture uploading
MariusDoe Jul 11, 2023
62d7865
Rename working to isWorking
MariusDoe Jul 11, 2023
7745fa5
Readd missing copy of users array
MariusDoe Jul 11, 2023
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
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { ApolloError } from '@apollo/client';
import { useTranslation } from 'react-i18next';
import { translateErrorMessage } from '../../i18n';
import { errorToTranslatedString } from '../../helpers/app-helpers';

const QueryErrorDisplay = ({ error }: { error: ApolloError }) => {
const QueryErrorDisplay = ({ error }: { error: unknown }) => {
const { t } = useTranslation();
return <div>{translateErrorMessage(error.message, t)}</div>;
return <div>{errorToTranslatedString(error, t)}</div>;
};

export default QueryErrorDisplay;
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
import { PictureFiltersInput } from '../../../graphql/APIConnector';
import { useSimplifiedQueryResponseData } from '../../../graphql/queryUtils';
import { useCachedOnRefetch } from '../../../hooks/cache-on-refetch.hook';
import { useScroll } from '../../../hooks/context-hooks';
import { useAuth, useScroll } from '../../../hooks/context-hooks';
import useGetPictures, {
NUMBER_OF_PICTURES_LOADED_PER_FETCH,
TextFilter,
Expand Down Expand Up @@ -63,8 +63,9 @@ const PictureScrollGrid = ({
const [lastScrollHeight, setLastScrollHeight] = useState<number>(0);
const [isFetching, setIsFetching] = useState<boolean>(false);

const { loggedIn } = useAuth();
const [selectedTextFilter, setSelectedTextFilter] = useState(
textFilter ?? TextFilter.ONLY_PICTURES
textFilter ?? (loggedIn ? TextFilter.PICTURES_AND_TEXTS : TextFilter.ONLY_PICTURES)
);

const { data, loading, error, fetchMore, refetch } = useGetPictures(
Expand Down
7 changes: 4 additions & 3 deletions projects/bp-gallery/src/components/provider/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,11 @@ const AuthProvider = ({ children }: PropsWithChildren<{}>) => {
passwordConfirmation,
},
});
const jwtToken = data?.resetPassword?.jwt;
await afterLogin(errors, jwtToken);
if (!errors && data?.resetPassword) {
displaySuccess(t('admin.resetPassword.success'));
}
},
[resetPasswordMutation, afterLogin]
[resetPasswordMutation, displaySuccess, t]
);

const logout = useCallback(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ type ColorsType = Record<
| 'archiveColor'
| 'titleColor'
| 'allSearchColor'
| 'likeColor',
| 'likeColor'
| 'greyColor',
string
>;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
.transform-to-left-side-of-screen {
transform: rotate(-90deg) translate(calc(20% - 50vh), calc(60% - 50vw));
position: sticky;
top: 0;
animation: fade-in 0.5s;
}

@keyframes fade-in {
from {
opacity: 0;
}

to {
opacity: 1;
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,27 @@
import { PropsWithChildren } from 'react';
import { PropsWithChildren, useMemo } from 'react';
import { useScroll } from '../../../hooks/context-hooks';
import './CenteredContainer.scss';

export const CenteredContainer = ({
title,
titleOnLeftSideOfScreenAfterScroll = false,
children,
}: PropsWithChildren<{ title: string; titleOnLeftSideOfScreenAfterScroll?: boolean }>) => {
const { scrollPos } = useScroll();
const titleClassName = useMemo(() => {
if (!titleOnLeftSideOfScreenAfterScroll) {
return '';
}
const fadeIn = 50;
if (scrollPos >= fadeIn) {
return 'transform-to-left-side-of-screen';
}
return '';
}, [titleOnLeftSideOfScreenAfterScroll, scrollPos]);

export const CenteredContainer = ({ title, children }: PropsWithChildren<{ title: string }>) => {
return (
<div className='w-[800px] mx-auto mt-4'>
<h1>{title}</h1>
<h1 className={titleClassName}>{title}</h1>
{children}
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,22 @@ export const ArchivesView = () => {
const { data, error, loading } = useGetAllArchiveTagsQuery();
const archives: FlatArchiveTag[] | undefined = useSimplifiedQueryResponseData(data)?.archiveTags;

const {
canUseArchivesView,
canUseMultipleEditArchiveViews,
loading: canUseArchivesViewLoading,
} = useCanUseArchivesView();

const sortedArchives = useMemo(
() => (archives ? archives.slice().sort((a, b) => a.name.localeCompare(b.name)) : undefined),
[archives]
() =>
archives
? archives
.filter(archive => canUseMultipleEditArchiveViews[archive.id])
.sort((a, b) => a.name.localeCompare(b.name))
: undefined,
[archives, canUseMultipleEditArchiveViews]
);

const { canUseArchivesView, loading: canUseArchivesViewLoading } = useCanUseArchivesView();

return (
<ProtectedRoute canUse={canUseArchivesView} canUseLoading={canUseArchivesViewLoading}>
{() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const ChangePasswordView = () => {
passwordConfirmation,
},
});
if (result.data?.changePassword?.jwt) {
if (result.data?.changePassword?.user.id) {
openAlert({
alertType: AlertType.SUCCESS,
message: t('admin.changePassword.success'),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { ExpandMore } from '@mui/icons-material';
import { ExpandMore, Search } from '@mui/icons-material';
import {
Accordion,
AccordionDetails,
AccordionSummary,
Button,
Input,
Stack,
TextField,
Typography,
} from '@mui/material';
import { Operation, Parameter } from 'bp-graphql/build';
Expand Down Expand Up @@ -238,9 +238,24 @@ const PermissionsView = ({ userId }: { userId: string }) => {
})
),
}));
const accordionStyle = {
backgroundColor: '#e9e9e9',
};
return (
<Accordion key={archive?.id ?? type} sx={{ backgroundColor: '#e9e9e9' }}>
<AccordionSummary expandIcon={<ExpandMore />}>
<Accordion
key={archive?.id ?? type}
sx={accordionStyle}
classes={{
root: 'before:z-20', // ::before is the divider between Accordions
}}
>
<AccordionSummary
expandIcon={<ExpandMore />}
classes={{
root: '!sticky top-0 z-10 ',
}}
sx={accordionStyle}
>
<Typography fontWeight='bold'>
<CoverageCheckbox
coverage={combineCoverages(
Expand Down Expand Up @@ -281,7 +296,7 @@ const PermissionsView = ({ userId }: { userId: string }) => {
coverage={combineCoverages(section.groups.map(group => group.coverage))}
operations={section.groups.flatMap(group => group.operations)}
archive={archive}
label={t(`admin.permissions.section.${section.name}`)}
label={t(`admin.permissions.section.${section.name}`, { context: type })}
prompt
toggleOperations={toggleOperations}
/>
Expand Down Expand Up @@ -347,13 +362,18 @@ const PermissionsView = ({ userId }: { userId: string }) => {
? t('admin.permissions.publicTitle')
: t('admin.permissions.title', { userName: user?.username })
}
titleOnLeftSideOfScreenAfterScroll
>
<div className='mb-2'>
<Input
<TextField
fullWidth
value={filter}
onChange={onFilterChange}
placeholder={t('admin.permissions.filterPlaceholder')}
variant='outlined'
InputProps={{
endAdornment: <Search />,
}}
/>
</div>
{renderSections('system')}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,13 @@
import { useMemo } from 'react';
import { useGetUserQuery, useRemoveUserMutation } from '../../../../graphql/APIConnector';
import { useSimplifiedQueryResponseData } from '../../../../graphql/queryUtils';
import { useRemoveUserMutation } from '../../../../graphql/APIConnector';
import { useCanRemoveUser } from '../../../../hooks/can-do-hooks';
import { FlatUsersPermissionsUser } from '../../../../types/additionalFlatTypes';
import { DangerousRemoveButton } from '../DangerousRemoveButton';

export const RemoveUserButton = ({ id }: { id: string | undefined }) => {
const { data } = useGetUserQuery({
variables: {
id: id ?? '-1',
},
});
const user: FlatUsersPermissionsUser | undefined =
useSimplifiedQueryResponseData(data)?.usersPermissionsUser;

export const RemoveUserButton = ({ user }: { user: FlatUsersPermissionsUser | undefined }) => {
const [removeUserMutation] = useRemoveUserMutation();

const { canRemoveUser } = useCanRemoveUser(id);
const { canRemoveUser } = useCanRemoveUser(user?.id);

const entity = useMemo(
() =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export const UserView = ({
{t('admin.user.permissions')}
</Button>
)}
<RemoveUserButton id={user?.id} />
<RemoveUserButton user={user} />
</Stack>
</CenteredContainer>
);
Expand Down
41 changes: 30 additions & 11 deletions projects/bp-gallery/src/components/views/admin/user/UsersView.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { Edit } from '@mui/icons-material';
import { ChevronRight, Edit } from '@mui/icons-material';
import { List, ListItemButton, ListItemIcon, ListItemText } from '@mui/material';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useGetUsersQuery } from '../../../../graphql/APIConnector';
import {
useCanRunGetUserQuery,
useCanRunUpdateUserMutation,
useGetUsersQuery,
} from '../../../../graphql/APIConnector';
import { useSimplifiedQueryResponseData } from '../../../../graphql/queryUtils';
import { useVisit } from '../../../../helpers/history';
import { useCanUseUsersView } from '../../../../hooks/can-do-hooks';
import { useAuth } from '../../../../hooks/context-hooks';
import { FlatUsersPermissionsUser } from '../../../../types/additionalFlatTypes';
import Loading from '../../../common/Loading';
import ProtectedRoute from '../../../common/ProtectedRoute';
Expand All @@ -17,13 +22,17 @@ import { PUBLIC_USER_ID } from './helper';
export const UsersView = () => {
const { t } = useTranslation();
const { visit } = useVisit();
const { userId } = useAuth();

const { data, error, loading } = useGetUsersQuery();
const users: FlatUsersPermissionsUser[] | undefined =
useSimplifiedQueryResponseData(data)?.usersPermissionsUsers;

const { canRun: canGetUser } = useCanRunGetUserQuery();
const { canRun: canUpdateUser } = useCanRunUpdateUserMutation();

const sortedUsers = useMemo(
() => (users ? users.slice().sort((a, b) => a.username.localeCompare(b.username)) : undefined),
() => (users ? users.sort((a, b) => a.username.localeCompare(b.username)) : undefined),
[users]
MariusDoe marked this conversation as resolved.
Show resolved Hide resolved
);

Expand All @@ -44,14 +53,24 @@ export const UsersView = () => {
{[
{ id: PUBLIC_USER_ID, username: t('admin.users.publicUsername') },
...sortedUsers,
].map(user => (
<ListItemButton key={user.id} onClick={() => visit(`/admin/user/${user.id}`)}>
<ListItemText primary={user.username} />
<ListItemIcon>
<Edit />
</ListItemIcon>
</ListItemButton>
))}
].map(user => {
const isMe = user.id === userId;
const visible = canGetUser || isMe;
const editable = canUpdateUser || isMe;
const path = isMe ? '/my-account' : `/admin/user/${user.id}`;
return (
<ListItemButton
key={user.id}
onClick={visible ? () => visit(path) : undefined}
disabled={!visible}
>
<ListItemText primary={user.username} />
{visible && (
<ListItemIcon>{editable ? <Edit /> : <ChevronRight />}</ListItemIcon>
)}
</ListItemButton>
);
})}
</List>
</CenteredContainer>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import {
useCanRunCreateSubCollectionMutation,
useCanRunUpdateCollectionMutation,
useCanRunUpdateCollectionParentsMutation,
useCreateSubCollectionMutation,
useUpdateCollectionMutation,
useUpdateCollectionParentsMutation,
} from '../../../graphql/APIConnector';
import { FlatCollection } from '../../../types/additionalFlatTypes';
import { DialogPreset, useDialog } from '../../provider/DialogProvider';
Expand All @@ -25,10 +25,10 @@ const AddCollectionMenu = ({

const open = Boolean(anchorEl);

const [updateCollection] = useUpdateCollectionMutation({
const [updateCollectionParents] = useUpdateCollectionParentsMutation({
refetchQueries: ['getCollectionInfoById', 'getAllCollections'],
});
const { canRun: canUpdateCollection } = useCanRunUpdateCollectionMutation();
const { canRun: canUpdateCollectionParents } = useCanRunUpdateCollectionParentsMutation();

const [createSubCollection] = useCreateSubCollectionMutation({
refetchQueries: ['getCollectionInfoById', 'getAllCollections'],
Expand Down Expand Up @@ -73,18 +73,16 @@ const AddCollectionMenu = ({
}
const parents = moveCollection ? [] : originalParents.map(c => c.id);
parents.push(parentCollectionId);
updateCollection({
updateCollectionParents({
variables: {
collectionId: selectedCollection.id,
data: {
parent_collections: parents,
},
parentCollectionIds: parents,
},
});
}
});
},
[updateCollection, parentCollectionId, dialog, t]
[updateCollectionParents, parentCollectionId, dialog, t]
);

return (
Expand All @@ -97,15 +95,15 @@ const AddCollectionMenu = ({
<ListItemText>{t('curator.createCollection')}</ListItemText>
</MenuItem>
)}
{canUpdateCollection && (
{canUpdateCollectionParents && (
<MenuItem onClick={() => onLinkOrMoveSubcollection(false)}>
<ListItemIcon>
<Link />
</ListItemIcon>
<ListItemText>{t('curator.linkCollection')}</ListItemText>
</MenuItem>
)}
{canUpdateCollection && (
{canUpdateCollectionParents && (
<MenuItem onClick={() => onLinkOrMoveSubcollection(true)}>
<ListItemIcon>
<MoveDown />
Expand Down
Loading
Loading