Skip to content

refactor(site): improve minor queries and visuals on external auth #11066

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

Merged
merged 3 commits into from
Dec 6, 2023
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
63 changes: 63 additions & 0 deletions site/src/api/queries/externalAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import * as API from "api/api";
import { ExternalAuth } from "api/typesGenerated";
import { QueryClient, UseMutationOptions } from "react-query";

// Returns all configured external auths for a given user.
export const externalAuths = () => {
return {
queryKey: ["external-auth"],
queryFn: () => API.getUserExternalAuthProviders(),
};
};

export const externalAuthProvider = (providerId: string) => {
return {
queryKey: ["external-auth", providerId],
queryFn: () => API.getExternalAuthProvider(providerId),
};
};

export const externalAuthDevice = (providerId: string) => {
return {
queryFn: () => API.getExternalAuthDevice(providerId),
queryKey: ["external-auth", providerId, "device"],
};
};

export const exchangeExternalAuthDevice = (
providerId: string,
deviceCode: string,
queryClient: QueryClient,
) => {
return {
queryFn: () =>
API.exchangeExternalAuthDevice(providerId, {
device_code: deviceCode,
}),
queryKey: ["external-auth", providerId, "device", deviceCode],
onSuccess: async () => {
// Force a refresh of the Git auth status.
await queryClient.invalidateQueries(["external-auth", providerId]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know what a good solution would be off the top of my head, but my main worry here is that onSuccess has been deprecated for useQuery in React Query v5, so I feel like we shouldn't become more dependent on that API, even though we can still technically use it in v4

https://tkdodo.eu/blog/breaking-react-querys-api-on-purpose

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is absolutely true! Let me remove it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After taking a look into this specific query, I think it is not trivial to remove it right now but we definitely can get back to this when migrating to v5.

},
};
};

export const validateExternalAuth = (
queryClient: QueryClient,
): UseMutationOptions<ExternalAuth, unknown, string> => {
return {
mutationFn: API.getExternalAuthProvider,
onSuccess: (data, providerId) => {
queryClient.setQueryData(["external-auth", providerId], data);
},
};
};

export const unlinkExternalAuths = (queryClient: QueryClient) => {
return {
mutationFn: API.unlinkExternalAuthProvider,
onSuccess: async () => {
await queryClient.invalidateQueries(["external-auth"]);
},
};
};
40 changes: 0 additions & 40 deletions site/src/api/queries/externalauth.ts

This file was deleted.

69 changes: 26 additions & 43 deletions site/src/pages/ExternalAuthPage/ExternalAuthPage.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import { useQuery, useQueryClient } from "react-query";
import {
exchangeExternalAuthDevice,
getExternalAuthDevice,
getExternalAuthProvider,
} from "api/api";
import { usePermissions } from "hooks";
import { type FC } from "react";
import { useParams, useSearchParams } from "react-router-dom";
Expand All @@ -13,56 +8,44 @@ import { isAxiosError } from "axios";
import Button from "@mui/material/Button";
import { SignInLayout } from "components/SignInLayout/SignInLayout";
import { Welcome } from "components/Welcome/Welcome";
import {
externalAuthDevice,
externalAuthProvider,
exchangeExternalAuthDevice,
} from "api/queries/externalAuth";

const ExternalAuthPage: FC = () => {
const { provider } = useParams();
if (!provider) {
throw new Error("provider must exist");
}
const { provider } = useParams() as { provider: string };
const [searchParams] = useSearchParams();
const permissions = usePermissions();
const queryClient = useQueryClient();
const getExternalAuthProviderQuery = useQuery({
queryKey: ["externalauth", provider],
queryFn: () => getExternalAuthProvider(provider),
const externalAuthProviderOpts = externalAuthProvider(provider);
const externalAuthProviderQuery = useQuery({
...externalAuthProviderOpts,
refetchOnWindowFocus: true,
});

const getExternalAuthDeviceQuery = useQuery({
const externalAuthDeviceQuery = useQuery({
...externalAuthDevice(provider),
enabled:
Boolean(!getExternalAuthProviderQuery.data?.authenticated) &&
Boolean(getExternalAuthProviderQuery.data?.device),
queryFn: () => getExternalAuthDevice(provider),
queryKey: ["externalauth", provider, "device"],
Boolean(!externalAuthProviderQuery.data?.authenticated) &&
Boolean(externalAuthProviderQuery.data?.device),
refetchOnMount: false,
});
const exchangeExternalAuthDeviceQuery = useQuery({
queryFn: () =>
exchangeExternalAuthDevice(provider, {
device_code: getExternalAuthDeviceQuery.data?.device_code || "",
}),
queryKey: [
"externalauth",
...exchangeExternalAuthDevice(
provider,
getExternalAuthDeviceQuery.data?.device_code,
],
enabled: Boolean(getExternalAuthDeviceQuery.data),
onSuccess: () => {
// Force a refresh of the Git auth status.
queryClient.invalidateQueries(["externalauth", provider]).catch((ex) => {
console.error("invalidate queries", ex);
});
},
externalAuthDeviceQuery.data?.device_code ?? "",
queryClient,
),
enabled: Boolean(externalAuthDeviceQuery.data),
retry: true,
retryDelay: (getExternalAuthDeviceQuery.data?.interval || 5) * 1000,
retryDelay: (externalAuthDeviceQuery.data?.interval || 5) * 1000,
refetchOnWindowFocus: (query) =>
query.state.status === "success" ? false : "always",
});

if (
getExternalAuthProviderQuery.isLoading ||
!getExternalAuthProviderQuery.data
) {
if (externalAuthProviderQuery.isLoading || !externalAuthProviderQuery.data) {
return null;
}

Expand All @@ -73,8 +56,8 @@ const ExternalAuthPage: FC = () => {
}

if (
!getExternalAuthProviderQuery.data.authenticated &&
!getExternalAuthProviderQuery.data.device
!externalAuthProviderQuery.data.authenticated &&
!externalAuthProviderQuery.data.device
) {
const redirectedParam = searchParams?.get("redirected");
if (redirectedParam && redirectedParam.toLowerCase() === "true") {
Expand Down Expand Up @@ -111,16 +94,16 @@ const ExternalAuthPage: FC = () => {

return (
<ExternalAuthPageView
externalAuth={getExternalAuthProviderQuery.data}
externalAuth={externalAuthProviderQuery.data}
onReauthenticate={() => {
queryClient.setQueryData(["externalauth", provider], {
...getExternalAuthProviderQuery.data,
queryClient.setQueryData(externalAuthProviderOpts.queryKey, {
...externalAuthProviderQuery.data,
authenticated: false,
});
}}
viewExternalAuthConfig={permissions.viewExternalAuthConfig}
deviceExchangeError={deviceExchangeError}
externalAuthDevice={getExternalAuthDeviceQuery.data}
externalAuthDevice={externalAuthDeviceQuery.data}
/>
);
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { FC, useState } from "react";
import { UserExternalAuthSettingsPageView } from "./UserExternalAuthSettingsPageView";
import {
listUserExternalAuths,
externalAuths,
unlinkExternalAuths,
validateExternalAuth,
} from "api/queries/externalauth";
} from "api/queries/externalAuth";
import { Section } from "components/SettingsLayout/Section";
import { DeleteDialog } from "components/Dialogs/DeleteDialog/DeleteDialog";
import { useMutation, useQuery, useQueryClient } from "react-query";
Expand All @@ -17,30 +17,17 @@ const UserExternalAuthSettingsPage: FC = () => {
// need to be refetched
const [unlinked, setUnlinked] = useState(0);

const {
data: externalAuths,
error,
isLoading,
refetch,
} = useQuery(listUserExternalAuths());

const externalAuthsQuery = useQuery(externalAuths());
const [appToUnlink, setAppToUnlink] = useState<string>();
const mutateParams = unlinkExternalAuths(queryClient);
const unlinkAppMutation = useMutation({
...mutateParams,
onSuccess: async () => {
await mutateParams.onSuccess();
},
});

const unlinkAppMutation = useMutation(unlinkExternalAuths(queryClient));
const validateAppMutation = useMutation(validateExternalAuth(queryClient));

return (
<Section title="External Authentication">
<Section title="External Authentication" layout="fluid">
<UserExternalAuthSettingsPageView
isLoading={isLoading}
getAuthsError={error}
auths={externalAuths}
isLoading={externalAuthsQuery.isLoading}
getAuthsError={externalAuthsQuery.error}
auths={externalAuthsQuery.data}
unlinked={unlinked}
onUnlinkExternalAuth={(providerID: string) => {
setAppToUnlink(providerID);
Expand Down Expand Up @@ -81,7 +68,7 @@ const UserExternalAuthSettingsPage: FC = () => {
// setAppToUnlink closes the modal
setAppToUnlink(undefined);
// refetch repopulates the external auth data
await refetch();
await externalAuthsQuery.refetch();
// this tells our child components to refetch their data
// as at least 1 provider was unlinked.
setUnlinked(unlinked + 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
import { ExternalAuthPollingState } from "pages/CreateWorkspacePage/CreateWorkspacePage";
import { useState, useCallback, useEffect } from "react";
import { useQuery } from "react-query";
import { userExternalAuth } from "api/queries/externalauth";
import { externalAuthProvider } from "api/queries/externalAuth";
import { FullScreenLoader } from "components/Loader/FullScreenLoader";

export type UserExternalAuthSettingsPageViewProps = {
Expand Down Expand Up @@ -61,7 +61,7 @@ export const UserExternalAuthSettingsPageView = ({
<TableRow>
<TableCell>Application</TableCell>
<TableCell>Link</TableCell>
<TableCell></TableCell>
<TableCell width="1%"></TableCell>
</TableRow>
</TableHead>
<TableBody>
Expand Down Expand Up @@ -150,7 +150,7 @@ const ExternalAuthRow = ({
message={authenticated ? "Authenticated" : "Click to Login"}
externalAuthPollingState={externalAuthPollingState}
startPollingExternalAuth={startPollingExternalAuth}
></ExternalAuth>
/>
</TableCell>
<TableCell>
{(link || externalAuth?.authenticated) && (
Expand Down Expand Up @@ -199,7 +199,7 @@ const useExternalAuth = (providerID: string, unlinked: number) => {
}, []);

const { data: externalAuth, refetch } = useQuery({
...userExternalAuth(providerID),
...externalAuthProvider(providerID),
refetchInterval: externalAuthPollingState === "polling" ? 1000 : false,
});

Expand Down