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

[QF-1165]: resolves the build and redirect issue #2233

Merged
merged 3 commits into from
Nov 10, 2024
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
2 changes: 1 addition & 1 deletion src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
makeWordByWordTranslationsUrl,
} from '@/utils/apiPaths';
import generateSignature from '@/utils/auth/signature';
import { isStaticBuild } from '@/utils/build';
import { SearchRequest, AdvancedCopyRequest, PagesLookUpRequest } from 'types/ApiRequests';
import {
TranslationsResponse,
Expand Down Expand Up @@ -65,7 +66,6 @@ export const X_AUTH_SIGNATURE = 'x-auth-signature';
export const X_TIMESTAMP = 'x-timestamp';
export const X_INTERNAL_CLIENT = 'x-internal-client';

const isStaticBuild = process.env.IS_BUILD_TIME === 'true';
export const fetcher = async function fetcher<T>(
input: RequestInfo,
init: RequestInit = {},
Expand Down
13 changes: 8 additions & 5 deletions src/pages/auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ interface AuthProps {
error?: string;
}

const LOGIN_URL = '/login';

const Auth: React.FC<AuthProps> = ({ error }) => {
const router = useRouter();
const toast = useToast();
Expand All @@ -37,14 +39,14 @@ const Auth: React.FC<AuthProps> = ({ error }) => {
*
* @param {GetServerSidePropsContext} context - The context object containing request and response information.
* @param {string} token - The token used for authentication and redirection.
* @param {string} redirectUrl - The URL to redirect the user to after successful token handling.
* @param {string} destination - The URL to redirect the user to after successful token handling.
* @returns {Promise<GetServerSidePropsResult<any>>} - A promise that resolves to the server-side props result,
* which includes either a redirection or an error message.
*/
const handleTokenRedirection = async (
context: GetServerSidePropsContext,
token: string,
redirectUrl: string,
destination: string,
): Promise<GetServerSidePropsResult<any>> => {
try {
const baseUrl = getBaseUrl(context);
Expand All @@ -59,7 +61,7 @@ const handleTokenRedirection = async (
return {
props: {},
redirect: {
destination: redirectUrl,
destination,
permanent: false,
},
};
Expand Down Expand Up @@ -128,15 +130,16 @@ const setProxyCookies = (response: Response, context: GetServerSidePropsContext)
export const getServerSideProps: GetServerSideProps = async (context) => {
const { r, token } = context.query;
const redirectUrl = (r || '/') as string;
const destination = redirectUrl === LOGIN_URL ? '/' : redirectUrl;

if (token) {
return handleTokenRedirection(context, token as string, redirectUrl);
return handleTokenRedirection(context, token as string, destination);
}

return {
props: {},
redirect: {
destination: redirectUrl,
destination,
permanent: false,
},
};
Expand Down
2 changes: 1 addition & 1 deletion src/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { decamelizeKeys } from 'humps';
import stringify from './qs-stringify';
import { getBasePath } from './url';

import { isStaticBuild } from '@/utils/build';
import { Mushaf, MushafLines, QuranFont, QuranFontMushaf } from 'types/QuranReader';

export const ITEMS_PER_PAGE = 10;
Expand All @@ -17,7 +18,6 @@ export const API_HOST =
process.env.NEXT_PUBLIC_VERCEL_ENV === 'production' ? PRODUCTION_API_HOST : STAGING_API_HOST;

const { API_GATEWAY_URL } = process.env;
const isStaticBuild = process.env.IS_BUILD_TIME === 'true';

/**
* Generates a url to make an api call to our backend
Expand Down
1 change: 1 addition & 0 deletions src/utils/apiPaths.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { decamelizeKeys } from 'humps';

// eslint-disable-next-line import/no-cycle
import { getDefaultWordFields, getMushafId, ITEMS_PER_PAGE, makeUrl } from './api';
import stringify from './qs-stringify';

Expand Down
24 changes: 22 additions & 2 deletions src/utils/auth/api.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
/* eslint-disable max-lines */
import { NextApiRequest } from 'next';
import { configureRefreshFetch } from 'refresh-fetch';

import { getTimezone } from '../datetime';
import { prepareGenerateMediaFileRequestData } from '../media/utils';

import generateSignature from './signature';
import BookmarkByCollectionIdQueryParams from './types/BookmarkByCollectionIdQueryParams';
import GetAllNotesQueryParams from './types/Note/GetAllNotesQueryParams';

import { fetcher, X_AUTH_SIGNATURE, X_INTERNAL_CLIENT, X_TIMESTAMP } from '@/api';
import {
FilterActivityDaysParams,
QuranActivityDay,
Expand Down Expand Up @@ -72,7 +75,7 @@ import {
makeGetMediaFileProgressUrl,
makeGetMonthlyMediaFilesCountUrl,
} from '@/utils/auth/apiPaths';
import { fetcher } from 'src/api';
import { isStaticBuild } from '@/utils/build';
import CompleteAnnouncementRequest from 'types/auth/CompleteAnnouncementRequest';
import { GetBookmarkCollectionsIdResponse } from 'types/auth/GetBookmarksByCollectionId';
import PreferenceGroup from 'types/auth/PreferenceGroup';
Expand All @@ -88,7 +91,6 @@ import { Collection } from 'types/Collection';
import CompleteSignupRequest from 'types/CompleteSignupRequest';

type RequestData = Record<string, any>;

const IGNORE_ERRORS = [
MediaRenderError.MediaVersesRangeLimitExceeded,
MediaRenderError.MediaFilesPerUserLimitExceeded,
Expand Down Expand Up @@ -445,13 +447,31 @@ export const withCredentialsFetcher = async <T>(
init?: RequestInit,
): Promise<T> => {
try {
let additionalHeaders = {};
if (isStaticBuild) {
const req: NextApiRequest = {
url: typeof input === 'string' ? input : input.url,
method: init.method || 'GET',
body: init.body,
headers: init.headers,
query: {},
} as NextApiRequest;

const { signature, timestamp } = generateSignature(req, req.url);
additionalHeaders = {
[X_AUTH_SIGNATURE]: signature,
[X_TIMESTAMP]: timestamp,
[X_INTERNAL_CLIENT]: process.env.INTERNAL_CLIENT_ID,
};
}
const data = await fetcher<T>(input, {
...init,
credentials: 'include',
headers: {
...init?.headers,
// eslint-disable-next-line @typescript-eslint/naming-convention
'x-timezone': getTimezone(),
...additionalHeaders,
},
});
return data;
Expand Down
2 changes: 2 additions & 0 deletions src/utils/build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// eslint-disable-next-line import/prefer-default-export
export const isStaticBuild = process.env.IS_BUILD_TIME === 'true';
11 changes: 8 additions & 3 deletions src/utils/url.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isStaticBuild } from '@/utils/build';

const getLocalePostfix = (locale: string) => (locale !== 'en' ? `/${locale}` : '');

export const getCurrentPath = () => {
Expand Down Expand Up @@ -43,7 +45,7 @@ export const navigateToExternalUrl = (url: string) => {
* @returns {string}
*/
export const getBasePath = (): string =>
`${process.env.NEXT_PUBLIC_VERCEL_ENV === 'development' ? 'http' : 'https'}://${
`${process.env.NEXT_PUBLIC_VERCEL_ENV === 'development' ? 'https' : 'https'}://${
process.env.NEXT_PUBLIC_VERCEL_URL
}`;

Expand All @@ -54,6 +56,9 @@ export const getBasePath = (): string =>
* @returns {string}
*/
export const getAuthApiPath = (path: string): string => {
const BASE_PATH = getBasePath();
return `${BASE_PATH}/api/proxy/auth/${path}`;
const PROXY_PATH = '/api/proxy/auth/';
const BASE_PATH = isStaticBuild
? `${process.env.API_GATEWAY_URL}/auth/`
: `${getBasePath()}${PROXY_PATH}`;
return `${BASE_PATH}${path}`;
};