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

feat(next): supports custom login redirects in initPage #6186

Merged
merged 2 commits into from
May 3, 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 packages/next/src/exports/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ export { createPayloadRequest } from '../utilities/createPayloadRequest.js'
export { getNextRequestI18n } from '../utilities/getNextRequestI18n.js'
export { getPayloadHMR, reload } from '../utilities/getPayloadHMR.js'
export { headersWithCors } from '../utilities/headersWithCors.js'
export { initPage } from '../utilities/initPage.js'
export { initPage } from '../utilities/initPage/index.js'
149 changes: 0 additions & 149 deletions packages/next/src/utilities/initPage.ts

This file was deleted.

59 changes: 59 additions & 0 deletions packages/next/src/utilities/initPage/handleAdminPage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { Permissions } from 'payload/auth'
import type {
SanitizedCollectionConfig,
SanitizedConfig,
SanitizedGlobalConfig,
} from 'payload/types'

import { notFound } from 'next/navigation.js'

import { isAdminAuthRoute, isAdminRoute } from './shared.js'

export const handleAdminPage = ({
adminRoute,
config,
permissions,
route,
}: {
adminRoute: string
config: SanitizedConfig
permissions: Permissions
route: string
}) => {
if (isAdminRoute(route, adminRoute)) {
const routeSegments = route.replace(adminRoute, '').split('/').filter(Boolean)
const [entityType, entitySlug, createOrID] = routeSegments
const collectionSlug = entityType === 'collections' ? entitySlug : undefined
const globalSlug = entityType === 'globals' ? entitySlug : undefined
const docID = collectionSlug && createOrID !== 'create' ? createOrID : undefined

let collectionConfig: SanitizedCollectionConfig | undefined
let globalConfig: SanitizedGlobalConfig | undefined

if (collectionSlug) {
collectionConfig = config.collections.find((collection) => collection.slug === collectionSlug)

if (!collectionConfig) {
notFound()
}
}

if (globalSlug) {
globalConfig = config.globals.find((global) => global.slug === globalSlug)

if (!globalConfig) {
notFound()
}
}

if (!permissions.canAccessAdmin && !isAdminAuthRoute(route, adminRoute)) {
notFound()
}

return {
collectionConfig,
docID,
globalConfig,
}
}
}
47 changes: 47 additions & 0 deletions packages/next/src/utilities/initPage/handleAuthRedirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { redirect } from 'next/navigation.js'
import QueryString from 'qs'

import { isAdminAuthRoute, isAdminRoute } from './shared.js'

export const handleAuthRedirect = ({
adminRoute,
redirectUnauthenticatedUser,
route,
searchParams,
}: {
adminRoute: string
redirectUnauthenticatedUser: boolean | string
route: string
searchParams: { [key: string]: string | string[] }
}) => {
if (!isAdminAuthRoute(route, adminRoute)) {
if (searchParams && 'redirect' in searchParams) delete searchParams.redirect

const redirectRoute = encodeURIComponent(
route + Object.keys(searchParams ?? {}).length
? `${QueryString.stringify(searchParams, { addQueryPrefix: true })}`
: undefined,
)

const adminLoginRoute = `${adminRoute}/login`

const customLoginRoute =
typeof redirectUnauthenticatedUser === 'string' ? redirectUnauthenticatedUser : undefined

const loginRoute = isAdminRoute(route, adminRoute)
? adminLoginRoute
: customLoginRoute || '/login'

const parsedLoginRouteSearchParams = QueryString.parse(loginRoute.split('?')[1] ?? '')

const searchParamsWithRedirect = `${QueryString.stringify(
{
...parsedLoginRouteSearchParams,
...(redirectRoute ? { redirect: redirectRoute } : {}),
},
{ addQueryPrefix: true },
)}`

redirect(`${loginRoute.split('?')[0]}${searchParamsWithRedirect}`)
}
}
105 changes: 105 additions & 0 deletions packages/next/src/utilities/initPage/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import type { InitPageResult, PayloadRequestWithData, VisibleEntities } from 'payload/types'

import { initI18n } from '@payloadcms/translations'
import { findLocaleFromCode } from '@payloadcms/ui/utilities/findLocaleFromCode'
import { headers as getHeaders } from 'next/headers.js'
import { parseCookies } from 'payload/auth'
import { createLocalReq, isEntityHidden } from 'payload/utilities'
import qs from 'qs'

import type { Args } from './types.js'

import { getPayloadHMR } from '../getPayloadHMR.js'
import { getRequestLanguage } from '../getRequestLanguage.js'
import { handleAdminPage } from './handleAdminPage.js'
import { handleAuthRedirect } from './handleAuthRedirect.js'

export const initPage = async ({
config: configPromise,
redirectUnauthenticatedUser = false,
route,
searchParams,
}: Args): Promise<InitPageResult> => {
const headers = getHeaders()
const localeParam = searchParams?.locale as string
const payload = await getPayloadHMR({ config: configPromise })

const {
collections,
globals,
i18n: i18nConfig,
localization,
routes: { admin: adminRoute },
} = payload.config

const queryString = `${qs.stringify(searchParams ?? {}, { addQueryPrefix: true })}`
const defaultLocale =
localization && localization.defaultLocale ? localization.defaultLocale : 'en'
const localeCode = localeParam || defaultLocale
const locale = localization && findLocaleFromCode(localization, localeCode)
const cookies = parseCookies(headers)
const language = getRequestLanguage({ config: payload.config, cookies, headers })

const i18n = await initI18n({
config: i18nConfig,
context: 'client',
language,
})

const req = await createLocalReq(
{
fallbackLocale: null,
locale: locale.code,
req: {
i18n,
query: qs.parse(queryString, {
depth: 10,
ignoreQueryPrefix: true,
}),
url: `${payload.config.serverURL}${route}${searchParams ? queryString : ''}`,
} as PayloadRequestWithData,
},
payload,
)

const { permissions, user } = await payload.auth({ headers, req })

req.user = user

const visibleEntities: VisibleEntities = {
collections: collections
.map(({ slug, admin: { hidden } }) => (!isEntityHidden({ hidden, user }) ? slug : null))
.filter(Boolean),
globals: globals
.map(({ slug, admin: { hidden } }) => (!isEntityHidden({ hidden, user }) ? slug : null))
.filter(Boolean),
}

if (redirectUnauthenticatedUser && !user) {
handleAuthRedirect({
adminRoute,
redirectUnauthenticatedUser,
route,
searchParams,
})
}

const { collectionConfig, docID, globalConfig } = handleAdminPage({
adminRoute,
config: payload.config,
permissions,
route,
})

return {
collectionConfig,
cookies,
docID,
globalConfig,
locale,
permissions,
req,
translations: i18n.translations,
visibleEntities,
}
}
17 changes: 17 additions & 0 deletions packages/next/src/utilities/initPage/shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const authRoutes = [
'/login',
'/logout',
'/create-first-user',
'/forgot',
'/reset',
'/verify',
'/logout-inactivity',
]

export const isAdminRoute = (route: string, adminRoute: string) => {
return route.startsWith(adminRoute)
}

export const isAdminAuthRoute = (route: string, adminRoute: string) => {
return authRoutes.some((r) => route.replace(adminRoute, '').startsWith(r))
}
Loading
Loading