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

GFF-250: adjust popup window size when connecting remote commons #327

Merged
merged 8 commits into from
Feb 7, 2025
Merged
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
876 changes: 579 additions & 297 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,16 +73,16 @@
"eslint-config-next": "^14.2.15",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.30.0",
"eslint-plugin-jsx-a11y": "^6.10.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-react": "^7.36.1",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react": "^7.37.4",
"eslint-plugin-react-hooks": "^5.1.0",
"jest": "^29.7.0",
"jest-canvas-mock": "^2.5.2",
"jest-environment-jsdom": "^29.7.0",
"lerna": "^8.1.8",
"nx": "19.4.3 ",
"oxlint": "^0.9.8",
"oxlint": "^0.15.8",
"postcss-import": "^16.1.0",
"postcss-modules": "^6.0.0",
"postcss-preset-mantine": "^1.17.0",
Expand Down
100 changes: 64 additions & 36 deletions packages/core/src/features/user/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react';
import { useGetExternalLoginsQuery } from './externalLoginsSlice';
import { FileMetadata } from './types';
import { ExternalProvider, FileMetadata } from './types';
import { GUID_PREFIX_PATTERN } from '../../constants';
import { resolveDRSObjectId } from '../drsResolver/utils';

Expand Down Expand Up @@ -91,7 +92,7 @@ interface FederatedLoginStatusParams {
selectedFiles: ReadonlyArray<FileMetadata>;
}

const useGetFederatedLoginStatus = async ({
const useGetFederatedLoginStatus = ({
selectedFiles,
}: FederatedLoginStatusParams) => {
const {
Expand All @@ -100,44 +101,71 @@ const useGetFederatedLoginStatus = async ({
error: wtsError,
} = useGetExternalLoginsQuery();

if (wtsError || wtsResults === undefined) {
return { error: wtsError };
}
// State to manage the asynchronous results
const [result, setResult] = useState<{
providersToAuthenticate?: ExternalProvider[];
missingProviders?: ExternalProvider[];
error?: Error;
} | null>(null);

const providers = wtsResults.providers ?? [];

const unauthenticatedProviders = providers.filter(
(provider) => !provider.refresh_token_expiration,
);

const guidResolutions = await resolveGUIDsInSelectedFiles(selectedFiles);
const providersToAuthenticate = unauthenticatedProviders.filter(
(unauthenticatedProvider) =>
Object(guidResolutions.externalHosts)
.values()
.includes(new URL(unauthenticatedProvider.base_url).hostname),
);

const missingProviders = providersToAuthenticate.filter(
(provider) =>
!Object(guidResolutions.externalHosts)
.values()
.includes(new URL(provider.base_url).hostname),
);
if (missingProviders.length > 0) {
throw new Error(
`Could not find DRS server hostname for providers: ${missingProviders
.map((provider) => provider.name)
.join(', ')}`,
);
}
useEffect(() => {
const fetchData = async () => {
if (wtsError || !wtsResults) {
if (wtsError instanceof Error) setResult({ error: wtsError });
else setResult({ error: new Error('Unknown error') });
return;
}

const providers = wtsResults.providers ?? [];
const unauthenticatedProviders = providers.filter(
(provider) => !provider.refresh_token_expiration,
);

try {
const guidResolutions =
await resolveGUIDsInSelectedFiles(selectedFiles);
const providersToAuthenticate = unauthenticatedProviders.filter(
(unauthenticatedProvider) =>
Object.values(guidResolutions.externalHosts).includes(
new URL(unauthenticatedProvider.base_url).hostname,
),
);

const missingProviders = providersToAuthenticate.filter(
(provider) =>
!Object.values(guidResolutions.externalHosts).includes(
new URL(provider.base_url).hostname,
),
);

if (missingProviders.length > 0) {
throw new Error(
`Could not find DRS server hostname for providers: ${missingProviders
.map((provider) => provider.name)
.join(', ')}`,
);
}

setResult({
providersToAuthenticate,
missingProviders,
});
} catch (error: unknown) {
if (error instanceof Error) setResult({ error });
else setResult({ error: new Error('Unknown error') });
}
};

// Only run if there's data to act on
if (!wstIsLoading && wtsResults) {
fetchData();
}
}, [selectedFiles, wstIsLoading, wtsError, wtsResults]);

return {
data: wtsResults,
isLoading: wstIsLoading,
error: wtsError,
providersToAuthenticate: providersToAuthenticate,
missingProviders: missingProviders,
data: result,
error: result?.error || wtsError,
};
};

Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/features/user/userSliceRTK.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ export const userAuthApi = createApi({

try {
results = await fetchFence({ endpoint, headers });
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_e: unknown) {
/*
Because an "error" response is valid for the auth requests we don't want to
put the request in an error state, or it will attempt the request over and over again
Expand Down
10 changes: 8 additions & 2 deletions packages/core/src/utils/extractvalues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,16 @@ export type JSONValue = string | number | boolean | JSONValue[] | JSONObject;

import { JSONPath } from 'jsonpath-plus';

export const extractValuesFromObject = (jsonPathMappings: JsonPathMapping, obj: JSONObject): JSONObject =>{
export const extractValuesFromObject = (
jsonPathMappings: JsonPathMapping,
obj: JSONObject,
): JSONObject => {
const result: { [key: string]: any } = {};

const extractObjectValue = (jsonPath: string, obj: JSONObject): JSONValue | undefined => {
const extractObjectValue = (
jsonPath: string,
obj: JSONObject,
): JSONValue | undefined => {
const extractedValues = JSONPath({ path: jsonPath, json: obj });
return extractedValues.length > 0 ? extractedValues[0] : undefined;
};
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"copy-tailwind": "cp src/tailwind.cjs dist/tailwind.cjs",
"build": "npm run compile && npm run types && npm run rollup",
"build:clean": "npm run clean && npm run build",
"build:watch": "npm run rollup -- --watch",
"build:watch": "npm run compile && npm run rollup -- --watch",
"dev": "npm run build:watch"
},
"exports": {
Expand Down Expand Up @@ -88,7 +88,7 @@
"mantine-react-table": "^2.0.0-beta.8",
"mathjs": "^13.1.1",
"minisearch": "^6.3.0",
"next": "^14.2.23",
"next": "^15.1.6",
"next-compose-plugins": "^2.2.1",
"next-images": "^1.8.5",
"node-json-db": "^2.3.0",
Expand Down
27 changes: 10 additions & 17 deletions packages/frontend/src/components/Profile/CredentialsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,23 +67,16 @@ const CredentialsTable = () => {
header: 'Actions',
Cell: ({ row }: MRT_Cell<APIKeyStatus>) => (
<div className="flex items-center">
{row.original.actions === 'delete' ? (
<ActionIcon
onClick={() =>
removeCredential({
csrfToken: csrfToken?.csrfToken,
id: row.original.key,
})
}
>
<DeleteIcon />
</ActionIcon>
) : (
<span>
{' '}
<RefreshIcon /> <DeleteIcon />
</span>
)}
<ActionIcon
onClick={() =>
removeCredential({
csrfToken: csrfToken?.csrfToken,
id: row.original.key,
})
}
>
<DeleteIcon />
</ActionIcon>
</div>
),
},
Expand Down
47 changes: 25 additions & 22 deletions packages/frontend/src/components/Profile/ExternalProviderCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,37 @@ import {
} from 'react-icons/io';
import Link from 'next/link';
import { useDisclosure } from '@mantine/hooks';
import {
QueryActionCreatorResult,
QueryDefinition,
} from '@reduxjs/toolkit/query';

/**
* Open a new window for authentication.
* @param url - URL to open
* @param title - Title of the window
* @param refetch - refetch the external status if successful
*/
const openAuthWindow = (url: string, title: string): Promise<unknown> => {
const openAuthWindow = (
url: string,
title: string,
refetch: () => QueryActionCreatorResult<
QueryDefinition<any, any, any, any, string>
>,
): Promise<unknown> => {
const pollInterval = 500;
return new Promise((resolve, reject) => {
if (window.navigator.cookieEnabled) {
const width = Math.max(1024, window.innerWidth / 2);
const height = Math.max(1024, window.innerHeight / 2);
const dualScreenLeft = window.screenLeft ?? window.screenX;
const dualScreenTop = window.screenTop ?? window.screenY;

const width =
window.innerWidth ??
document.documentElement.clientWidth ??
screen.width;

const height =
window.innerHeight ??
document.documentElement.clientHeight ??
screen.height;

const systemZoom = width / window.screen.availWidth;

const left = (width - 500) / 2 / systemZoom + dualScreenLeft;
const top = (height - 550) / 2 / systemZoom + dualScreenTop;

const left = dualScreenLeft + (window.innerWidth - width) / 2;
const top = dualScreenTop + (window.innerHeight - height) / 2;
const win = window.open(
url,
title,
`width=${500 / systemZoom},height=${
550 / systemZoom
},top=${top},left=${left}`,
`width=${width},height=${height},left=${left},top=${top}`,
);

if (!win) {
Expand All @@ -65,9 +62,11 @@ const openAuthWindow = (url: string, title: string): Promise<unknown> => {
reject('login_error');
return;
}
refetch();
resolve('success');
}
} catch (err) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_err: unknown) {
// We just want to catch it and not reject it. Rejecting the promise leads to unexpected behavior
// where the logged-in status isn't reflected immediately as the program moves ahead w/o users
// having a chance to log in, requiring a manual screen refresh to update. By catching errors
Expand All @@ -85,11 +84,14 @@ const openAuthWindow = (url: string, title: string): Promise<unknown> => {

interface ExternalProviderCardProps extends HTMLAttributes<HTMLDivElement> {
provider: ExternalProvider;
refetch: () => QueryActionCreatorResult<
QueryDefinition<any, any, any, any, string>
>;
}

const ExternalProviderCard: React.FunctionComponent<
ExternalProviderCardProps
> = ({ provider }) => {
> = ({ provider, refetch }) => {
const [loading, handler] = useDisclosure();
return (
<Card withBorder radius="sm">
Expand Down Expand Up @@ -141,6 +143,7 @@ const ExternalProviderCard: React.FunctionComponent<
openAuthWindow(
`${providerUrl.url}${queryChar}redirect=${window.location.pathname}`,
provider.name,
refetch,
).finally(() => {
handler.close();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,18 @@ const ExternalProvidersPanel = () => {
isLoading,
isError,
isSuccess,
refetch,
} = useGetExternalLoginsQuery();

const providerCards = useMemo(
() =>
externalProviders
? externalProviders.providers.map((provider: ExternalProvider) => (
<ExternalProviderCard key={provider.base_url} provider={provider} />
<ExternalProviderCard
key={provider.base_url}
provider={provider}
refetch={refetch}
/>
))
: null,
[externalProviders],
Expand Down
Loading