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

Type authenticated query correctly #393

Draft
wants to merge 33 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
c8c7bb9
Add useAuthenticatedQuery
simon-debruijn Apr 13, 2022
ad56f49
Add redirect when unauthorized
simon-debruijn Apr 13, 2022
2cac594
Remove unnecessary typing
simon-debruijn Apr 13, 2022
f550c18
Sort imports
simon-debruijn Apr 14, 2022
0b55d57
Add server side api call to test example
simon-debruijn Apr 14, 2022
637eecf
Use separate prefetchAuthenticatedQuery function
simon-debruijn Apr 14, 2022
241f589
Rename file to v2
simon-debruijn Apr 14, 2022
e8340e0
Change after next build
simon-debruijn Apr 14, 2022
98e3c49
Rename type to GenerateQueryKeyArguments
simon-debruijn Apr 14, 2022
0409ad5
Remove toString
simon-debruijn Apr 14, 2022
814c0a3
Merge branch 'main' into type-authenticated-query-correctly
Anahkiasen Aug 10, 2023
90c2f98
Update useGetUserQuery
Anahkiasen Aug 10, 2023
6532974
Add types to useHeaders
Anahkiasen Aug 11, 2023
ca3892d
Update useGetPermissionsQuery
Anahkiasen Aug 11, 2023
62579f2
Update useGetRolesQuery
Anahkiasen Aug 11, 2023
960564d
Pass headers through context instead of meta
Anahkiasen Aug 11, 2023
c01e417
Update useGetUserQueryServerSide
Anahkiasen Aug 11, 2023
c08fcac
Pass headers through context instead of meta
Anahkiasen Aug 11, 2023
06cd225
Merge branch 'type-authenticated-query-correctly' into type-authentic…
Anahkiasen Aug 11, 2023
d63ebf4
Pass queryArguments as part of context
Anahkiasen Aug 11, 2023
b27f7bb
Work on failed authentication
Anahkiasen Aug 24, 2023
5cbbdc5
Fix Sidebar not returning valid JSX
Anahkiasen Aug 25, 2023
c04d9e8
Fix some TS errors
Anahkiasen Aug 25, 2023
b2f3187
Return query state
Anahkiasen Aug 25, 2023
38f474a
Try to revert some changes?
Anahkiasen Aug 25, 2023
e21e07f
Try to make authentication work properly
Anahkiasen Aug 25, 2023
8eac43b
Fix optional feature flag property
Anahkiasen Aug 25, 2023
9f578fd
Merge branch 'type-authenticated-query-correctly' into type-authentic…
Anahkiasen Aug 25, 2023
32feb8f
Make return type explicit
Anahkiasen Aug 25, 2023
343ecd1
Linting
Anahkiasen Aug 25, 2023
d8a21e1
Better handling of undefined query page
Anahkiasen Sep 7, 2023
73936c4
Correct feature flag type
Anahkiasen Sep 7, 2023
63dc168
Merge pull request #797 from cultuurnet/type-authenticated-query-corr…
Anahkiasen Sep 7, 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
154 changes: 154 additions & 0 deletions src/hooks/api/authenticated-query-v2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { useRouter } from 'next/router';
import { GetServerSidePropsContext } from 'next/types';
import { Cookies } from 'react-cookie';
import {
FetchQueryOptions,
QueryClient,
QueryFunctionContext,
QueryKey,
useQuery,
UseQueryOptions,
} from 'react-query';

import { FetchError } from '@/utils/fetchFromApi';
import { isTokenValid } from '@/utils/isTokenValid';

import { useCookiesWithOptions } from '../useCookiesWithOptions';
import { createHeaders, useHeaders } from './useHeaders';

type QueryArguments = Record<string, string>;

type GenerateQueryKeyArguments = {
queryKey: QueryKey;
queryArguments: QueryArguments;
};

type GeneratedQueryKey = readonly [QueryKey, QueryArguments];

type AuthenticatedQueryFunctionContext<TQueryArguments = unknown> =
QueryFunctionContext<GeneratedQueryKey> & {
headers: HeadersInit;
queryArguments?: TQueryArguments;
};

type ServerSideOptions = {
req: GetServerSidePropsContext['req'];
queryClient: QueryClient;
};

type PrefetchAuthenticatedQueryOptions<TQueryFnData> = {
queryArguments?: QueryArguments;
} & ServerSideOptions &
FetchQueryOptions<TQueryFnData, FetchError, TQueryFnData, QueryKey>;

type UseAuthenticatedQueryOptions<
TQueryFnData,
TQueryArguments = QueryArguments,
> = {
queryArguments?: TQueryArguments;
} & Omit<
UseQueryOptions<TQueryFnData, FetchError, TQueryFnData, QueryKey>,
'queryFn'
> & {
queryFn: (
context: AuthenticatedQueryFunctionContext,
) => TQueryFnData | Promise<TQueryFnData>;
};

const isUnAuthorized = (status: number) => [401, 403].includes(status);

const generateQueryKey = ({
queryKey,
queryArguments,
}: GenerateQueryKeyArguments): GeneratedQueryKey => {
if (Object.keys(queryArguments ?? {}).length > 0) {
return [queryKey, queryArguments];
}

return [queryKey, {}];
};

type GetPreparedOptionsArguments<TQueryFnData> = {
options: UseAuthenticatedQueryOptions<TQueryFnData>;
isTokenPresent: boolean;
headers: HeadersInit;
};

const getPreparedOptions = <TQueryFnData = unknown>({
options,
isTokenPresent,
headers,
}: GetPreparedOptionsArguments<TQueryFnData>) => {
const { queryKey, queryArguments, queryFn, ...restOptions } = options;
const generatedQueryKey = generateQueryKey({
queryKey,
queryArguments,
});

return {
...restOptions,
queryKey: generatedQueryKey,
queryArguments,
queryFn: (context) => queryFn({ ...context, queryArguments, headers }),
...('enabled' in restOptions && {
enabled: isTokenPresent && !!restOptions.enabled,
}),
};
};

const prefetchAuthenticatedQuery = async <TQueryFnData = unknown>({
req,
queryClient,
...options
}: PrefetchAuthenticatedQueryOptions<TQueryFnData>) => {
if (typeof window !== 'undefined') {
throw new Error('Only use prefetchAuthenticatedQuery in server-side code');
}

const cookies = new Cookies(req?.headers?.cookie);
const headers = createHeaders(cookies.get('token'));

const { queryKey, queryFn } = getPreparedOptions<TQueryFnData>({
// @ts-expect-error
options,
isTokenPresent: isTokenValid(cookies.get('token')),
headers,
});

return queryClient.fetchQuery<TQueryFnData, FetchError>(queryKey, queryFn);
};

const useAuthenticatedQuery = <TQueryFnData = unknown>(
options: UseAuthenticatedQueryOptions<TQueryFnData>,
) => {
const headers = useHeaders();
const { cookies, removeAuthenticationCookies } = useCookiesWithOptions([
'token',
]);
const router = useRouter();

const preparedOptions = getPreparedOptions({
options,
isTokenPresent: isTokenValid(cookies.token),
headers,
});

const result = useQuery(preparedOptions);

if (
isUnAuthorized(result?.error?.status) &&
!router.asPath.startsWith('/login') &&
router.asPath !== '/[...params]'
) {
removeAuthenticationCookies();

router.push('/login');

return;
}

return result;
};

export { prefetchAuthenticatedQuery, useAuthenticatedQuery };
export type { AuthenticatedQueryFunctionContext };
8 changes: 5 additions & 3 deletions src/hooks/api/authenticated-query.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { isEqual } from 'lodash';
import flatten from 'lodash/flatten';
import type { NextApiRequest } from 'next';
import { useRouter } from 'next/router';
import { GetServerSidePropsContext } from 'next/types';
import { useCallback } from 'react';
import { Cookies } from 'react-cookie';
import {
MutationFunction,
QueryClient,
useMutation,
useQueries,
useQuery,
useQueryClient,
UseQueryResult,
} from 'react-query';
import { useMutation, useQueries, useQuery } from 'react-query';

import { useCookiesWithOptions } from '@/hooks/useCookiesWithOptions';
import type { CalendarSummaryFormat } from '@/utils/createEmbededCalendarSummaries';
Expand All @@ -21,7 +23,7 @@ import { isTokenValid } from '@/utils/isTokenValid';
import { createHeaders, useHeaders } from './useHeaders';

type ServerSideQueryOptions = {
req?: NextApiRequest;
req?: GetServerSidePropsContext['req'];
queryClient?: QueryClient;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import getConfig from 'next/config';

import { useCookiesWithOptions } from '../useCookiesWithOptions';

const createHeaders = (token, extraHeaders) => {
const createHeaders = (
token: string,
extraHeaders: HeadersInit = {},
): HeadersInit => {
const { publicRuntimeConfig } = getConfig();

return {
Expand Down
36 changes: 20 additions & 16 deletions src/hooks/api/user.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import jwt_decode from 'jwt-decode';
import getConfig from 'next/config';

import { FetchError, fetchFromApi, isErrorObject } from '@/utils/fetchFromApi';

import { Cookies, useCookiesWithOptions } from '../useCookiesWithOptions';
import { ServerSideQueryOptions } from './authenticated-query';
import {
ServerSideQueryOptions,
useAuthenticatedQuery,
} from './authenticated-query';
prefetchAuthenticatedQuery,
useAuthenticatedQuery as useAuthenticatedQueryV2,
} from './authenticated-query-v2';

type User = {
sub: string;
Expand Down Expand Up @@ -45,7 +45,7 @@ const getUser = async (cookies: Cookies) => {
throw new FetchError(401, 'Unauthorized');
}

const userInfo = jwt_decode(cookies.idToken) as User;
const userInfo = jwt_decode<User>(cookies.idToken);
const decodedAccessToken = jwt_decode(cookies.token) as decodedAccessToken;

if (Date.now() >= decodedAccessToken.exp * 1000) {
Expand All @@ -58,7 +58,7 @@ const getUser = async (cookies: Cookies) => {
const useGetUserQuery = () => {
const { cookies } = useCookiesWithOptions(['idToken']);

return useAuthenticatedQuery({
return useAuthenticatedQueryV2({
queryKey: ['user'],
queryFn: () => getUser(cookies),
});
Expand All @@ -70,7 +70,7 @@ const useGetUserQueryServerSide = (
) => {
const cookies = req.cookies;

return useAuthenticatedQuery({
return prefetchAuthenticatedQuery({
req,
queryClient,
queryKey: ['user'],
Expand All @@ -82,19 +82,20 @@ const useGetUserQueryServerSide = (
const getPermissions = async ({ headers }) => {
const res = await fetchFromApi({
path: '/user/permissions/',
options: {
headers,
},
options: { headers },
});

if (isErrorObject(res)) {
// eslint-disable-next-line no-console
return console.error(res);
console.error(res);
return;
}
return await res.json();

return (await res.json()) as string[];
};

const useGetPermissionsQuery = (configuration = {}) =>
useAuthenticatedQuery({
useAuthenticatedQueryV2({
queryKey: ['user', 'permissions'],
queryFn: getPermissions,
...configuration,
Expand All @@ -107,15 +108,18 @@ const getRoles = async ({ headers }) => {
headers,
},
});

if (isErrorObject(res)) {
// eslint-disable-next-line no-console
return console.error(res);
console.error(res);
return;
}
return await res.json();

return (await res.json()) as any[];
};

const useGetRolesQuery = (configuration = {}) =>
useAuthenticatedQuery({
useAuthenticatedQueryV2({
queryKey: ['user', 'roles'],
queryFn: getRoles,
...configuration,
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/useFeatureFlag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,5 @@ export {
isFeatureFlagEnabledInCookies,
useFeatureFlag,
};

export type { FeatureFlagName };
Loading