feat: builds multi-tenant example (#2689)

* feat: builds multi-tenant example

* chore: updates seed script logic
This commit is contained in:
Jacob Fletcher
2023-05-23 16:40:18 -04:00
committed by GitHub
parent f9de807daa
commit 2fc9288870
42 changed files with 8286 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
MONGODB_URI=mongodb://localhost/payload-example-auth
PAYLOAD_SECRET=PAYLOAD_AUTH_EXAMPLE_SECRET_KEY
PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3000
PAYLOAD_SEED=true
PAYLOAD_DROP_DATABASE=true

View File

@@ -0,0 +1,4 @@
module.exports = {
root: true,
extends: ['@payloadcms'],
}

5
examples/multi-tenant/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
build
dist
node_modules
package-lock.json
.env

View File

@@ -0,0 +1 @@
legacy-peer-deps=true

View File

@@ -0,0 +1,8 @@
module.exports = {
printWidth: 100,
parser: "typescript",
semi: false,
singleQuote: true,
trailingComma: "all",
arrowParens: "avoid",
};

View File

@@ -0,0 +1,130 @@
# Payload Multi-Tenant Example
This example demonstrates how to achieve a multi-tenancy in [Payload](https://github.com/payloadcms/payload). This is a powerful way to vertically scale your application by sharing infrastructure across tenants.
## Quick Start
To spin up this example locally, follow these steps:
1. First clone the repo
1. Then `cd YOUR_PROJECT_REPO && cp .env.example .env`
1. Next `yarn && yarn dev`
1. Now `open http://localhost:3000/admin` to access the admin panel
1. Login with email `dev@payloadcms.com` and password `test`
That's it! Changes made in `./src` will be reflected in your app. See the [Development](#development) section for more details on how to log in as a tenant.
## How it works
A multi-tenant Payload application is a single server that hosts multiple "tenants". Examples of tenants may be your agency's clients, your business conglomerate's organizations, or your SaaS customers.
Each tenant has its own set of users, pages, and other data that is scoped to that tenant. This means that your application will be shared across tenants but the data will be scoped to each tenant. Tenants also run on separate domains entirely, so users are not aware of their tenancy.
### Collections
See the [Collections](https://payloadcms.com/docs/configuration/collections) docs for details on how to extend any of this functionality.
- #### Users
The `users` collection is auth-enabled and encompass both app-wide and tenant-scoped users based on the value of their `roles` and `tenants` fields. Users with the role `super-admin` can manage your entire application, while users with the _tenant role_ of `admin` have limited access to the platform and can manage only the tenant(s) they are assigned to, see [Tenants](#tenants) for more details.
For additional help with authentication, see the official [Auth Example](https://github.com/payloadcms/payload/tree/master/examples/auth/cms#readme) or the [Authentication](https://payloadcms.com/docs/authentication/overview#authentication-overview) docs.
- #### Tenants
A `tenants` collection is used to achieve tenant-based access control. Each user is assigned an array of `tenants` which includes a relationship to a `tenant` and their `roles` within that tenant. You can then scope any document within your application to any of your tenants using a simple [relationship](https://payloadcms.com/docs/fields/relationship) field on the `users` or `pages` collections, or any other collection that your application needs. The value of this field is used to filter documents in the admin panel and API to ensure that users can only access documents that belong to their tenant and are within their role. See [Access Control](#access-control) for more details.
For more details on how to extend this functionality, see the [Payload Access Control](https://payloadcms.com/docs/access-control/overview) docs.
- #### Pages
Each page is assigned a `tenant` which is used to control access and scope API requests. Pages that are created by tenants are automatically assigned that tenant based on that user's `lastLoggedInTenant` field.
## Access control
Basic role-based access control is setup to determine what users can and cannot do based on their roles, which are:
- `super-admin`: They can access the Payload admin panel to manage your multi-tenant application. They can see all tenants and make all operations.
- `user`: They can only access the Payload admin panel if they are a tenant-admin, in which case they have a limited access to operations based on their tenant (see below).
This applies to each collection in the following ways:
- `users`: Only super-admins, tenant-admins, and the user themselves can access their profile. Anyone can create a user, but only these admins can delete users. See [Users](#users) for more details.
- `tenants`: Only super-admins and tenant-admins can read, create, update, or delete tenants. See [Tenants](#tenants) for more details.
- `pages`: Everyone can access pages, but only super-admins and tenant-admins can create, update, or delete them.
> If you have versions and drafts enabled on your pages, you will need to add additional read access control condition to check the user's tenants that prevents them from accessing draft documents of other tenants.
For more details on how to extend this functionality, see the [Payload Access Control](https://payloadcms.com/docs/access-control/overview#access-control) docs.
## CORS
This multi-tenant setup requires an open CORS policy. Since each tenant contains a dynamic list of domains, there's no way to know specifically which domains to whitelist at runtime without significant performance implications. This also means that the `serverURL` is not set, as this scopes all requests to a single domain.
Alternatively, if you know the domains of your tenants ahead of time and these values won't change often, you could simply remove the `domains` field altogether and instead use static values.
For more details on this, see the [CORS](https://payloadcms.com/docs/production/preventing-abuse#cross-origin-resource-sharing-cors) docs.
## Front-end
If you're building a website or other front-end for your tenant, you will need specify the `tenant` in your requests. For example, if you wanted to fetch all pages for the tenant `ABC`, you would make a request to `/api/pages?where[tenant][slug][equals]=abc`.
For a head start on building a website for your tenant(s), check out the official [Website Template](https://github.com/payloadcms/template-website). It includes a page layout builder, preview, SEO, and much more. It is not multi-tenant, though, but you can easily take the concepts from that example and apply them here.
## Development
To spin up this example locally, follow the [Quick Start](#quick-start).
### Seed
On boot, a seed script is included to scaffold a basic database for you to use as an example. This is done by setting the `PAYLOAD_DROP_DATABASE` and `PAYLOAD_SEED` environment variables which are included in the `.env.example` by default. You can remove these from your `.env` to prevent this behavior. You can also freshly seed your project at any time by running `yarn seed`. This seed creates a super-admin user with email `dev@payloadcms.com` and password `test` along with the following tenants:
- `ABC`
- Domains:
- `abc.localhost.com:3000`
- Users:
- `admin@abc.com` with role `admin` and password `test`
- `user@abc.com` with role `user` and password `test`
- Pages:
- `ABC Home` with content `Hello, ABC!`
- `BBC`
- Domains:
- `bbc.localhost.com:3000`
- Users:
- `admin@bbc.com` with role `admin` and password `test`
- `user@bbc.com` with role `user` and password `test`
- Pages:
- `BBC Home` with content `Hello, BBC!`
> NOTICE: seeding the database is destructive because it drops your current database to populate a fresh one from the seed template. Only run this command if you are starting a new project or can afford to lose your current data.
### Hosts file
To fully experience the multi-tenancy of this example locally, your app must run on one of the domains listed in any of your tenant's `domains` field. The simplest way to do this to add the following lines to your hosts file.
```bash
# these domains were provided in the seed script
# if needed, change them based on your own tenant settings
# remember to specify the port number when browsing to these domains
127.0.0.1 abc.localhost.com
127.0.0.1 bbc.localhost.com
```
> On Mac you can find the hosts file at `/etc/hosts`. On Windows, it's at `C:\Windows\System32\drivers\etc\hosts`.
Then you can access your app at `http://abc.localhost.com:3000` and `http://bbc.localhost.com:3000`. Access control will be scoped to the correct tenant based on that user's `tenants`, see [Access Control](#access-control) for more details.
## Production
To run Payload in production, you need to build and serve the Admin panel. To do so, follow these steps:
1. First, invoke the `payload build` script by running `yarn build` or `npm run build` in your project root. This creates a `./build` directory with a production-ready admin bundle.
1. Then, run `yarn serve` or `npm run serve` to run Node in production and serve Payload from the `./build` directory.
### Deployment
The easiest way to deploy your project is to use [Payload Cloud](https://payloadcms.com/new/import), a one-click hosting solution to deploy production-ready instances of your Payload apps directly from your GitHub repo. You can also choose to self-host your app, check out the [Deployment](https://payloadcms.com/docs/production/deployment) docs for more details.
## Questions
If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/r6sCXqVk3v) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions).

View File

@@ -0,0 +1,4 @@
{
"ext": "ts",
"exec": "ts-node src/server.ts"
}

View File

@@ -0,0 +1,46 @@
{
"name": "payload-example-multi-tenant",
"description": "Payload multi-tenant example.",
"version": "1.0.0",
"main": "dist/server.js",
"license": "MIT",
"scripts": {
"dev": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts nodemon",
"seed": "rm -rf media && cross-env PAYLOAD_SEED=true PAYLOAD_DROP_DATABASE=true PAYLOAD_CONFIG_PATH=src/payload.config.ts ts-node src/server.ts",
"build:payload": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts payload build",
"build:server": "tsc",
"build": "yarn copyfiles && yarn build:payload && yarn build:server",
"serve": "cross-env PAYLOAD_CONFIG_PATH=dist/payload.config.js NODE_ENV=production node dist/server.js",
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png}\" dist/",
"generate:types": "cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:types",
"generate:graphQLSchema": "PAYLOAD_CONFIG_PATH=src/payload.config.ts payload generate:graphQLSchema",
"lint": "eslint src",
"lint:fix": "eslint --fix --ext .ts,.tsx src"
},
"dependencies": {
"dotenv": "^8.2.0",
"express": "^4.17.1",
"payload": "^1.8.2"
},
"devDependencies": {
"@payloadcms/eslint-config": "^0.0.1",
"@types/express": "^4.17.9",
"@types/node": "18.11.3",
"@types/react": "18.0.21",
"@typescript-eslint/eslint-plugin": "^5.51.0",
"@typescript-eslint/parser": "^5.51.0",
"copyfiles": "^2.4.1",
"cross-env": "^7.0.3",
"eslint": "^8.19.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-filenames": "^1.3.2",
"eslint-plugin-import": "2.25.4",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-simple-import-sort": "^10.0.0",
"nodemon": "^2.0.6",
"prettier": "^2.7.1",
"ts-node": "^9.1.1",
"typescript": "^4.8.4"
}
}

View File

@@ -0,0 +1,6 @@
import type { Access } from 'payload/types'
import { checkUserRoles } from '../../utilities/checkUserRoles'
export const lastLoggedInTenant: Access = ({ req: { user }, data }) =>
checkUserRoles(['super-admin'], user) || user?.lastLoggedInTenant?.id === data?.id

View File

@@ -0,0 +1,5 @@
import type { Access } from 'payload/config'
export const loggedIn: Access = ({ req: { user } }) => {
return Boolean(user)
}

View File

@@ -0,0 +1,21 @@
import type { Access } from 'payload/config'
import { checkUserRoles } from '../../utilities/checkUserRoles'
// the user must be an admin of the document's tenant
export const tenantAdmins: Access = ({ req: { user } }) => {
if (checkUserRoles(['super-admin'], user)) {
return true
}
return {
tenant: {
in:
user?.tenants
?.map(({ tenant, roles }) =>
roles.includes('admin') ? (typeof tenant === 'string' ? tenant : tenant.id) : null,
) // eslint-disable-line function-paren-newline
.filter(Boolean) || [],
},
}
}

View File

@@ -0,0 +1,13 @@
import type { Access } from 'payload/types'
import { isSuperAdmin } from '../../utilities/isSuperAdmin'
export const tenants: Access = ({ req: { user }, data }) =>
isSuperAdmin(user) ||
// individual documents
(data?.tenant?.id && user?.lastLoggedInTenant?.id === data.tenant.id) || {
// list of documents
tenant: {
equals: user?.lastLoggedInTenant?.id,
},
}

View File

@@ -0,0 +1,27 @@
import type { FieldHook } from 'payload/types'
const format = (val: string): string =>
val
.replace(/ /g, '-')
.replace(/[^\w-]+/g, '')
.toLowerCase()
const formatSlug =
(fallback: string): FieldHook =>
({ operation, value, originalDoc, data }) => {
if (typeof value === 'string') {
return format(value)
}
if (operation === 'create') {
const fallbackData = data?.[fallback] || originalDoc?.[fallback]
if (fallbackData && typeof fallbackData === 'string') {
return format(fallbackData)
}
}
return value
}
export default formatSlug

View File

@@ -0,0 +1,43 @@
import type { CollectionConfig } from 'payload/types'
import richText from '../fields/richText'
import { tenant } from '../fields/tenant'
import { loggedIn } from './access/loggedIn'
import { tenantAdmins } from './access/tenantAdmins'
import { tenants } from './access/tenants'
import formatSlug from './hooks/formatSlug'
export const Pages: CollectionConfig = {
slug: 'pages',
admin: {
useAsTitle: 'title',
defaultColumns: ['title', 'slug', 'updatedAt'],
},
access: {
read: tenants,
create: loggedIn,
update: tenantAdmins,
delete: tenantAdmins,
},
fields: [
{
name: 'title',
type: 'text',
required: true,
},
{
name: 'slug',
label: 'Slug',
type: 'text',
index: true,
admin: {
position: 'sidebar',
},
hooks: {
beforeValidate: [formatSlug('title')],
},
},
tenant,
richText(),
],
}

View File

@@ -0,0 +1,21 @@
import type { Access } from 'payload/config'
import { checkUserRoles } from '../../utilities/checkUserRoles'
// the user must be an admin of the tenant being accessed
export const tenantAdmins: Access = ({ req: { user } }) => {
if (checkUserRoles(['super-admin'], user)) {
return true
}
return {
id: {
in:
user?.tenants
?.map(({ tenant, roles }) =>
roles.includes('admin') ? (typeof tenant === 'string' ? tenant : tenant.id) : null,
) // eslint-disable-line function-paren-newline
.filter(Boolean) || [],
},
}
}

View File

@@ -0,0 +1,36 @@
import type { CollectionConfig } from 'payload/types'
import { superAdmins } from '../access/superAdmins'
import { tenantAdmins } from './access/tenantAdmins'
export const Tenants: CollectionConfig = {
slug: 'tenants',
access: {
create: superAdmins,
read: tenantAdmins,
update: tenantAdmins,
delete: superAdmins,
},
admin: {
useAsTitle: 'name',
},
fields: [
{
name: 'name',
type: 'text',
required: true,
},
{
name: 'domains',
type: 'array',
index: true,
fields: [
{
name: 'domain',
type: 'text',
required: true,
},
],
},
],
}

View File

@@ -0,0 +1,37 @@
import type { Access } from 'payload/config'
import type { User } from 'payload/generated-types'
import { isSuperAdmin } from '../../utilities/isSuperAdmin'
export const adminsAndSelf: Access<any, User> = async ({ req: { user } }) => {
if (user) {
if (isSuperAdmin(user)) {
return true
}
// allow users to read themselves and any users within the tenants they are admins of
return {
or: [
{
id: {
equals: user.id,
},
},
{
'tenants.tenant': {
in:
user?.tenants
?.map(({ tenant, roles }) =>
roles.includes('admin')
? typeof tenant === 'string'
? tenant
: tenant.id
: null,
) // eslint-disable-line function-paren-newline
.filter(Boolean) || [],
},
},
],
}
}
}

View File

@@ -0,0 +1,19 @@
import type { FieldAccess } from 'payload/types'
import { checkUserRoles } from '../../utilities/checkUserRoles'
import { checkTenantRoles } from '../utilities/checkTenantRoles'
export const tenantAdmins: FieldAccess = args => {
const {
req: { user },
doc,
} = args
return (
checkUserRoles(['super-admin'], user) ||
doc?.tenants?.some(({ tenant }) => {
const id = typeof tenant === 'string' ? tenant : tenant?.id
return checkTenantRoles(['admin'], user, id)
})
)
}

View File

@@ -0,0 +1,29 @@
import type { AfterChangeHook } from 'payload/dist/collections/config/types'
export const loginAfterCreate: AfterChangeHook = async ({
doc,
req,
req: { payload, body = {}, res },
operation,
}) => {
if (operation === 'create' && !req.user) {
const { email, password } = body
if (email && password) {
const { user, token } = await payload.login({
collection: 'users',
data: { email, password },
req,
res,
})
return {
...doc,
token,
user,
}
}
}
return doc
}

View File

@@ -0,0 +1,34 @@
import type { AfterLoginHook } from 'payload/dist/collections/config/types'
import { isSuperAdmin } from '../../utilities/isSuperAdmin'
export const recordLastLoggedInTenant: AfterLoginHook = async ({ req, user }) => {
try {
if (!isSuperAdmin(user)) {
const relatedOrg = await req.payload.find({
collection: 'tenants',
where: {
'domains.domain': {
in: [req.headers.host],
},
},
depth: 0,
limit: 1,
})
if (relatedOrg.docs.length > 0) {
await req.payload.update({
id: user.id,
collection: 'users',
data: {
lastLoggedInTenant: relatedOrg.docs[0].id,
},
})
}
}
} catch (err: unknown) {
req.payload.logger.error(`Error recording last logged in tenant for user ${user.id}: ${err}`)
}
return user
}

View File

@@ -0,0 +1,104 @@
import type { CollectionConfig } from 'payload/types'
import { anyone } from '../access/anyone'
import { superAdminFieldAccess } from '../access/superAdmins'
import { adminsAndSelf } from './access/adminsAndSelf'
import { tenantAdmins } from './access/tenantAdmins'
import { loginAfterCreate } from './hooks/loginAfterCreate'
import { recordLastLoggedInTenant } from './hooks/recordLastLoggedInTenant'
import { isSuperOrTenantAdmin } from './utilities/isSuperOrTenantAdmin'
export const Users: CollectionConfig = {
slug: 'users',
auth: true,
admin: {
useAsTitle: 'email',
},
access: {
read: adminsAndSelf,
create: anyone,
update: adminsAndSelf,
delete: adminsAndSelf,
admin: isSuperOrTenantAdmin,
},
hooks: {
afterChange: [loginAfterCreate],
afterLogin: [recordLastLoggedInTenant],
},
fields: [
{
name: 'firstName',
type: 'text',
},
{
name: 'lastName',
type: 'text',
},
{
name: 'roles',
type: 'select',
hasMany: true,
required: true,
access: {
create: superAdminFieldAccess,
update: superAdminFieldAccess,
read: superAdminFieldAccess,
},
options: [
{
label: 'Super Admin',
value: 'super-admin',
},
{
label: 'User',
value: 'user',
},
],
},
{
name: 'tenants',
type: 'array',
label: 'Tenants',
access: {
create: tenantAdmins,
update: tenantAdmins,
read: tenantAdmins,
},
fields: [
{
name: 'tenant',
type: 'relationship',
relationTo: 'tenants',
required: true,
},
{
name: 'roles',
type: 'select',
hasMany: true,
required: true,
options: [
{
label: 'Admin',
value: 'admin',
},
{
label: 'User',
value: 'user',
},
],
},
],
},
{
name: 'lastLoggedInTenant',
type: 'relationship',
relationTo: 'tenants',
index: true,
access: {
create: () => false,
read: tenantAdmins,
update: () => false,
},
},
],
}

View File

@@ -0,0 +1,23 @@
import type { User } from '../../../payload-types'
export const checkTenantRoles = (
allRoles: User['tenants'][0]['roles'] = [],
user: User = undefined,
tenant: User['tenants'][0]['tenant'] = undefined,
): boolean => {
if (tenant) {
const id = typeof tenant === 'string' ? tenant : tenant?.id
if (
allRoles.some(role => {
return user?.tenants?.some(({ tenant: userTenant, roles }) => {
const tenantID = typeof userTenant === 'string' ? userTenant : userTenant?.id
return tenantID === id && roles?.includes(role)
})
})
)
return true
}
return false
}

View File

@@ -0,0 +1,70 @@
import type { PayloadRequest } from 'payload/dist/types'
import { isSuperAdmin } from '../../utilities/isSuperAdmin'
const logs = false
export const isSuperOrTenantAdmin = async (args: { req: PayloadRequest }): Promise<boolean> => {
const {
req,
req: { user, payload },
} = args
// always allow super admins through
if (isSuperAdmin(user)) {
return true
}
if (logs) {
const msg = `Finding tenant with host: '${req.headers.host}'`
payload.logger.info({ msg })
}
// read `req.headers.host`, lookup the tenant by `domain` to ensure it exists, and check if the user is an admin of that tenant
const foundTenants = await payload.find({
collection: 'tenants',
where: {
'domains.domain': {
in: [req.headers.host],
},
},
depth: 0,
limit: 1,
})
// if this tenant does not exist, deny access
if (foundTenants.totalDocs === 0) {
if (logs) {
const msg = `No tenant found for ${req.headers.host}`
payload.logger.info({ msg })
}
return false
}
if (logs) {
const msg = `Found tenant: '${foundTenants.docs?.[0]?.name}', checking if user is an tenant admin`
payload.logger.info({ msg })
}
// finally check if the user is an admin of this tenant
const tenantWithUser = user?.tenants?.find(
({ tenant: userTenant }) => userTenant?.id === foundTenants.docs[0].id,
)
if (tenantWithUser?.roles?.some(role => role === 'admin')) {
if (logs) {
const msg = `User is an admin of ${foundTenants.docs[0].name}, allowing access`
payload.logger.info({ msg })
}
return true
}
if (logs) {
const msg = `User is not an admin of ${foundTenants.docs[0].name}, denying access`
payload.logger.info({ msg })
}
return false
}

View File

@@ -0,0 +1,3 @@
import type { Access } from 'payload/config'
export const anyone: Access = () => true

View File

@@ -0,0 +1,9 @@
import type { Access } from 'payload/config'
import type { FieldHook } from 'payload/types'
import { checkUserRoles } from '../utilities/checkUserRoles'
export const superAdmins: Access = ({ req: { user } }) => checkUserRoles(['super-admin'], user)
export const superAdminFieldAccess: FieldHook = ({ req: { user } }) =>
checkUserRoles(['super-admin'], user)

View File

@@ -0,0 +1,145 @@
import type { Field } from 'payload/types'
import deepMerge from '../utilities/deepMerge'
export const appearanceOptions = {
primary: {
label: 'Primary Button',
value: 'primary',
},
secondary: {
label: 'Secondary Button',
value: 'secondary',
},
default: {
label: 'Default',
value: 'default',
},
}
export type LinkAppearances = 'primary' | 'secondary' | 'default'
type LinkType = (options?: {
appearances?: LinkAppearances[] | false
disableLabel?: boolean
overrides?: Record<string, unknown>
}) => Field
const link: LinkType = ({ appearances, disableLabel = false, overrides = {} } = {}) => {
const linkResult: Field = {
name: 'link',
type: 'group',
admin: {
hideGutter: true,
},
fields: [
{
type: 'row',
fields: [
{
name: 'type',
type: 'radio',
options: [
{
label: 'Internal link',
value: 'reference',
},
{
label: 'Custom URL',
value: 'custom',
},
],
defaultValue: 'reference',
admin: {
layout: 'horizontal',
width: '50%',
},
},
{
name: 'newTab',
label: 'Open in new tab',
type: 'checkbox',
admin: {
width: '50%',
style: {
alignSelf: 'flex-end',
},
},
},
],
},
],
}
const linkTypes: Field[] = [
{
name: 'reference',
label: 'Document to link to',
type: 'relationship',
relationTo: ['pages'],
required: true,
maxDepth: 1,
admin: {
condition: (_, siblingData) => siblingData?.type === 'reference',
},
},
{
name: 'url',
label: 'Custom URL',
type: 'text',
required: true,
admin: {
condition: (_, siblingData) => siblingData?.type === 'custom',
},
},
]
if (!disableLabel) {
linkTypes[0].admin.width = '50%'
linkTypes[1].admin.width = '50%'
linkResult.fields.push({
type: 'row',
fields: [
...linkTypes,
{
name: 'label',
label: 'Label',
type: 'text',
required: true,
admin: {
width: '50%',
},
},
],
})
} else {
linkResult.fields = [...linkResult.fields, ...linkTypes]
}
if (appearances !== false) {
let appearanceOptionsToUse = [
appearanceOptions.default,
appearanceOptions.primary,
appearanceOptions.secondary,
]
if (appearances) {
appearanceOptionsToUse = appearances.map(appearance => appearanceOptions[appearance])
}
linkResult.fields.push({
name: 'appearance',
type: 'select',
defaultValue: 'default',
options: appearanceOptionsToUse,
admin: {
description: 'Choose how the link should be rendered.',
},
})
}
return deepMerge(linkResult, overrides)
}
export default link

View File

@@ -0,0 +1,5 @@
import type { RichTextElement } from 'payload/dist/fields/config/types'
const elements: RichTextElement[] = ['blockquote', 'h2', 'h3', 'h4', 'h5', 'h6', 'link']
export default elements

View File

@@ -0,0 +1,86 @@
import type { RichTextElement, RichTextField, RichTextLeaf } from 'payload/dist/fields/config/types'
import deepMerge from '../../utilities/deepMerge'
import link from '../link'
import elements from './elements'
import leaves from './leaves'
type RichText = (
overrides?: Partial<RichTextField>,
additions?: {
elements?: RichTextElement[]
leaves?: RichTextLeaf[]
},
) => RichTextField
const richText: RichText = (
overrides,
additions = {
elements: [],
leaves: [],
},
) =>
deepMerge<RichTextField, Partial<RichTextField>>(
{
name: 'richText',
type: 'richText',
required: true,
admin: {
upload: {
collections: {
media: {
fields: [
{
type: 'richText',
name: 'caption',
label: 'Caption',
admin: {
elements: [...elements],
leaves: [...leaves],
},
},
{
type: 'radio',
name: 'alignment',
label: 'Alignment',
options: [
{
label: 'Left',
value: 'left',
},
{
label: 'Center',
value: 'center',
},
{
label: 'Right',
value: 'right',
},
],
},
{
name: 'enableLink',
type: 'checkbox',
label: 'Enable Link',
},
link({
appearances: false,
disableLabel: true,
overrides: {
admin: {
condition: (_, data) => Boolean(data?.enableLink),
},
},
}),
],
},
},
},
elements: [...elements, ...(additions.elements || [])],
leaves: [...leaves, ...(additions.leaves || [])],
},
},
overrides,
)
export default richText

View File

@@ -0,0 +1,5 @@
import type { RichTextLeaf } from 'payload/dist/fields/config/types'
const defaultLeaves: RichTextLeaf[] = ['bold', 'italic', 'underline']
export default defaultLeaves

View File

@@ -0,0 +1,16 @@
import type { FieldAccess } from 'payload/types'
import { checkUserRoles } from '../../../utilities/checkUserRoles'
export const tenantAdminFieldAccess: FieldAccess = ({ req: { user }, doc }) => {
return (
checkUserRoles(['super-admin'], user) ||
!doc?.tenant ||
(doc?.tenant &&
user?.tenants?.some(
({ tenant: userTenant, roles }) =>
(typeof doc?.tenant === 'string' ? doc?.tenant : doc?.tenant.id) === userTenant?.id &&
roles?.includes('admin'),
))
)
}

View File

@@ -0,0 +1,42 @@
import type { Field } from 'payload/types'
import { superAdminFieldAccess } from '../../access/superAdmins'
import { isSuperAdmin } from '../../utilities/isSuperAdmin'
import { tenantAdminFieldAccess } from './access/tenantAdmins'
export const tenant: Field = {
name: 'tenant',
type: 'relationship',
relationTo: 'tenants',
// don't require this field because we need to auto-populate it, see below
// required: true,
// we also don't want to hide this field because super-admins may need to manage it
// to achieve this, create a custom component that conditionally renders the field based on the user's role
// hidden: true,
index: true,
admin: {
position: 'sidebar',
},
access: {
create: superAdminFieldAccess,
read: tenantAdminFieldAccess,
update: superAdminFieldAccess,
},
hooks: {
// automatically set the tenant to the last logged in tenant
// for super admins, allow them to set the tenant
beforeChange: [
async ({ req, req: { user }, data }) => {
if ((await isSuperAdmin(req.user)) && data?.tenant) {
return data.tenant
}
if (user?.lastLoggedInTenant?.id) {
return user.lastLoggedInTenant.id
}
return undefined
},
],
},
}

View File

@@ -0,0 +1,16 @@
import type { User } from '../../payload-types'
export const checkUserRoles = (allRoles: User['roles'] = [], user: User = undefined): boolean => {
if (user) {
if (
allRoles.some(role => {
return user?.roles?.some(individualRole => {
return individualRole === role
})
})
)
return true
}
return false
}

View File

@@ -0,0 +1,32 @@
/**
* Simple object check.
* @param item
* @returns {boolean}
*/
export function isObject(item: unknown): boolean {
return item && typeof item === 'object' && !Array.isArray(item)
}
/**
* Deep merge two objects.
* @param target
* @param ...sources
*/
export default function deepMerge<T, R>(target: T, source: R): T {
const output = { ...target }
if (isObject(target) && isObject(source)) {
Object.keys(source).forEach(key => {
if (isObject(source[key])) {
if (!(key in (target as Record<string, unknown>))) {
Object.assign(output, { [key]: source[key] })
} else {
output[key] = deepMerge(target[key], source[key])
}
} else {
Object.assign(output, { [key]: source[key] })
}
})
}
return output
}

View File

@@ -0,0 +1,8 @@
import type { User } from 'payload/generated-types'
import { checkUserRoles } from './checkUserRoles'
export const isSuperAdmin = (user: User): boolean => {
if (user?.email === 'dev@payloadcms.com') return true // for the seed script, remove this in production
return checkUserRoles(['super-admin'], user)
}

View File

@@ -0,0 +1,56 @@
/* tslint:disable */
/**
* This file was automatically generated by Payload CMS.
* DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,
* and re-run `payload generate:types` to regenerate this file.
*/
export interface Config {
collections: {
users: User
tenants: Tenant
pages: Page
}
globals: {}
}
export interface User {
id: string
firstName?: string
lastName?: string
roles: Array<'super-admin' | 'user'>
tenants?: Array<{
tenant: string | Tenant
roles: Array<'admin' | 'user'>
id?: string
}>
lastLoggedInTenant?: string | Tenant
updatedAt: string
createdAt: string
email?: string
resetPasswordToken?: string
resetPasswordExpiration?: string
loginAttempts?: number
lockUntil?: string
password?: string
}
export interface Tenant {
id: string
name: string
domains: Array<{
domain: string
id?: string
}>
updatedAt: string
createdAt: string
}
export interface Page {
id: string
title: string
slug?: string
tenant?: string | Tenant
richText: Array<{
[k: string]: unknown
}>
updatedAt: string
createdAt: string
}

View File

@@ -0,0 +1,19 @@
import dotenv from 'dotenv'
import path from 'path'
dotenv.config({
path: path.resolve(__dirname, '../.env'),
})
import { buildConfig } from 'payload/config'
import { Pages } from './collections/Pages'
import { Tenants } from './collections/Tenants'
import { Users } from './collections/Users'
export default buildConfig({
collections: [Users, Tenants, Pages],
typescript: {
outputFile: path.resolve(__dirname, 'payload-types.ts'),
},
})

View File

@@ -0,0 +1,119 @@
import type { Payload } from 'payload'
export const seed = async (payload: Payload): Promise<void> => {
// create super admin
await payload.create({
collection: 'users',
data: {
email: 'dev@payloadcms.com',
password: 'test',
roles: ['super-admin'],
},
})
// create tenants, use `*.localhost.com` so that accidentally forgotten changes the hosts file are acceptable
const [abc, bbc] = await Promise.all([
await payload.create({
collection: 'tenants',
data: {
name: 'ABC',
domains: [{ domain: 'abc.localhost.com:3000' }],
},
}),
await payload.create({
collection: 'tenants',
data: {
name: 'BBC',
domains: [{ domain: 'bbc.localhost.com:3000' }],
},
}),
])
// create tenant-scoped admins and users
await Promise.all([
await payload.create({
collection: 'users',
data: {
email: 'admin@abc.com',
password: 'test',
roles: ['user'],
tenants: [
{
tenant: abc.id,
roles: ['admin'],
},
],
},
}),
await payload.create({
collection: 'users',
data: {
email: 'user@abc.com',
password: 'test',
roles: ['user'],
tenants: [
{
tenant: abc.id,
roles: ['user'],
},
],
},
}),
await payload.create({
collection: 'users',
data: {
email: 'admin@bbc.com',
password: 'test',
roles: ['user'],
tenants: [
{
tenant: bbc.id,
roles: ['admin'],
},
],
},
}),
await payload.create({
collection: 'users',
data: {
email: 'user@bbc.com',
password: 'test',
roles: ['user'],
tenants: [
{
tenant: bbc.id,
roles: ['user'],
},
],
},
}),
])
// create tenant-scoped pages
await Promise.all([
await payload.create({
collection: 'pages',
data: {
tenant: abc.id,
title: 'ABC Home',
richText: [
{
text: 'Hello, ABC!',
},
],
},
}),
await payload.create({
collection: 'pages',
data: {
title: 'BBC Home',
tenant: bbc.id,
richText: [
{
text: 'Hello, BBC!',
},
],
},
}),
])
}

View File

@@ -0,0 +1,37 @@
import dotenv from 'dotenv'
import path from 'path'
dotenv.config({
path: path.resolve(__dirname, '../.env'),
})
import express from 'express'
import payload from 'payload'
import { seed } from './seed'
const app = express()
app.get('/', (_, res) => {
res.redirect('/admin')
})
const start = async (): Promise<void> => {
await payload.init({
secret: process.env.PAYLOAD_SECRET,
mongoURL: process.env.MONGODB_URI,
express: app,
onInit: () => {
payload.logger.info(`Payload Admin URL: ${payload.getAdminURL()}`)
},
})
if (process.env.PAYLOAD_SEED === 'true') {
payload.logger.info('---- SEEDING DATABASE ----')
await seed(payload)
}
app.listen(3000)
}
start()

View File

@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"strict": false,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./src",
"jsx": "react",
"sourceMap": true,
"resolveJsonModule": true,
"paths": {
"payload/generated-types": ["./src/payload-types.ts"],
"node_modules/*": ["./node_modules/*"]
},
},
"include": [
"src"
],
"exclude": [
"node_modules",
"dist",
"build",
],
"ts-node": {
"transpileOnly": true
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -149,6 +149,7 @@
"passport-local": "^1.0.0",
"passport-local-mongoose": "^7.1.2",
"path-browserify": "^1.0.1",
"payload": "^1.8.2",
"pino": "^6.4.1",
"pino-pretty": "^9.1.1",
"pluralize": "^8.0.0",

115
yarn.lock
View File

@@ -9164,6 +9164,121 @@ pause@0.0.1:
resolved "https://registry.yarnpkg.com/pause/-/pause-0.0.1.tgz#1d408b3fdb76923b9543d96fb4c9dfd535d9cb5d"
integrity sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg==
payload@^1.8.2:
version "1.8.2"
resolved "https://registry.yarnpkg.com/payload/-/payload-1.8.2.tgz#94edff09f1580aa6dc28b41210244229303e1435"
integrity sha512-Bk7nDGdaQAhMIX7J9S+FkbLoZ+PNVrmwAg84RAj9Q7JyBeHHmJyDSTaGVenzXjWpch5bbMEd9nNdezpSalmZeg==
dependencies:
"@date-io/date-fns" "^2.16.0"
"@dnd-kit/core" "^6.0.7"
"@dnd-kit/sortable" "^7.0.2"
"@faceless-ui/modal" "^2.0.1"
"@faceless-ui/scroll-info" "^1.3.0"
"@faceless-ui/window-info" "^2.1.1"
"@monaco-editor/react" "^4.4.6"
"@swc/core" "^1.3.26"
"@swc/register" "^0.1.10"
"@types/sharp" "^0.31.1"
body-parser "^1.20.1"
bson-objectid "^2.0.4"
compression "^1.7.4"
conf "^10.2.0"
connect-history-api-fallback "^1.6.0"
css-loader "^5.2.7"
css-minimizer-webpack-plugin "^3.4.1"
dataloader "^2.1.0"
date-fns "^2.29.3"
deep-equal "^2.2.0"
deepmerge "^4.2.2"
dotenv "^8.6.0"
express "^4.18.2"
express-fileupload "1.4.0"
express-rate-limit "^5.5.1"
file-loader "^6.2.0"
file-type "16.5.4"
find-up "4.1.0"
flatley "^5.2.0"
fs-extra "^10.1.0"
get-tsconfig "^4.4.0"
graphql "^16.6.0"
graphql-http "^1.17.1"
graphql-playground-middleware-express "^1.7.23"
graphql-query-complexity "^0.12.0"
graphql-scalars "^1.20.1"
graphql-type-json "^0.3.2"
html-webpack-plugin "^5.5.0"
http-status "^1.6.2"
i18next "^22.4.9"
i18next-browser-languagedetector "^6.1.8"
i18next-http-middleware "^3.2.2"
is-hotkey "^0.2.0"
is-plain-object "^5.0.0"
isomorphic-fetch "^3.0.0"
joi "^17.7.0"
json-schema-to-typescript "11.0.3"
jsonwebtoken "^9.0.0"
jwt-decode "^3.1.2"
md5 "^2.3.0"
method-override "^3.0.0"
micro-memoize "^4.0.14"
mini-css-extract-plugin "1.6.2"
minimist "^1.2.7"
mkdirp "^1.0.4"
mongoose "6.5.0"
mongoose-aggregate-paginate-v2 "^1.0.6"
mongoose-paginate-v2 "^1.6.1"
nodemailer "^6.9.0"
object-to-formdata "^4.4.2"
passport "^0.6.0"
passport-anonymous "^1.0.1"
passport-headerapikey "^1.2.2"
passport-jwt "^4.0.1"
passport-local "^1.0.0"
passport-local-mongoose "^7.1.2"
path-browserify "^1.0.1"
pino "^6.4.1"
pino-pretty "^9.1.1"
pluralize "^8.0.0"
postcss "^8.4.21"
postcss-loader "^6.2.1"
postcss-preset-env "^7.8.3"
probe-image-size "^6.0.0"
process "^0.11.10"
qs "^6.11.0"
qs-middleware "^1.0.3"
react "^18.2.0"
react-animate-height "^2.1.2"
react-datepicker "^4.10.0"
react-diff-viewer "^3.1.1"
react-dom "^18.2.0"
react-helmet "^6.1.0"
react-i18next "^11.18.6"
react-router-dom "^5.3.4"
react-router-navigation-prompt "^1.9.6"
react-select "^3.2.0"
react-toastify "^8.2.0"
sanitize-filename "^1.6.3"
sass "^1.57.1"
sass-loader "^12.6.0"
sharp "^0.31.3"
slate "^0.91.4"
slate-history "^0.86.0"
slate-hyperscript "^0.81.3"
slate-react "^0.92.0"
style-loader "^2.0.0"
swc-loader "^0.2.3"
swc-minify-webpack-plugin "^2.1.0"
terser-webpack-plugin "^5.3.6"
ts-essentials "^7.0.3"
url-loader "^4.1.1"
use-context-selector "^1.4.1"
uuid "^8.3.2"
webpack "^5.78.0"
webpack-bundle-analyzer "^4.8.0"
webpack-cli "^4.10.0"
webpack-dev-middleware "6.0.1"
webpack-hot-middleware "^2.25.3"
peek-readable@^4.1.0:
version "4.1.0"
resolved "https://registry.yarnpkg.com/peek-readable/-/peek-readable-4.1.0.tgz#4ece1111bf5c2ad8867c314c81356847e8a62e72"