Merge claude/read-published-versions-fix: readPublished on version history, readPublishedVersions, the documented form works
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+18
-2
@@ -195,10 +195,26 @@ access: { update: requireRole('editor') }
|
||||
// a collection with drafts: editors (or the role you name) read everything; visitors, plain `user` accounts and a
|
||||
// session that still owes its second factor read published documents only — by id, in lists, with ?draft=true and
|
||||
// over GraphQL. Payload's open `read: () => true` answers ?draft=true with the draft itself (1.17.1).
|
||||
access: { read: readPublished(), readVersions: readPublished() }
|
||||
access: { read: readPublished('admin') }
|
||||
// Version history asks for the status at another path: readPublishedVersions() goes on readVersions (1.17.2).
|
||||
access: { read: readPublished(), readVersions: readPublishedVersions() }
|
||||
access: { read: readPublished('admin'), readVersions: readPublishedVersions('admin') }
|
||||
```
|
||||
|
||||
**Where each rule may be used.**
|
||||
|
||||
| Rule | Where | What a visitor gets |
|
||||
|---|---|---|
|
||||
| `readPublished()` | `access.read` of a collection or global with `versions: { drafts: true }` | published documents: by id, lists, `?draft=true`, GraphQL |
|
||||
| `readPublishedVersions()` | `access.readVersions` of the same collection or global | published versions: the version list, one version by id (a draft one: `403`), the count, GraphQL, the panel's version view |
|
||||
|
||||
The two answer with different paths: a document has `_status`, a version has `version._status`. In 1.17.1,
|
||||
`readVersions: readPublished()` (the form these docs showed) answered every version read with **500** on MongoDB,
|
||||
Postgres and SQLite. Since 1.17.2, iapl() swaps a `readPublished()` it finds on `readVersions` of a collection or
|
||||
global for `readPublishedVersions()` with the same role, so that form works too. A collection added by a plugin
|
||||
listed **after** iapl() is not seen: use `readPublishedVersions()` there, or `withVersionReadRules(collections)`.
|
||||
Neither rule belongs on a collection without drafts (no `_status`: every read would fail). Check: without a session,
|
||||
`GET /api/<slug>/versions?limit=10` → `200` with published versions only, never `500`.
|
||||
|
||||
A role name the plugin does not know (`requireRole('Admin')`, `readPublished('superadmin')`) throws where the rule
|
||||
is written; `hasMinimumRole` / `userMeetsRole` answer `false` for it (before 1.17.1 every staff account met it).
|
||||
`readPublished` with `?draft=true` on a page whose newest version is a draft answers a visitor `404` (Payload applies
|
||||
|
||||
+1
-1
@@ -1103,7 +1103,7 @@ project → **plugin gap**, not a copy.
|
||||
| ISR after save, old slug → 308, images across languages | `buildRevalidateHook`, `trackSlugHistoryHook`, `buildCrossLocaleFieldSync` | hooks.md |
|
||||
| ISR after a global is saved | plugin globals: `iapl({ revalidatePath })`; your own globals: `buildGlobalRevalidateHook({ revalidatePath })` | hooks.md |
|
||||
| Change a plugin global (access, hooks, fields) | `iapl({ globalOverrides })` | access.md |
|
||||
| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); a collection with drafts: `access: { read: readPublished(), readVersions: readPublished() }` (editors read drafts, everybody else published only — Payload's open `read: () => true` answers `?draft=true` with the draft; verify: `GET /api/<slug>/<draft id>?draft=true` without a session → 404); an unknown role name throws where the rule is written; staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection; in a client component `isAdmin(user, config)` with `useConfig()`, imported from **`@intecion/ipal-kit/client`** (the main entry does not build there with webpack), in middleware `isAdmin(user, { staffCollections: ['users'] })` — without the last argument there it is always `false`), `staffCollectionSlugs(payload)`, `access.staffCollections`; second factor in your own code: `secondFactorPassed(req)`, `requireSecondFactor(access)`; injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md, security.md |
|
||||
| Roles and access | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `adminOrSelfIn(slug)` (several auth collections), `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`); a collection or global with drafts: `access: { read: readPublished(), readVersions: readPublishedVersions() }` (editors read drafts and every version, everybody else published only — Payload's open `read: () => true` answers `?draft=true` with the draft; `readPublished` is for `read` only, `readPublishedVersions` for `readVersions` only — `readVersions: readPublished()` answered 500 in 1.17.1 and is swapped for you since 1.17.2 on entities iapl() sees, `withVersionReadRules(entities)` for a plugin listed after it, `READ_PUBLISHED` marks the rule; neither on a collection without drafts; verify: without a session `GET /api/<slug>/<draft id>?draft=true` → 404 and `GET /api/<slug>/versions?limit=10` → 200, published only); an unknown role name throws where the rule is written; staff checks: `userMeetsRole(req, role)`, `isAdmin(req.user, req.payload)` (roles count only for accounts of a staff collection; in a client component `isAdmin(user, config)` with `useConfig()`, imported from **`@intecion/ipal-kit/client`** (the main entry does not build there with webpack), in middleware `isAdmin(user, { staffCollections: ['users'] })` — without the last argument there it is always `false`), `staffCollectionSlugs(payload)`, `access.staffCollections`; second factor in your own code: `secondFactorPassed(req)`, `requireSecondFactor(access)`; injected `users`: `access.authAccess`, first user = admin (`access.firstUserAdmin`) | access.md, security.md |
|
||||
| Data from globals | `getGlobal`, `getSiteSettings`, `getSiteIntegrations` | payload-helpers.md |
|
||||
|
||||
**Links and navigation**
|
||||
|
||||
@@ -78,7 +78,8 @@ names, env, admin, AGENTS.md, skills, seeds and — with `--url` / `--deep` —
|
||||
|
||||
- **Drafts and locales over the API** (a collection with `versions: { drafts: true }`): without a session,
|
||||
`curl -s "$U/api/<slug>?draft=true&limit=100" | grep -c '"_status":"draft"'` → `0`, else ERROR: give it
|
||||
`access: { read: readPublished(), readVersions: readPublished() }` (access.md). `curl -sI "$U/md/xx"` → `404`
|
||||
`access: { read: readPublished(), readVersions: readPublishedVersions() }` (access.md). `curl -s -o /dev/null -w '%{http_code}' "$U/api/<slug>/versions?limit=10"`
|
||||
→ `200` (a `500` = a rule with the document's `_status` path on `readVersions`: ERROR). `curl -sI "$U/md/xx"` → `404`
|
||||
(no stand-in locale); a 404 page assigned in System pages must be published.
|
||||
- **Secrets out of queries** (as an admin, with versions on for Site integrations or a collection using
|
||||
`writeOnlySecret`): `curl -s -H "Authorization: JWT $T" "$U/api/globals/site-integrations/versions?where[version.smtpPassword][exists]=true"`
|
||||
|
||||
@@ -46,9 +46,11 @@ Ask only when the brief leaves a business question open (e.g. "do posts have aut
|
||||
**No URL prefix in code** — the editor assigns the archive page in
|
||||
Site settings (`<slug>Archive`). The plugin handles routing, sitemap,
|
||||
generateStaticParams, hreflang.
|
||||
**With drafts** (`versions: { drafts: true }`): `access: { read: readPublished(), readVersions: readPublished() }`
|
||||
**With drafts** (`versions: { drafts: true }`): `access: { read: readPublished(), readVersions: readPublishedVersions() }`
|
||||
(`readPublished` is for `read`, `readPublishedVersions` for `readVersions` — the version list asks for `version._status`)
|
||||
— Payload's open `read: () => true` answers `?draft=true` with the draft over REST and GraphQL. Check:
|
||||
`curl -i <site>/api/<slug>/<draft id>?draft=true` without a session → `404`; the same with an editor's token → the draft.
|
||||
`curl -i <site>/api/<slug>/<draft id>?draft=true` without a session → `404`; the same with an editor's token → the draft;
|
||||
`curl -s -o /dev/null -w '%{http_code}' <site>/api/<slug>/versions?limit=10` without a session → `200`, never `500`.
|
||||
3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses
|
||||
`resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article).
|
||||
4. **An auth collection for visitors** (`auth: true`: customers, members) only when the client requires it
|
||||
|
||||
@@ -15,12 +15,15 @@ export {
|
||||
injectRoles,
|
||||
isAdmin,
|
||||
isEditor,
|
||||
READ_PUBLISHED,
|
||||
readPublished,
|
||||
readPublishedVersions,
|
||||
requireRole,
|
||||
requireRoleField,
|
||||
ROLE_HIERARCHY,
|
||||
staffCollectionSlugs,
|
||||
userMeetsRole,
|
||||
withVersionReadRules,
|
||||
} from './modules/access/index.js'
|
||||
export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js'
|
||||
export { applyPasswordRule, buildPasswordRuleHook, checkPassword, DEFAULT_PASSWORD_MIN_LENGTH, resolvePasswordRule } from './modules/access/passwordRule.js'
|
||||
|
||||
@@ -21,17 +21,51 @@ export const requireRole = (minimum: Role): Access => {
|
||||
return ({ req }) => hasMinimumRole(req.user, minimum, req.payload)
|
||||
}
|
||||
|
||||
/** Marks a `readPublished()` rule, so the plugin can give `readVersions` the version form of it (a symbol, not a name). */
|
||||
export const READ_PUBLISHED = Symbol.for('iapl.readPublished')
|
||||
|
||||
/**
|
||||
* Read rule for a collection with drafts: staff of `minimum` role or higher (default editor) read everything,
|
||||
* drafts and versions included; everybody else (visitors, plain `user` accounts, a session that still owes its
|
||||
* Read rule for a collection (or a global) with drafts: staff of `minimum` role or higher (default editor) read
|
||||
* everything, drafts included; everybody else (visitors, plain `user` accounts, a session that still owes its
|
||||
* second factor) reads published documents only — by id, in lists, with `?draft=true` and over GraphQL. Payload's
|
||||
* open `read: () => true` answers `?draft=true` with the draft itself (IAWL idea 23).
|
||||
*
|
||||
* access: { read: readPublished(), readVersions: readPublished() }
|
||||
* For `read`. Version history (`readVersions`) asks for the status at another path (`version._status`): use
|
||||
* `readPublishedVersions()` there. Given to `readVersions` of a collection or global that iapl() sees, this rule
|
||||
* is swapped for `readPublishedVersions()` with the same role (1.17.2; in 1.17.1 it answered 500 there).
|
||||
*
|
||||
* access: { read: readPublished(), readVersions: readPublishedVersions() }
|
||||
*/
|
||||
export const readPublished = (minimum: Role = 'editor'): Access => {
|
||||
assertKnownRole('readPublished', minimum)
|
||||
return ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { _status: { equals: 'published' } })
|
||||
const rule: Access = ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { _status: { equals: 'published' } })
|
||||
return Object.assign(rule, { [READ_PUBLISHED]: minimum })
|
||||
}
|
||||
|
||||
/**
|
||||
* The version-history form of `readPublished()`, for `readVersions`: staff of `minimum` role or higher read every
|
||||
* version; everybody else reads published versions only — the list, one version by id, the count, REST, GraphQL,
|
||||
* the Local API with access control. A version query runs on the versions collection, where the status is
|
||||
* `version._status` (a `_status` condition there is an unknown path: 500 on every database adapter).
|
||||
*/
|
||||
export const readPublishedVersions = (minimum: Role = 'editor'): Access => {
|
||||
assertKnownRole('readPublishedVersions', minimum)
|
||||
return ({ req }) => (hasMinimumRole(req.user, minimum, req.payload) ? true : { 'version._status': { equals: 'published' } })
|
||||
}
|
||||
|
||||
type WithAccess = { access?: { readVersions?: unknown } }
|
||||
|
||||
/**
|
||||
* Gives every `readVersions: readPublished()` the version form (`readPublishedVersions()` with the same role).
|
||||
* iapl() runs it on the collections and globals it sees; a plugin listed after iapl() uses
|
||||
* `readPublishedVersions()` itself, or runs this on its own entities.
|
||||
*/
|
||||
export function withVersionReadRules<T extends WithAccess>(entities: T[] | undefined): T[] | undefined {
|
||||
return entities?.map((entity) => {
|
||||
const rule = entity.access?.readVersions as (object & Partial<Record<typeof READ_PUBLISHED, Role>>) | undefined
|
||||
const minimum = rule && typeof rule === 'function' ? rule[READ_PUBLISHED] : undefined
|
||||
return minimum ? { ...entity, access: { ...entity.access, readVersions: readPublishedVersions(minimum) } } : entity
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,9 +6,12 @@ export {
|
||||
adminOrSelf,
|
||||
adminOrSelfIn,
|
||||
authenticated,
|
||||
READ_PUBLISHED,
|
||||
readPublished,
|
||||
readPublishedVersions,
|
||||
requireRole,
|
||||
requireRoleField,
|
||||
withVersionReadRules,
|
||||
} from './access.js'
|
||||
export { injectRoles } from './injectRoles.js'
|
||||
export { clearStaffRegistry, hasMinimumRole, isAdmin, isEditor, registerStaffCollections, staffCollectionSlugs, userMeetsRole } from './predicates.js'
|
||||
|
||||
+5
-1
@@ -12,7 +12,7 @@ import { buildNotifications } from './globals/Notifications/index.js'
|
||||
import { applyGlobalOverrides } from './globals/overrides.js'
|
||||
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
|
||||
import { buildSiteSettings } from './globals/SiteSettings/index.js'
|
||||
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
|
||||
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs, withVersionReadRules } from './modules/access/index.js'
|
||||
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
|
||||
import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js'
|
||||
import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, markStaffRules, staffCollectionsNobodyManages, unknownStaffCollections } from './modules/access/selfRegistration.js'
|
||||
@@ -1093,6 +1093,10 @@ export const iapl = (options: IaplOptions): Plugin => {
|
||||
payload.logger.info('[iapl] Plugin initialized.')
|
||||
}
|
||||
|
||||
// readVersions: readPublished() asks for `version._status` on version history (readPublishedVersions).
|
||||
config.collections = withVersionReadRules(config.collections)
|
||||
config.globals = withVersionReadRules(config.globals)
|
||||
|
||||
// Every auth collection of this config has been seen: what appears later is a late one (adoptConfig).
|
||||
if (accounts) {
|
||||
const panel = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
|
||||
|
||||
@@ -140,7 +140,11 @@ describe('idea 23: drafts over REST and GraphQL', () => {
|
||||
expect(asked.status).toBe(404)
|
||||
expect(await asked.text()).not.toContain('szkic')
|
||||
// the version list: a visitor sees published versions only
|
||||
expect(await (await api('/guarded-pages/versions?limit=50')).text()).not.toContain('szkic')
|
||||
const versions = await api('/guarded-pages/versions?limit=50&locale=pl')
|
||||
expect(versions.status).toBe(200) // 1.17.1 answered 500 here: the check below alone passed on an error page
|
||||
const list = await versions.text()
|
||||
expect(list).toContain('Cennik')
|
||||
expect(list).not.toContain('szkic')
|
||||
})
|
||||
|
||||
test('readPublished(): an editor still sees the draft', async () => {
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* readPublished() on version history (`readVersions`) — reported by a client project upgrading to 1.17.1:
|
||||
* `GET /api/pages/versions` answered 500 on MongoDB. The rule answered `{ _status: { equals: 'published' } }`, a path
|
||||
* of the document, while a version query runs on the versions collection, where the status is `version._status`.
|
||||
*
|
||||
* Every way a version is read, for a visitor, a plain `user` account and an editor: the list (REST, Local API,
|
||||
* GraphQL, `depth`), one version by id (REST, GraphQL — the panel's version view reads it the same way), the count.
|
||||
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { READ_PUBLISHED, readPublished, readPublishedVersions, withVersionReadRules } from '../src/modules/access/access.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { startPayloadServer, type TestServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
const tokens: Record<'editor' | 'user', string> = { editor: '', user: '' }
|
||||
let pageId: number | string
|
||||
let neverPublishedId: number | string
|
||||
const versionIds: { draft: (number | string)[]; published: (number | string)[] } = { draft: [], published: [] }
|
||||
|
||||
type Who = 'editor' | 'user' | 'visitor'
|
||||
const headers = (who: Who) => ({ 'content-type': 'application/json', ...(who === 'visitor' ? {} : { authorization: `JWT ${tokens[who]}` }) })
|
||||
const rest = async (pathname: string, who: Who) => {
|
||||
const res = await fetch(`${server.url}/api${pathname}`, { headers: headers(who) })
|
||||
return { body: await res.text(), status: res.status }
|
||||
}
|
||||
const gql = async (query: string, who: Who) => {
|
||||
const res = await fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: headers(who), method: 'POST' })
|
||||
return { body: await res.text(), status: res.status }
|
||||
}
|
||||
const titles = (body: string) => [...body.matchAll(/"title":"([^"]+)"/g)].map((m) => m[1])
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [
|
||||
{
|
||||
slug: 'pages',
|
||||
access: { read: readPublished(), readVersions: readPublished() },
|
||||
fields: [{ name: 'title', type: 'text', localized: true }, { name: 'related', type: 'relationship', relationTo: 'pages' }],
|
||||
versions: { drafts: true, maxPerDoc: 20 },
|
||||
},
|
||||
// the explicit version rule, and a role other than the default
|
||||
{ slug: 'notes', access: { read: readPublished('admin'), readVersions: readPublishedVersions('admin') }, fields: [{ name: 'title', type: 'text' }], versions: { drafts: true } },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-read-published-versions') } },
|
||||
],
|
||||
db: testDatabase('read_published_versions'),
|
||||
editor: lexicalEditor(),
|
||||
globals: [{ slug: 'banner', access: { read: readPublished(), readVersions: readPublished() }, fields: [{ name: 'title', type: 'text' }], versions: { drafts: true } }],
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })],
|
||||
secret: 'read-published-versions-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config)
|
||||
for (const role of ['editor', 'user'] as const) {
|
||||
await payload.create({ collection: 'users' as never, data: { email: `${role}@example.com`, password: PASSWORD, roles: [role] } as never })
|
||||
tokens[role] = ((await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: `${role}@example.com`, password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }).token
|
||||
}
|
||||
await payload.create({ collection: 'notes' as never, data: { _status: 'published', title: 'Note published' } as never })
|
||||
await payload.create({ collection: 'notes' as never, data: { _status: 'draft', title: 'Note draft' } as never, draft: true })
|
||||
await payload.updateGlobal({ slug: 'banner' as never, data: { _status: 'published', title: 'Banner published' } as never })
|
||||
await payload.updateGlobal({ slug: 'banner' as never, data: { _status: 'draft', title: 'Banner draft' } as never, draft: true })
|
||||
pageId = (await payload.create({ collection: 'pages' as never, data: { _status: 'published', title: 'Published one' } as never, locale: 'pl' })).id
|
||||
await payload.update({ id: pageId, collection: 'pages' as never, data: { _status: 'draft', title: 'Draft over it' } as never, draft: true, locale: 'pl' })
|
||||
neverPublishedId = (await payload.create({ collection: 'pages' as never, data: { _status: 'draft', related: pageId, title: 'Never published' } as never, draft: true, locale: 'pl' })).id
|
||||
const all = await payload.findVersions({ collection: 'pages' as never, depth: 0, limit: 100, locale: 'pl' })
|
||||
for (const v of all.docs as unknown as { id: number | string; version: { _status?: string } }[]) {
|
||||
versionIds[v.version._status === 'published' ? 'published' : 'draft'].push(v.id)
|
||||
}
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
describe('readPublished() as readVersions', () => {
|
||||
test.each(['visitor', 'user'] as const)('the version list answers a %s with published versions only (REST, depth 0 and 2)', async (who) => {
|
||||
for (const q of ['?limit=100&depth=0', '?limit=100&depth=2&locale=pl']) {
|
||||
const { body, status } = await rest(`/pages/versions${q}`, who)
|
||||
expect(status).toBe(200)
|
||||
expect(titles(body)).toContain('Published one')
|
||||
expect(body).not.toContain('Draft over it')
|
||||
expect(body).not.toContain('Never published')
|
||||
}
|
||||
})
|
||||
|
||||
test('an editor lists every version', async () => {
|
||||
const { body, status } = await rest('/pages/versions?limit=100&depth=0&locale=pl', 'editor')
|
||||
expect(status).toBe(200)
|
||||
expect(titles(body)).toEqual(expect.arrayContaining(['Published one', 'Draft over it', 'Never published']))
|
||||
})
|
||||
|
||||
test('one version by id: a published one is answered, a draft one is not found (REST)', async () => {
|
||||
expect((await rest(`/pages/versions/${versionIds.published[0]}?locale=pl`, 'visitor')).status).toBe(200)
|
||||
for (const id of versionIds.draft) {
|
||||
const { body, status } = await rest(`/pages/versions/${id}?locale=pl`, 'visitor')
|
||||
expect([403, 404]).toContain(status) // Payload refuses a version the rule's condition leaves out
|
||||
expect(body).not.toMatch(/Draft over it|Never published/)
|
||||
}
|
||||
expect((await rest(`/pages/versions/${versionIds.draft[0]}?locale=pl`, 'editor')).status).toBe(200)
|
||||
})
|
||||
|
||||
test('GraphQL: the list and one version, as a visitor', async () => {
|
||||
const list = await gql('{ versionsPages(limit: 100, locale: pl) { totalDocs docs { id version { title _status } } } }', 'visitor')
|
||||
expect(list.status).toBe(200)
|
||||
expect(list.body).not.toContain('"errors"')
|
||||
expect(list.body).toContain('Published one')
|
||||
expect(list.body).not.toMatch(/Draft over it|Never published/)
|
||||
const draft = await gql(`{ versionPage(id: "${versionIds.draft[0]}", locale: pl) { version { title } } }`, 'visitor')
|
||||
expect(draft.body).not.toMatch(/Draft over it|Never published/)
|
||||
})
|
||||
|
||||
test('Local API with access control: findVersions and countVersions as a visitor', async () => {
|
||||
const found = await payload.findVersions({ collection: 'pages' as never, depth: 0, limit: 100, locale: 'pl', overrideAccess: false })
|
||||
expect((found.docs as unknown as { version: { title?: string } }[]).map((d) => d.version.title)).toEqual(['Published one'])
|
||||
const counted = await payload.countVersions({ collection: 'pages' as never, overrideAccess: false })
|
||||
expect(counted.totalDocs).toBe(versionIds.published.length)
|
||||
})
|
||||
|
||||
test('reading the documents still works as before (read: readPublished())', async () => {
|
||||
expect((await rest(`/pages/${neverPublishedId}`, 'visitor')).status).toBe(404)
|
||||
expect(titles((await rest(`/pages/${pageId}?locale=pl`, 'visitor')).body)).toContain('Published one')
|
||||
expect(titles((await rest(`/pages/${pageId}?draft=true&locale=pl`, 'editor')).body)).toContain('Draft over it')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the other ways in', () => {
|
||||
test('readPublishedVersions(), with its own role: an editor is a visitor when the role is admin', async () => {
|
||||
for (const who of ['visitor', 'editor'] as const) {
|
||||
const { body, status } = await rest('/notes/versions?limit=50', who)
|
||||
expect(status).toBe(200)
|
||||
expect(body).toContain('Note published')
|
||||
expect(body).not.toContain('Note draft')
|
||||
}
|
||||
})
|
||||
|
||||
test('a global: readVersions: readPublished() lists published versions only', async () => {
|
||||
const { body, status } = await rest('/globals/banner/versions?limit=50', 'visitor')
|
||||
expect(status).toBe(200)
|
||||
expect(body).toContain('Banner published')
|
||||
expect(body).not.toContain('Banner draft')
|
||||
expect((await rest('/globals/banner/versions?limit=50', 'editor')).body).toContain('Banner draft')
|
||||
})
|
||||
|
||||
test('withVersionReadRules swaps only a readPublished() rule, keeping its role (a plugin listed after iapl)', () => {
|
||||
const own = () => true
|
||||
const [swapped, kept, none] = withVersionReadRules([
|
||||
{ slug: 'late', access: { readVersions: readPublished('admin') } },
|
||||
{ slug: 'mine', access: { readVersions: own } },
|
||||
{ slug: 'open' },
|
||||
] as { access?: { readVersions?: unknown }; slug: string }[])!
|
||||
const rule = swapped.access!.readVersions as (a: unknown) => unknown
|
||||
expect(READ_PUBLISHED in rule).toBe(false)
|
||||
expect(rule({ req: { payload: undefined, user: undefined } })).toEqual({ 'version._status': { equals: 'published' } })
|
||||
expect(kept.access!.readVersions).toBe(own)
|
||||
expect(none).toEqual({ slug: 'open' })
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user