Add helpers for creating server-side redirects

This commit is contained in:
Marshall Polaris 2022-07-07 23:27:00 -07:00
parent 3d454ed03c
commit 3405096438
2 changed files with 26 additions and 14 deletions

View File

@ -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: {} }
}
}
}

View File

@ -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