Skip to content

Commit

Permalink
chore(frontend): do not parse env variables in the frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
IgnisDa committed Oct 27, 2024
1 parent d20da1a commit 63c7a86
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 53 deletions.
45 changes: 13 additions & 32 deletions apps/frontend/app/lib/utilities.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,16 +100,14 @@ export const serverGqlService = new AuthenticatedGraphQLClient(
{ headers: { Connection: "keep-alive" } },
);

export const getCookieValue = (request: Request, cookieName: string) => {
return parse(request.headers.get("cookie") || "")[cookieName];
};
export const getCookieValue = (request: Request, cookieName: string) =>
parse(request.headers.get("cookie") || "")[cookieName];

export const getAuthorizationCookie = (request: Request) => {
return getCookieValue(request, AUTH_COOKIE_NAME);
};
export const getAuthorizationCookie = (request: Request) =>
getCookieValue(request, AUTH_COOKIE_NAME);

export const redirectIfNotAuthenticatedOrUpdated = async (request: Request) => {
const { userDetails } = await getCachedUserDetails(request);
const userDetails = await getCachedUserDetails(request);
if (!userDetails || userDetails.__typename === "UserDetailsError") {
const nextUrl = withoutHost(request.url);
throw redirect($path("/auth", { [redirectToQueryParam]: nextUrl }), {
Expand All @@ -126,20 +124,6 @@ export const redirectIfNotAuthenticatedOrUpdated = async (request: Request) => {
return userDetails;
};

const expectedServerVariables = z.object({
DISABLE_TELEMETRY: z
.string()
.optional()
.transform((v) => v === "true"),
FRONTEND_UMAMI_SCRIPT_URL: z.string().optional(),
FRONTEND_UMAMI_WEBSITE_ID: z.string().optional(),
FRONTEND_UMAMI_DOMAINS: z.string().optional(),
FRONTEND_OIDC_BUTTON_LABEL: z
.string()
.default("Continue with OpenID Connect"),
FRONTEND_DASHBOARD_MESSAGE: z.string().optional(),
});

/**
* Combine multiple header objects into one (uses append so headers are not overridden)
*/
Expand Down Expand Up @@ -169,7 +153,8 @@ export const MetadataSpecificsSchema = z.object({
export const getCachedCoreDetails = async () => {
return await queryClient.ensureQueryData({
queryKey: queryFactory.miscellaneous.coreDetails().queryKey,
queryFn: () => serverGqlService.request(CoreDetailsDocument),
queryFn: () =>
serverGqlService.request(CoreDetailsDocument).then((d) => d.coreDetails),
});
};

Expand All @@ -178,11 +163,9 @@ export const getCachedUserDetails = async (request: Request) => {
return await queryClient.ensureQueryData({
queryKey: queryFactory.users.details(token ?? "").queryKey,
queryFn: () =>
serverGqlService.authenticatedRequest(
request,
UserDetailsDocument,
undefined,
),
serverGqlService
.authenticatedRequest(request, UserDetailsDocument, undefined)
.then((d) => d.userDetails),
});
};

Expand Down Expand Up @@ -294,8 +277,6 @@ export const s3FileUploader = (prefix: string) =>
return undefined;
}, unstable_createMemoryUploadHandler());

export const serverVariables = expectedServerVariables.parse(process.env);

export const toastSessionStorage = createCookieSessionStorage({
cookie: {
sameSite: "lax",
Expand Down Expand Up @@ -363,7 +344,7 @@ export const getCookiesForApplication = async (
token: string,
tokenValidForDays?: number,
) => {
const [{ coreDetails }] = await Promise.all([getCachedCoreDetails()]);
const [coreDetails] = await Promise.all([getCachedCoreDetails()]);
const maxAge =
(tokenValidForDays || coreDetails.tokenValidForDays) * 24 * 60 * 60;
const options = { maxAge, path: "/" } satisfies SerializeOptions;
Expand Down Expand Up @@ -422,9 +403,9 @@ export const redirectToFirstPageIfOnInvalidPage = async (
totalResults: number,
currentPage: number,
) => {
const { coreDetails } = await getCachedCoreDetails();
const coreDetails = await getCachedCoreDetails();
const { searchParams } = new URL(request.url);
const totalPages = Math.ceil(totalResults / coreDetails.pageLimit);
const totalPages = Math.ceil(totalResults / coreDetails.frontend.pageSize);
if (currentPage > totalPages && currentPage !== 1) {
searchParams.set(pageQueryParam, "1");
throw redirect(`?${searchParams.toString()}`);
Expand Down
4 changes: 2 additions & 2 deletions apps/frontend/app/routes/_dashboard._index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,9 @@ export default function Page() {
return (
<Container>
<Stack gap={32}>
{dashboardLayoutData.envData.FRONTEND_DASHBOARD_MESSAGE ? (
{dashboardLayoutData.coreDetails.frontend.dashboardMessage ? (
<Alert variant="default" icon={<IconInfoCircle />}>
{dashboardLayoutData.envData.FRONTEND_DASHBOARD_MESSAGE}
{dashboardLayoutData.coreDetails.frontend.dashboardMessage}
</Alert>
) : null}
{userPreferences.general.dashboard.map((de) =>
Expand Down
26 changes: 11 additions & 15 deletions apps/frontend/app/routes/_dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,6 @@ import {
useReviewEntity,
} from "~/lib/state/media";
import {
serverVariables as envData,
getAuthorizationCookie,
getCachedCoreDetails,
getCachedUserCollectionsList,
Expand All @@ -152,13 +151,11 @@ const discordLink = "https://discord.gg/D9XTg2a7R8";

export const loader = async ({ request }: LoaderFunctionArgs) => {
const userDetails = await redirectIfNotAuthenticatedOrUpdated(request);
const [userPreferences, userCollections, { coreDetails }] = await Promise.all(
[
getCachedUserPreferences(request),
getCachedUserCollectionsList(request),
getCachedCoreDetails(),
],
);
const [userPreferences, userCollections, coreDetails] = await Promise.all([
getCachedUserPreferences(request),
getCachedUserCollectionsList(request),
getCachedCoreDetails(),
]);

const mediaLinks = [
...(Object.entries(userPreferences.featuresEnabled.media || {})
Expand Down Expand Up @@ -250,16 +247,15 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
const isDemo = Boolean(decodedCookie?.access_link?.is_demo);

const shouldHaveUmami =
envData.FRONTEND_UMAMI_SCRIPT_URL &&
envData.FRONTEND_UMAMI_WEBSITE_ID &&
!envData.DISABLE_TELEMETRY &&
coreDetails.frontend.umami.scriptUrl &&
coreDetails.frontend.umami.websiteId &&
!coreDetails.disableTelemetry &&
!isDemo;

const workoutInProgress = isWorkoutActive(request);

return {
isDemo,
envData,
mediaLinks,
userDetails,
coreDetails,
Expand Down Expand Up @@ -762,9 +758,9 @@ export default function Layout() {
{loaderData.shouldHaveUmami ? (
<script
defer
src={loaderData.envData.FRONTEND_UMAMI_SCRIPT_URL}
data-website-id={loaderData.envData.FRONTEND_UMAMI_WEBSITE_ID}
data-domains={loaderData.envData.FRONTEND_UMAMI_DOMAINS}
src={loaderData.coreDetails.frontend.umami.scriptUrl}
data-domains={loaderData.coreDetails.frontend.umami.domains}
data-website-id={loaderData.coreDetails.frontend.umami.websiteId}
/>
) : null}
</>
Expand Down
7 changes: 3 additions & 4 deletions apps/frontend/app/routes/auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ import {
getCookiesForApplication,
redirectWithToast,
serverGqlService,
serverVariables,
} from "~/lib/utilities.server";

const searchParamsSchema = z.object({
Expand Down Expand Up @@ -79,14 +78,14 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
);
throw redirect($path("/"));
}
const [{ coreDetails }] = await Promise.all([getCachedCoreDetails()]);
const [coreDetails] = await Promise.all([getCachedCoreDetails()]);
return {
intent: query.intent || "login",
oidcEnabled: coreDetails.oidcEnabled,
oidcButtonLabel: serverVariables.FRONTEND_OIDC_BUTTON_LABEL,
signupAllowed: coreDetails.signupAllowed,
localAuthDisabled: coreDetails.localAuthDisabled,
tokenValidForDays: coreDetails.tokenValidForDays,
signupAllowed: coreDetails.signupAllowed,
oidcButtonLabel: coreDetails.frontend.oidcButtonLabel,
};
};

Expand Down

0 comments on commit 63c7a86

Please sign in to comment.