Skip to content

Commit

Permalink
fix(plugin-multi-tenant): prevent throwing when no user exists (#10699)
Browse files Browse the repository at this point in the history
### What?
Fixes issue where the provider would throw an error and prevent the
login screen from loading if there was no user.

### Why?
Missing try/catch around tenant find for the provider. (Missed because
test suites have autoLogin: true)

### How?
Adds try/catch around find query.
  • Loading branch information
JarrodMFlesch authored Jan 21, 2025
1 parent 3e0baf5 commit a9c0832
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 14 deletions.
2 changes: 1 addition & 1 deletion examples/multi-tenant/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"dependencies": {
"@payloadcms/db-mongodb": "latest",
"@payloadcms/next": "latest",
"@payloadcms/plugin-multi-tenant": "file:payloadcms-plugin-multi-tenant-3.15.1.tgz",
"@payloadcms/plugin-multi-tenant": "latest",
"@payloadcms/richtext-lexical": "latest",
"@payloadcms/ui": "latest",
"cross-env": "^7.0.3",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import type { OptionObject } from 'payload'

import { useAuth } from '@payloadcms/ui'
import { useRouter } from 'next/navigation.js'
import React, { createContext } from 'react'

Expand Down Expand Up @@ -34,6 +35,8 @@ export const TenantSelectionProviderClient = ({
initialValue || SELECT_ALL,
)
const [preventRefreshOnChange, setPreventRefreshOnChange] = React.useState(false)
const { user } = useAuth()
const userID = React.useMemo(() => user?.id, [user?.id])

const router = useRouter()

Expand Down Expand Up @@ -72,6 +75,10 @@ export const TenantSelectionProviderClient = ({
}
}, [initialValue, setTenant, selectedTenantID, tenantOptions])

React.useEffect(() => {
router.refresh()
}, [userID, router])

return (
<Context.Provider
value={{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,26 @@ export const TenantSelectionProvider = async ({
useAsTitle,
user,
}: Args) => {
const { docs: userTenants } = await payload.find({
collection: tenantsCollectionSlug,
depth: 0,
limit: 1000,
overrideAccess: false,
sort: useAsTitle,
user,
})

const tenantOptions: OptionObject[] = userTenants.map((doc) => ({
label: String(doc[useAsTitle]),
value: String(doc.id),
}))
let tenantOptions: OptionObject[] = []

try {
const { docs: userTenants } = await payload.find({
collection: tenantsCollectionSlug,
depth: 0,
limit: 1000,
overrideAccess: false,
sort: useAsTitle,
user,
})

tenantOptions = userTenants.map((doc) => ({
label: String(doc[useAsTitle]),
value: String(doc.id),
}))
} catch (_) {
// user likely does not have access
}

const cookies = await getCookies()
const tenantCookie = cookies.get('payload-tenant')?.value
const selectedTenant =
Expand Down

0 comments on commit a9c0832

Please # to comment.