diff --git a/web/lib/firebase/server-auth.ts b/web/lib/firebase/server-auth.ts index a9f52ddd..5f828683 100644 --- a/web/lib/firebase/server-auth.ts +++ b/web/lib/firebase/server-auth.ts @@ -3,6 +3,7 @@ import fetch from 'node-fetch' import { IncomingMessage, ServerResponse } from 'http' import { FIREBASE_CONFIG, PROJECT_ID } from 'common/envs/constants' import { getAuthCookies, setAuthCookies } from './auth' +import { GetServerSideProps, GetServerSidePropsContext } from 'next' const ensureApp = async () => { // Note: firebase-admin can only be imported from a server context, @@ -61,3 +62,25 @@ export const getServerAuthenticatedUid = async (ctx: RequestContext) => { } return undefined } + +export const redirectIfLoggedIn = (dest: string, fn?: GetServerSideProps) => { + return async (ctx: GetServerSidePropsContext) => { + const uid = await getServerAuthenticatedUid(ctx) + if (uid == null) { + return fn != null ? await fn(ctx) : { props: {} } + } else { + return { redirect: { destination: dest, permanent: false } } + } + } +} + +export const redirectIfLoggedOut = (dest: string, fn?: GetServerSideProps) => { + return async (ctx: GetServerSidePropsContext) => { + const uid = await getServerAuthenticatedUid(ctx) + if (uid == null) { + return { redirect: { destination: dest, permanent: false } } + } else { + return fn != null ? await fn(ctx) : { props: {} } + } + } +} diff --git a/web/pages/index.tsx b/web/pages/index.tsx index 5006e58e..44683a4f 100644 --- a/web/pages/index.tsx +++ b/web/pages/index.tsx @@ -5,20 +5,9 @@ import { Page } from 'web/components/page' import { LandingPagePanel } from 'web/components/landing-page-panel' import { Col } from 'web/components/layout/col' import { ManifoldLogo } from 'web/components/nav/manifold-logo' +import { redirectIfLoggedIn } from 'web/lib/firebase/server-auth' -import { GetServerSideProps } from 'next' -import { getServerAuthenticatedUid } from 'web/lib/firebase/server-auth' - -export const getServerSideProps: GetServerSideProps = async (ctx) => { - const uid = await getServerAuthenticatedUid(ctx) - if (uid != null) { - return { - redirect: { - destination: '/home', - permanent: false, - }, - } - } +export const getServerSideProps = redirectIfLoggedIn('/home', async (_) => { // These hardcoded markets will be shown in the frontpage for signed-out users: const hotContracts = await getContractsBySlugs([ 'will-max-go-to-prom-with-a-girl', @@ -33,7 +22,7 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => { 'will-at-least-10-world-cities-have', ]) return { props: { hotContracts } } -} +}) export default function Home(props: { hotContracts: Contract[] }) { const { hotContracts } = props