@foundrykit/permissions-plugin 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,7 +29,7 @@ export default buildConfig({
29
29
  ```
30
30
 
31
31
  Run `payload generate:importmap` afterwards. The users collection must not already have `role` or
32
- `lastLoginAt` fields, and no `roles`, `permission-overrides` or `permission-audit-log` collections
32
+ `lastActiveAt` fields, and no `roles`, `permission-overrides` or `permission-audit-log` collections
33
33
  may exist.
34
34
 
35
35
  ### Areas
@@ -45,6 +45,9 @@ Each area produces permissions keyed `area.action`:
45
45
  Pass `actions` to choose the standard actions explicitly. An action left out is denied for CMS
46
46
  users. `permissions.manage` is always registered.
47
47
 
48
+ On Postgres, permission keys are stored as an enum, so adding an area or action needs a database
49
+ migration (`payload migrate:create`).
50
+
48
51
  ## How permissions resolve
49
52
 
50
53
  1. Super admin → allowed.
@@ -1,4 +1,5 @@
1
- import { getOverrides, hasPermission, OVERRIDES_SLUG } from '../access.js';
1
+ import { commitTransaction, initTransaction, killTransaction } from 'payload';
2
+ import { getOverrides, getState, hasPermission, OVERRIDES_SLUG } from '../access.js';
2
3
  import { PART_OF_CHANGE, writeAudit } from '../audit.js';
3
4
  import { MANAGE_PERMISSION } from '../registry.js';
4
5
  import { assertCanGrant, assertNotSelf } from '../rules.js';
@@ -15,35 +16,66 @@ export const RESET_PATH = '/permissions/reset/:id';
15
16
  status: 403
16
17
  });
17
18
  }
18
- const id = req.routeParams?.id;
19
+ // Look the user up so the id has the database's type (a number on Postgres, not the URL string).
20
+ const user = await req.payload.findByID({
21
+ id: req.routeParams?.id,
22
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- a union once a site generates types
23
+ collection: getState(req.payload).usersSlug,
24
+ depth: 0,
25
+ disableErrors: true,
26
+ overrideAccess: true,
27
+ req
28
+ }).catch(()=>null);
29
+ if (!user) {
30
+ return Response.json({
31
+ errors: [
32
+ {
33
+ message: 'Not Found'
34
+ }
35
+ ]
36
+ }, {
37
+ status: 404
38
+ });
39
+ }
40
+ const id = user.id;
19
41
  assertNotSelf(req, id);
20
42
  const overrides = await getOverrides(req.payload, id, req);
21
43
  // Lifting a deny can hand the permission back, which counts as granting it.
22
44
  await assertCanGrant(req, overrides.filter((o)=>o.effect === 'deny').map((o)=>o.permission));
23
45
  if (overrides.length) {
24
- await req.payload.delete({
25
- collection: OVERRIDES_SLUG,
26
- context: {
27
- [PART_OF_CHANGE]: true
28
- },
29
- overrideAccess: true,
30
- req,
31
- where: {
32
- user: {
33
- equals: id
46
+ // One transaction, so the overrides are never cleared without the audit entry.
47
+ const ownsTransaction = await initTransaction(req);
48
+ try {
49
+ await req.payload.delete({
50
+ collection: OVERRIDES_SLUG,
51
+ context: {
52
+ [PART_OF_CHANGE]: true
53
+ },
54
+ overrideAccess: true,
55
+ req,
56
+ where: {
57
+ user: {
58
+ equals: id
59
+ }
34
60
  }
61
+ });
62
+ await writeAudit(req, {
63
+ action: 'user.reset',
64
+ after: [],
65
+ before: overrides.map(({ effect, permission })=>({
66
+ effect,
67
+ permission
68
+ })),
69
+ summary: `Reset to role: ${overrides.length} override${overrides.length === 1 ? '' : 's'} cleared`,
70
+ user: id
71
+ });
72
+ if (ownsTransaction) {
73
+ await commitTransaction(req);
35
74
  }
36
- });
37
- await writeAudit(req, {
38
- action: 'user.reset',
39
- after: [],
40
- before: overrides.map(({ effect, permission })=>({
41
- effect,
42
- permission
43
- })),
44
- summary: `Reset to role: ${overrides.length} override${overrides.length === 1 ? '' : 's'} cleared`,
45
- user: id
46
- });
75
+ } catch (err) {
76
+ await killTransaction(req);
77
+ throw err;
78
+ }
47
79
  }
48
80
  return Response.json({
49
81
  removed: overrides.length
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoints/resetToRole.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\n\nimport { getOverrides, hasPermission, OVERRIDES_SLUG } from '../access.js'\nimport { PART_OF_CHANGE, writeAudit } from '../audit.js'\nimport { MANAGE_PERMISSION } from '../registry.js'\nimport { assertCanGrant, assertNotSelf } from '../rules.js'\n\nexport const RESET_PATH = '/permissions/reset/:id'\n\n/** Clears every override on a user, logged as one \"Reset to role\" entry. */\nexport const resetToRoleHandler: PayloadHandler = async (req) => {\n if (!(await hasPermission(req, MANAGE_PERMISSION))) {\n return Response.json({ errors: [{ message: 'Forbidden' }] }, { status: 403 })\n }\n const id = req.routeParams?.id as string\n assertNotSelf(req, id)\n\n const overrides = await getOverrides(req.payload, id, req)\n // Lifting a deny can hand the permission back, which counts as granting it.\n await assertCanGrant(\n req,\n overrides.filter((o) => o.effect === 'deny').map((o) => o.permission),\n )\n if (overrides.length) {\n await req.payload.delete({\n collection: OVERRIDES_SLUG,\n context: { [PART_OF_CHANGE]: true },\n overrideAccess: true,\n req,\n where: { user: { equals: id } },\n })\n await writeAudit(req, {\n action: 'user.reset',\n after: [],\n before: overrides.map(({ effect, permission }) => ({ effect, permission })),\n summary: `Reset to role: ${overrides.length} override${overrides.length === 1 ? '' : 's'} cleared`,\n user: id,\n })\n }\n return Response.json({ removed: overrides.length })\n}\n"],"names":["getOverrides","hasPermission","OVERRIDES_SLUG","PART_OF_CHANGE","writeAudit","MANAGE_PERMISSION","assertCanGrant","assertNotSelf","RESET_PATH","resetToRoleHandler","req","Response","json","errors","message","status","id","routeParams","overrides","payload","filter","o","effect","map","permission","length","delete","collection","context","overrideAccess","where","user","equals","action","after","before","summary","removed"],"mappings":"AAEA,SAASA,YAAY,EAAEC,aAAa,EAAEC,cAAc,QAAQ,eAAc;AAC1E,SAASC,cAAc,EAAEC,UAAU,QAAQ,cAAa;AACxD,SAASC,iBAAiB,QAAQ,iBAAgB;AAClD,SAASC,cAAc,EAAEC,aAAa,QAAQ,cAAa;AAE3D,OAAO,MAAMC,aAAa,yBAAwB;AAElD,0EAA0E,GAC1E,OAAO,MAAMC,qBAAqC,OAAOC;IACvD,IAAI,CAAE,MAAMT,cAAcS,KAAKL,oBAAqB;QAClD,OAAOM,SAASC,IAAI,CAAC;YAAEC,QAAQ;gBAAC;oBAAEC,SAAS;gBAAY;aAAE;QAAC,GAAG;YAAEC,QAAQ;QAAI;IAC7E;IACA,MAAMC,KAAKN,IAAIO,WAAW,EAAED;IAC5BT,cAAcG,KAAKM;IAEnB,MAAME,YAAY,MAAMlB,aAAaU,IAAIS,OAAO,EAAEH,IAAIN;IACtD,4EAA4E;IAC5E,MAAMJ,eACJI,KACAQ,UAAUE,MAAM,CAAC,CAACC,IAAMA,EAAEC,MAAM,KAAK,QAAQC,GAAG,CAAC,CAACF,IAAMA,EAAEG,UAAU;IAEtE,IAAIN,UAAUO,MAAM,EAAE;QACpB,MAAMf,IAAIS,OAAO,CAACO,MAAM,CAAC;YACvBC,YAAYzB;YACZ0B,SAAS;gBAAE,CAACzB,eAAe,EAAE;YAAK;YAClC0B,gBAAgB;YAChBnB;YACAoB,OAAO;gBAAEC,MAAM;oBAAEC,QAAQhB;gBAAG;YAAE;QAChC;QACA,MAAMZ,WAAWM,KAAK;YACpBuB,QAAQ;YACRC,OAAO,EAAE;YACTC,QAAQjB,UAAUK,GAAG,CAAC,CAAC,EAAED,MAAM,EAAEE,UAAU,EAAE,GAAM,CAAA;oBAAEF;oBAAQE;gBAAW,CAAA;YACxEY,SAAS,CAAC,eAAe,EAAElB,UAAUO,MAAM,CAAC,SAAS,EAAEP,UAAUO,MAAM,KAAK,IAAI,KAAK,IAAI,QAAQ,CAAC;YAClGM,MAAMf;QACR;IACF;IACA,OAAOL,SAASC,IAAI,CAAC;QAAEyB,SAASnB,UAAUO,MAAM;IAAC;AACnD,EAAC"}
1
+ {"version":3,"sources":["../../src/endpoints/resetToRole.ts"],"sourcesContent":["import type { CollectionSlug, PayloadHandler } from 'payload'\n\nimport { commitTransaction, initTransaction, killTransaction } from 'payload'\n\nimport { getOverrides, getState, hasPermission, OVERRIDES_SLUG } from '../access.js'\nimport { PART_OF_CHANGE, writeAudit } from '../audit.js'\nimport { MANAGE_PERMISSION } from '../registry.js'\nimport { assertCanGrant, assertNotSelf } from '../rules.js'\n\nexport const RESET_PATH = '/permissions/reset/:id'\n\n/** Clears every override on a user, logged as one \"Reset to role\" entry. */\nexport const resetToRoleHandler: PayloadHandler = async (req) => {\n if (!(await hasPermission(req, MANAGE_PERMISSION))) {\n return Response.json({ errors: [{ message: 'Forbidden' }] }, { status: 403 })\n }\n // Look the user up so the id has the database's type (a number on Postgres, not the URL string).\n const user = await req.payload\n .findByID({\n id: req.routeParams?.id as string,\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- a union once a site generates types\n collection: getState(req.payload).usersSlug as CollectionSlug,\n depth: 0,\n disableErrors: true,\n overrideAccess: true,\n req,\n })\n .catch(() => null)\n if (!user) {\n return Response.json({ errors: [{ message: 'Not Found' }] }, { status: 404 })\n }\n const id = user.id\n assertNotSelf(req, id)\n\n const overrides = await getOverrides(req.payload, id, req)\n // Lifting a deny can hand the permission back, which counts as granting it.\n await assertCanGrant(\n req,\n overrides.filter((o) => o.effect === 'deny').map((o) => o.permission),\n )\n if (overrides.length) {\n // One transaction, so the overrides are never cleared without the audit entry.\n const ownsTransaction = await initTransaction(req)\n try {\n await req.payload.delete({\n collection: OVERRIDES_SLUG,\n context: { [PART_OF_CHANGE]: true },\n overrideAccess: true,\n req,\n where: { user: { equals: id } },\n })\n await writeAudit(req, {\n action: 'user.reset',\n after: [],\n before: overrides.map(({ effect, permission }) => ({ effect, permission })),\n summary: `Reset to role: ${overrides.length} override${overrides.length === 1 ? '' : 's'} cleared`,\n user: id,\n })\n if (ownsTransaction) {\n await commitTransaction(req)\n }\n } catch (err) {\n await killTransaction(req)\n throw err\n }\n }\n return Response.json({ removed: overrides.length })\n}\n"],"names":["commitTransaction","initTransaction","killTransaction","getOverrides","getState","hasPermission","OVERRIDES_SLUG","PART_OF_CHANGE","writeAudit","MANAGE_PERMISSION","assertCanGrant","assertNotSelf","RESET_PATH","resetToRoleHandler","req","Response","json","errors","message","status","user","payload","findByID","id","routeParams","collection","usersSlug","depth","disableErrors","overrideAccess","catch","overrides","filter","o","effect","map","permission","length","ownsTransaction","delete","context","where","equals","action","after","before","summary","err","removed"],"mappings":"AAEA,SAASA,iBAAiB,EAAEC,eAAe,EAAEC,eAAe,QAAQ,UAAS;AAE7E,SAASC,YAAY,EAAEC,QAAQ,EAAEC,aAAa,EAAEC,cAAc,QAAQ,eAAc;AACpF,SAASC,cAAc,EAAEC,UAAU,QAAQ,cAAa;AACxD,SAASC,iBAAiB,QAAQ,iBAAgB;AAClD,SAASC,cAAc,EAAEC,aAAa,QAAQ,cAAa;AAE3D,OAAO,MAAMC,aAAa,yBAAwB;AAElD,0EAA0E,GAC1E,OAAO,MAAMC,qBAAqC,OAAOC;IACvD,IAAI,CAAE,MAAMT,cAAcS,KAAKL,oBAAqB;QAClD,OAAOM,SAASC,IAAI,CAAC;YAAEC,QAAQ;gBAAC;oBAAEC,SAAS;gBAAY;aAAE;QAAC,GAAG;YAAEC,QAAQ;QAAI;IAC7E;IACA,iGAAiG;IACjG,MAAMC,OAAO,MAAMN,IAAIO,OAAO,CAC3BC,QAAQ,CAAC;QACRC,IAAIT,IAAIU,WAAW,EAAED;QACrB,mHAAmH;QACnHE,YAAYrB,SAASU,IAAIO,OAAO,EAAEK,SAAS;QAC3CC,OAAO;QACPC,eAAe;QACfC,gBAAgB;QAChBf;IACF,GACCgB,KAAK,CAAC,IAAM;IACf,IAAI,CAACV,MAAM;QACT,OAAOL,SAASC,IAAI,CAAC;YAAEC,QAAQ;gBAAC;oBAAEC,SAAS;gBAAY;aAAE;QAAC,GAAG;YAAEC,QAAQ;QAAI;IAC7E;IACA,MAAMI,KAAKH,KAAKG,EAAE;IAClBZ,cAAcG,KAAKS;IAEnB,MAAMQ,YAAY,MAAM5B,aAAaW,IAAIO,OAAO,EAAEE,IAAIT;IACtD,4EAA4E;IAC5E,MAAMJ,eACJI,KACAiB,UAAUC,MAAM,CAAC,CAACC,IAAMA,EAAEC,MAAM,KAAK,QAAQC,GAAG,CAAC,CAACF,IAAMA,EAAEG,UAAU;IAEtE,IAAIL,UAAUM,MAAM,EAAE;QACpB,+EAA+E;QAC/E,MAAMC,kBAAkB,MAAMrC,gBAAgBa;QAC9C,IAAI;YACF,MAAMA,IAAIO,OAAO,CAACkB,MAAM,CAAC;gBACvBd,YAAYnB;gBACZkC,SAAS;oBAAE,CAACjC,eAAe,EAAE;gBAAK;gBAClCsB,gBAAgB;gBAChBf;gBACA2B,OAAO;oBAAErB,MAAM;wBAAEsB,QAAQnB;oBAAG;gBAAE;YAChC;YACA,MAAMf,WAAWM,KAAK;gBACpB6B,QAAQ;gBACRC,OAAO,EAAE;gBACTC,QAAQd,UAAUI,GAAG,CAAC,CAAC,EAAED,MAAM,EAAEE,UAAU,EAAE,GAAM,CAAA;wBAAEF;wBAAQE;oBAAW,CAAA;gBACxEU,SAAS,CAAC,eAAe,EAAEf,UAAUM,MAAM,CAAC,SAAS,EAAEN,UAAUM,MAAM,KAAK,IAAI,KAAK,IAAI,QAAQ,CAAC;gBAClGjB,MAAMG;YACR;YACA,IAAIe,iBAAiB;gBACnB,MAAMtC,kBAAkBc;YAC1B;QACF,EAAE,OAAOiC,KAAK;YACZ,MAAM7C,gBAAgBY;YACtB,MAAMiC;QACR;IACF;IACA,OAAOhC,SAASC,IAAI,CAAC;QAAEgC,SAASjB,UAAUM,MAAM;IAAC;AACnD,EAAC"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Config } from 'payload';
2
2
  import type { PermissionsPluginConfig } from './types.js';
3
- export { AUDIT_SLUG, computePermissions, getPermissions, hasPermission, OVERRIDES_SLUG, requirePermission, ROLES_SLUG, } from './access.js';
3
+ export { AUDIT_SLUG, computePermissions, getPermissions, hasPermission, OVERRIDES_SLUG, requirePermission, ROLES_SLUG, userHasPermission, } from './access.js';
4
4
  export { MANAGE_PERMISSION } from './registry.js';
5
5
  export { redundantOverrides, resolvePermission, resolvePermissions } from './resolve.js';
6
6
  export type { Area, AreaConfig, Permission, PermissionsPluginConfig, StandardAction, } from './types.js';
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { createRolesCollection } from './collections/Roles.js';
6
6
  import { RESET_PATH, resetToRoleHandler } from './endpoints/resetToRole.js';
7
7
  import { buildRegistry } from './registry.js';
8
8
  import { extendUsersCollection } from './users.js';
9
- export { AUDIT_SLUG, computePermissions, getPermissions, hasPermission, OVERRIDES_SLUG, requirePermission, ROLES_SLUG } from './access.js';
9
+ export { AUDIT_SLUG, computePermissions, getPermissions, hasPermission, OVERRIDES_SLUG, requirePermission, ROLES_SLUG, userHasPermission } from './access.js';
10
10
  export { MANAGE_PERMISSION } from './registry.js';
11
11
  export { redundantOverrides, resolvePermission, resolvePermissions } from './resolve.js';
12
12
  /** Publishing (moving `_status` to published) needs `area.publish` on top of create/edit. */ const guardPublish = (key)=>async ({ data, originalDoc, req })=>{
@@ -14,8 +14,9 @@ export { redundantOverrides, resolvePermission, resolvePermissions } from './res
14
14
  // asks to publish, or lands on a published document, changes what's live.
15
15
  const publishing = data._status !== 'draft' && (data._status === 'published' || originalDoc?._status === 'published');
16
16
  // Draft saves also send `_status: 'draft'`; only REST and GraphQL say which is which.
17
+ // REST parses `?draft=true` into a boolean before hooks run; GraphQL leaves the string.
17
18
  // ponytail: local API unpublishes aren't checked, since hooks can't tell them from draft saves
18
- const unpublishing = data._status === 'draft' && originalDoc?._status === 'published' && req.payloadAPI !== 'local' && req.query?.draft !== 'true';
19
+ const unpublishing = data._status === 'draft' && originalDoc?._status === 'published' && req.payloadAPI !== 'local' && String(req.query?.draft) !== 'true';
19
20
  if (!publishing && !unpublishing) {
20
21
  return data;
21
22
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n CollectionConfig,\n CollectionSlug,\n Config,\n GlobalConfig,\n PayloadRequest,\n} from 'payload'\n\nimport { APIError } from 'payload'\n\nimport type { Area, PermissionsPluginConfig } from './types.js'\n\nimport {\n AUDIT_SLUG,\n gateAccess,\n hasPermission,\n isCMSUser,\n markActive,\n OVERRIDES_SLUG,\n ROLES_SLUG,\n} from './access.js'\nimport { createAuditCollection } from './audit.js'\nimport { createOverridesCollection } from './collections/PermissionOverrides.js'\nimport { createRolesCollection } from './collections/Roles.js'\nimport { RESET_PATH, resetToRoleHandler } from './endpoints/resetToRole.js'\nimport { buildRegistry } from './registry.js'\nimport { extendUsersCollection } from './users.js'\n\nexport {\n AUDIT_SLUG,\n computePermissions,\n getPermissions,\n hasPermission,\n OVERRIDES_SLUG,\n requirePermission,\n ROLES_SLUG,\n} from './access.js'\nexport { MANAGE_PERMISSION } from './registry.js'\nexport { redundantOverrides, resolvePermission, resolvePermissions } from './resolve.js'\nexport type {\n Area,\n AreaConfig,\n Permission,\n PermissionsPluginConfig,\n StandardAction,\n} from './types.js'\n\n/** Publishing (moving `_status` to published) needs `area.publish` on top of create/edit. */\nconst guardPublish =\n (key: string) =>\n async ({\n data,\n originalDoc,\n req,\n }: {\n data: Record<string, unknown>\n originalDoc?: Record<string, unknown>\n req: PayloadRequest\n }) => {\n // Payload marks every draft save `_status: 'draft'` before hooks run, so anything else that\n // asks to publish, or lands on a published document, changes what's live.\n const publishing =\n data._status !== 'draft' &&\n (data._status === 'published' || originalDoc?._status === 'published')\n // Draft saves also send `_status: 'draft'`; only REST and GraphQL say which is which.\n // ponytail: local API unpublishes aren't checked, since hooks can't tell them from draft saves\n const unpublishing =\n data._status === 'draft' &&\n originalDoc?._status === 'published' &&\n req.payloadAPI !== 'local' &&\n req.query?.draft !== 'true'\n if (!publishing && !unpublishing) {\n return data\n }\n if (isCMSUser(req.payload, req.user) && !(await hasPermission(req, key))) {\n const verb = publishing ? 'publish' : 'unpublish'\n throw new APIError(`You don't have permission to ${verb} this.`, 403, undefined, true)\n }\n return data\n }\n\nconst hasKey = (area: Area, key: string) => area.permissions.some((p) => p.key === key)\n\nconst RSC = '@foundrykit/permissions-plugin/rsc'\n\n/** Server component that hides the (un)publish button from people without `key`. */\nconst publishButton = (key: string, kind: 'publish' | 'unpublish' = 'publish') => ({\n path: `${RSC}#PublishButtonGate`,\n serverProps: { kind, permission: key },\n})\n\nconst gateCollection = (collection: CollectionConfig, area: Area): CollectionConfig => ({\n ...collection,\n access: {\n ...collection.access,\n create: gateAccess(`${area.slug}.create`, collection.access?.create),\n delete: gateAccess(`${area.slug}.delete`, collection.access?.delete),\n read: gateAccess(`${area.slug}.read`, collection.access?.read),\n update: gateAccess(`${area.slug}.edit`, collection.access?.update),\n },\n admin: hasKey(area, `${area.slug}.publish`)\n ? {\n ...collection.admin,\n components: {\n ...collection.admin?.components,\n edit: {\n PublishButton: publishButton(`${area.slug}.publish`),\n UnpublishButton: publishButton(`${area.slug}.publish`, 'unpublish'),\n ...collection.admin?.components?.edit,\n },\n },\n }\n : collection.admin,\n hooks: {\n ...collection.hooks,\n afterChange: [...(collection.hooks?.afterChange ?? []), ({ req }) => markActive(req)],\n afterDelete: [...(collection.hooks?.afterDelete ?? []), ({ req }) => markActive(req)],\n beforeChange: hasKey(area, `${area.slug}.publish`)\n ? [...(collection.hooks?.beforeChange ?? []), guardPublish(`${area.slug}.publish`)]\n : collection.hooks?.beforeChange,\n },\n})\n\nconst gateGlobal = (global: GlobalConfig, area: Area): GlobalConfig => ({\n ...global,\n access: {\n ...global.access,\n read: gateAccess(`${area.slug}.read`, global.access?.read),\n update: gateAccess(`${area.slug}.edit`, global.access?.update),\n },\n admin: hasKey(area, `${area.slug}.publish`)\n ? {\n ...global.admin,\n components: {\n ...global.admin?.components,\n elements: {\n PublishButton: publishButton(`${area.slug}.publish`),\n UnpublishButton: publishButton(`${area.slug}.publish`, 'unpublish'),\n ...global.admin?.components?.elements,\n },\n },\n }\n : global.admin,\n hooks: {\n ...global.hooks,\n afterChange: [...(global.hooks?.afterChange ?? []), ({ req }) => markActive(req)],\n beforeChange: hasKey(area, `${area.slug}.publish`)\n ? [...(global.hooks?.beforeChange ?? []), guardPublish(`${area.slug}.publish`)]\n : global.hooks?.beforeChange,\n },\n})\n\nexport const permissionsPlugin =\n (pluginOptions: PermissionsPluginConfig = {}) =>\n (config: Config): Config => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- a union once a site generates types\n const usersSlug = (config.admin?.user ?? 'users') as CollectionSlug\n const collections = config.collections ?? []\n const globals = config.globals ?? []\n const areas = pluginOptions.areas ?? []\n\n if (!collections.some((c) => c.slug === usersSlug)) {\n throw new Error(`permissions: users collection \"${usersSlug}\" not found`)\n }\n for (const slug of [ROLES_SLUG, OVERRIDES_SLUG, AUDIT_SLUG]) {\n if (collections.some((c) => c.slug === slug)) {\n throw new Error(`permissions: a \"${slug}\" collection already exists`)\n }\n }\n\n const registry = buildRegistry(areas, collections, globals)\n const areaFor = (key: 'collection' | 'global', slug: string) => {\n const configured = areas.find((a) => a[key] === slug)\n return configured && registry.find((a) => a.slug === configured.slug)\n }\n\n config.custom = {\n ...config.custom,\n permissions: {\n isSuperAdmin: pluginOptions.isSuperAdmin ?? (() => false),\n keys: registry.flatMap((a) => a.permissions.map((p) => p.key)),\n registry,\n usersSlug,\n },\n }\n\n config.collections = [\n ...collections.map((collection) => {\n if (collection.slug === usersSlug) {\n return extendUsersCollection(collection)\n }\n const area = !pluginOptions.disabled && areaFor('collection', collection.slug)\n return area ? gateCollection(collection, area) : collection\n }),\n createRolesCollection({ registry, usersSlug }),\n createOverridesCollection({ registry, usersSlug }),\n createAuditCollection(usersSlug),\n ]\n\n if (pluginOptions.disabled) {\n return config\n }\n\n config.globals = globals.map((global) => {\n const area = areaFor('global', global.slug)\n return area ? gateGlobal(global, area) : global\n })\n\n config.admin = {\n ...config.admin,\n components: {\n ...config.admin?.components,\n afterNavLinks: [...(config.admin?.components?.afterNavLinks ?? []), `${RSC}#NavLinks`],\n views: {\n ...config.admin?.components?.views,\n permissionsRoles: { Component: `${RSC}#RolesView`, exact: true, path: '/permissions' },\n permissionsUsers: {\n Component: `${RSC}#UsersView`,\n exact: true,\n path: '/permissions/users',\n },\n },\n },\n }\n\n config.endpoints = [\n ...(config.endpoints ?? []),\n { handler: resetToRoleHandler, method: 'post', path: RESET_PATH },\n ]\n\n return config\n }\n"],"names":["APIError","AUDIT_SLUG","gateAccess","hasPermission","isCMSUser","markActive","OVERRIDES_SLUG","ROLES_SLUG","createAuditCollection","createOverridesCollection","createRolesCollection","RESET_PATH","resetToRoleHandler","buildRegistry","extendUsersCollection","computePermissions","getPermissions","requirePermission","MANAGE_PERMISSION","redundantOverrides","resolvePermission","resolvePermissions","guardPublish","key","data","originalDoc","req","publishing","_status","unpublishing","payloadAPI","query","draft","payload","user","verb","undefined","hasKey","area","permissions","some","p","RSC","publishButton","kind","path","serverProps","permission","gateCollection","collection","access","create","slug","delete","read","update","admin","components","edit","PublishButton","UnpublishButton","hooks","afterChange","afterDelete","beforeChange","gateGlobal","global","elements","permissionsPlugin","pluginOptions","config","usersSlug","collections","globals","areas","c","Error","registry","areaFor","configured","find","a","custom","isSuperAdmin","keys","flatMap","map","disabled","afterNavLinks","views","permissionsRoles","Component","exact","permissionsUsers","endpoints","handler","method"],"mappings":"AAQA,SAASA,QAAQ,QAAQ,UAAS;AAIlC,SACEC,UAAU,EACVC,UAAU,EACVC,aAAa,EACbC,SAAS,EACTC,UAAU,EACVC,cAAc,EACdC,UAAU,QACL,cAAa;AACpB,SAASC,qBAAqB,QAAQ,aAAY;AAClD,SAASC,yBAAyB,QAAQ,uCAAsC;AAChF,SAASC,qBAAqB,QAAQ,yBAAwB;AAC9D,SAASC,UAAU,EAAEC,kBAAkB,QAAQ,6BAA4B;AAC3E,SAASC,aAAa,QAAQ,gBAAe;AAC7C,SAASC,qBAAqB,QAAQ,aAAY;AAElD,SACEb,UAAU,EACVc,kBAAkB,EAClBC,cAAc,EACdb,aAAa,EACbG,cAAc,EACdW,iBAAiB,EACjBV,UAAU,QACL,cAAa;AACpB,SAASW,iBAAiB,QAAQ,gBAAe;A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0B;gBAAEoE;gBAAUN;YAAU;YAChD/D,sBAAsB+D;SACvB;QAED,IAAIF,cAAckB,QAAQ,EAAE;YAC1B,OAAOjB;QACT;QAEAA,OAAOG,OAAO,GAAGA,QAAQa,GAAG,CAAC,CAACpB;YAC5B,MAAM5B,OAAOwC,QAAQ,UAAUZ,OAAOd,IAAI;YAC1C,OAAOd,OAAO2B,WAAWC,QAAQ5B,QAAQ4B;QAC3C;QAEAI,OAAOd,KAAK,GAAG;YACb,GAAGc,OAAOd,KAAK;YACfC,YAAY;gBACV,GAAGa,OAAOd,KAAK,EAAEC,UAAU;gBAC3B+B,eAAe;uBAAKlB,OAAOd,KAAK,EAAEC,YAAY+B,iBAAiB,EAAE;oBAAG,GAAG9C,IAAI,SAAS,CAAC;iBAAC;gBACtF+C,OAAO;oBACL,GAAGnB,OAAOd,KAAK,EAAEC,YAAYgC,KAAK;oBAClCC,kBAAkB;wBAAEC,WAAW,GAAGjD,IAAI,UAAU,CAAC;wBAAEkD,OAAO;wBAAM/C,MAAM;oBAAe;oBACrFgD,kBAAkB;wBAChBF,WAAW,GAAGjD,IAAI,UAAU,CAAC;wBAC7BkD,OAAO;wBACP/C,MAAM;oBACR;gBACF;YACF;QACF;QAEAyB,OAAOwB,SAAS,GAAG;eACbxB,OAAOwB,SAAS,IAAI,EAAE;YAC1B;gBAAEC,SAASnF;gBAAoBoF,QAAQ;gBAAQnD,MAAMlC;YAAW;SACjE;QAED,OAAO2D;IACT,EAAC"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n CollectionConfig,\n CollectionSlug,\n Config,\n GlobalConfig,\n PayloadRequest,\n} from 'payload'\n\nimport { APIError } from 'payload'\n\nimport type { Area, PermissionsPluginConfig } from './types.js'\n\nimport {\n AUDIT_SLUG,\n gateAccess,\n hasPermission,\n isCMSUser,\n markActive,\n OVERRIDES_SLUG,\n ROLES_SLUG,\n} from './access.js'\nimport { createAuditCollection } from './audit.js'\nimport { createOverridesCollection } from './collections/PermissionOverrides.js'\nimport { createRolesCollection } from './collections/Roles.js'\nimport { RESET_PATH, resetToRoleHandler } from './endpoints/resetToRole.js'\nimport { buildRegistry } from './registry.js'\nimport { extendUsersCollection } from './users.js'\n\nexport {\n AUDIT_SLUG,\n computePermissions,\n getPermissions,\n hasPermission,\n OVERRIDES_SLUG,\n requirePermission,\n ROLES_SLUG,\n userHasPermission,\n} from './access.js'\nexport { MANAGE_PERMISSION } from './registry.js'\nexport { redundantOverrides, resolvePermission, resolvePermissions } from './resolve.js'\nexport type {\n Area,\n AreaConfig,\n Permission,\n PermissionsPluginConfig,\n StandardAction,\n} from './types.js'\n\n/** Publishing (moving `_status` to published) needs `area.publish` on top of create/edit. */\nconst guardPublish =\n (key: string) =>\n async ({\n data,\n originalDoc,\n req,\n }: {\n data: Record<string, unknown>\n originalDoc?: Record<string, unknown>\n req: PayloadRequest\n }) => {\n // Payload marks every draft save `_status: 'draft'` before hooks run, so anything else that\n // asks to publish, or lands on a published document, changes what's live.\n const publishing =\n data._status !== 'draft' &&\n (data._status === 'published' || originalDoc?._status === 'published')\n // Draft saves also send `_status: 'draft'`; only REST and GraphQL say which is which.\n // REST parses `?draft=true` into a boolean before hooks run; GraphQL leaves the string.\n // ponytail: local API unpublishes aren't checked, since hooks can't tell them from draft saves\n const unpublishing =\n data._status === 'draft' &&\n originalDoc?._status === 'published' &&\n req.payloadAPI !== 'local' &&\n String(req.query?.draft) !== 'true'\n if (!publishing && !unpublishing) {\n return data\n }\n if (isCMSUser(req.payload, req.user) && !(await hasPermission(req, key))) {\n const verb = publishing ? 'publish' : 'unpublish'\n throw new APIError(`You don't have permission to ${verb} this.`, 403, undefined, true)\n }\n return data\n }\n\nconst hasKey = (area: Area, key: string) => area.permissions.some((p) => p.key === key)\n\nconst RSC = '@foundrykit/permissions-plugin/rsc'\n\n/** Server component that hides the (un)publish button from people without `key`. */\nconst publishButton = (key: string, kind: 'publish' | 'unpublish' = 'publish') => ({\n path: `${RSC}#PublishButtonGate`,\n serverProps: { kind, permission: key },\n})\n\nconst gateCollection = (collection: CollectionConfig, area: Area): CollectionConfig => ({\n ...collection,\n access: {\n ...collection.access,\n create: gateAccess(`${area.slug}.create`, collection.access?.create),\n delete: gateAccess(`${area.slug}.delete`, collection.access?.delete),\n read: gateAccess(`${area.slug}.read`, collection.access?.read),\n update: gateAccess(`${area.slug}.edit`, collection.access?.update),\n },\n admin: hasKey(area, `${area.slug}.publish`)\n ? {\n ...collection.admin,\n components: {\n ...collection.admin?.components,\n edit: {\n PublishButton: publishButton(`${area.slug}.publish`),\n UnpublishButton: publishButton(`${area.slug}.publish`, 'unpublish'),\n ...collection.admin?.components?.edit,\n },\n },\n }\n : collection.admin,\n hooks: {\n ...collection.hooks,\n afterChange: [...(collection.hooks?.afterChange ?? []), ({ req }) => markActive(req)],\n afterDelete: [...(collection.hooks?.afterDelete ?? []), ({ req }) => markActive(req)],\n beforeChange: hasKey(area, `${area.slug}.publish`)\n ? [...(collection.hooks?.beforeChange ?? []), guardPublish(`${area.slug}.publish`)]\n : collection.hooks?.beforeChange,\n },\n})\n\nconst gateGlobal = (global: GlobalConfig, area: Area): GlobalConfig => ({\n ...global,\n access: {\n ...global.access,\n read: gateAccess(`${area.slug}.read`, global.access?.read),\n update: gateAccess(`${area.slug}.edit`, global.access?.update),\n },\n admin: hasKey(area, `${area.slug}.publish`)\n ? {\n ...global.admin,\n components: {\n ...global.admin?.components,\n elements: {\n PublishButton: publishButton(`${area.slug}.publish`),\n UnpublishButton: publishButton(`${area.slug}.publish`, 'unpublish'),\n ...global.admin?.components?.elements,\n },\n },\n }\n : global.admin,\n hooks: {\n ...global.hooks,\n afterChange: [...(global.hooks?.afterChange ?? []), ({ req }) => markActive(req)],\n beforeChange: hasKey(area, `${area.slug}.publish`)\n ? [...(global.hooks?.beforeChange ?? []), guardPublish(`${area.slug}.publish`)]\n : global.hooks?.beforeChange,\n },\n})\n\nexport const permissionsPlugin =\n (pluginOptions: PermissionsPluginConfig = {}) =>\n (config: Config): Config => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- a union once a site generates types\n const usersSlug = (config.admin?.user ?? 'users') as CollectionSlug\n const collections = config.collections ?? []\n const globals = config.globals ?? []\n const areas = pluginOptions.areas ?? []\n\n if (!collections.some((c) => c.slug === usersSlug)) {\n throw new Error(`permissions: users collection \"${usersSlug}\" not found`)\n }\n for (const slug of [ROLES_SLUG, OVERRIDES_SLUG, AUDIT_SLUG]) {\n if (collections.some((c) => c.slug === slug)) {\n throw new Error(`permissions: a \"${slug}\" collection already exists`)\n }\n }\n\n const registry = buildRegistry(areas, collections, globals)\n const areaFor = (key: 'collection' | 'global', slug: string) => {\n const configured = areas.find((a) => a[key] === slug)\n return configured && registry.find((a) => a.slug === configured.slug)\n }\n\n config.custom = {\n ...config.custom,\n permissions: {\n isSuperAdmin: pluginOptions.isSuperAdmin ?? (() => false),\n keys: registry.flatMap((a) => a.permissions.map((p) => p.key)),\n registry,\n usersSlug,\n },\n }\n\n config.collections = [\n ...collections.map((collection) => {\n if (collection.slug === usersSlug) {\n return extendUsersCollection(collection)\n }\n const area = !pluginOptions.disabled && areaFor('collection', collection.slug)\n return area ? gateCollection(collection, area) : collection\n }),\n createRolesCollection({ registry, usersSlug }),\n createOverridesCollection({ registry, usersSlug }),\n createAuditCollection(usersSlug),\n ]\n\n if (pluginOptions.disabled) {\n return config\n }\n\n config.globals = globals.map((global) => {\n const area = areaFor('global', global.slug)\n return area ? gateGlobal(global, area) : global\n })\n\n config.admin = {\n ...config.admin,\n components: {\n ...config.admin?.components,\n afterNavLinks: [...(config.admin?.components?.afterNavLinks ?? []), `${RSC}#NavLinks`],\n views: {\n ...config.admin?.components?.views,\n permissionsRoles: { Component: `${RSC}#RolesView`, exact: true, path: '/permissions' },\n permissionsUsers: {\n Component: `${RSC}#UsersView`,\n exact: true,\n path: '/permissions/users',\n },\n },\n },\n }\n\n config.endpoints = [\n ...(config.endpoints ?? []),\n { handler: resetToRoleHandler, method: 'post', path: RESET_PATH },\n ]\n\n return config\n }\n"],"names":["APIError","AUDIT_SLUG","gateAccess","hasPermission","isCMSUser","markActive","OVERRIDES_SLUG","ROLES_SLUG","createAuditCollection","createOverridesCollection","createRolesCollection","RESET_PATH","resetToRoleHandler","buildRegistry","extendUsersCollection","computePermissions","getPermissions","requirePermission","userHasPermission","MANAGE_PERMISSION","redundantOverrides","resolvePermission","resolvePermissions","guardPublish","key","data","originalDoc","req","publishing","_status","unpublishing","payloadAPI","String","query","draft","payload","user","verb","undefined","hasKey","area","permissions","some","p","RSC","publishButton","kind","path","serverProps","permission","gateCollection","collection","access","create","slug","delete","read","update","admin","components","edit","PublishButton","UnpublishButton","hooks","afterChange","afterDelete","beforeChange","gateGlobal","global","elements","permissionsPlugin","pluginOptions","config","usersSlug","collections","globals","areas","c","Error","registry","areaFor","configured","find","a","custom","isSuperAdmin","keys","flatMap","map","disabled","afterNavLinks","views","permissionsRoles","Component","exact","permissionsUsers","endpoints","handler","method"],"mappings":"AAQA,SAASA,QAAQ,QAAQ,UAAS;AAIlC,SACEC,UAAU,EACVC,UAAU,EACVC,aAAa,EACbC,SAAS,EACTC,UAAU,EACVC,cAAc,EACdC,UAAU,QACL,cAAa;AACpB,SAASC,qBAAqB,QAAQ,aAAY;AAClD,SAASC,yBAAyB,QAAQ,uCAAsC;AAChF,SAASC,qBAAqB,QAAQ,yBAAwB;AAC9D,SAASC,UAAU,EAAEC,kBAAkB,QAAQ,6BAA4B;AAC3E,SAASC,aAAa,QAAQ,gBAAe;AAC7C,SAASC,qBAAqB,QAAQ,aAAY;AAElD,SACEb,UAAU,EACVc,kBAAkB,EAClBC,cAAc,EACdb,aAAa,EACbG,cAAc,EACdW,iBAAiB,EACjBV,UAAU,EACVW,iBAAiB,QACZ,cAAa;AACpB,SAASC,iBAAiB,QAAQ,gBAAe;AACjD,SAASC,kBAAkB,EAAEC,iBAAiB,EAAEC,kBAAkB,QAAQ,eAAc;AASxF,2FAA2F,GAC3F,MAAMC,eACJ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AQ,EAAE;YAC1B,OAAOjB;QACT;QAEAA,OAAOG,OAAO,GAAGA,QAAQa,GAAG,CAAC,CAACpB;YAC5B,MAAM5B,OAAOwC,QAAQ,UAAUZ,OAAOd,IAAI;YAC1C,OAAOd,OAAO2B,WAAWC,QAAQ5B,QAAQ4B;QAC3C;QAEAI,OAAOd,KAAK,GAAG;YACb,GAAGc,OAAOd,KAAK;YACfC,YAAY;gBACV,GAAGa,OAAOd,KAAK,EAAEC,UAAU;gBAC3B+B,eAAe;uBAAKlB,OAAOd,KAAK,EAAEC,YAAY+B,iBAAiB,EAAE;oBAAG,GAAG9C,IAAI,SAAS,CAAC;iBAAC;gBACtF+C,OAAO;oBACL,GAAGnB,OAAOd,KAAK,EAAEC,YAAYgC,KAAK;oBAClCC,kBAAkB;wBAAEC,WAAW,GAAGjD,IAAI,UAAU,CAAC;wBAAEkD,OAAO;wBAAM/C,MAAM;oBAAe;oBACrFgD,kBAAkB;wBAChBF,WAAW,GAAGjD,IAAI,UAAU,CAAC;wBAC7BkD,OAAO;wBACP/C,MAAM;oBACR;gBACF;YACF;QACF;QAEAyB,OAAOwB,SAAS,GAAG;eACbxB,OAAOwB,SAAS,IAAI,EAAE;YAC1B;gBAAEC,SAASrF;gBAAoBsF,QAAQ;gBAAQnD,MAAMpC;YAAW;SACjE;QAED,OAAO6D;IACT,EAAC"}
package/dist/users.js CHANGED
@@ -62,6 +62,7 @@ const roleName = async (req, id)=>{
62
62
  ],
63
63
  hooks: {
64
64
  ...users.hooks,
65
+ // The override's user is required, so the database can't just null it out.
65
66
  afterChange: [
66
67
  ...users.hooks?.afterChange ?? [],
67
68
  async ({ doc, operation, previousDoc, req })=>{
@@ -134,6 +135,24 @@ const roleName = async (req, id)=>{
134
135
  }
135
136
  return data;
136
137
  }
138
+ ],
139
+ beforeDelete: [
140
+ ...users.hooks?.beforeDelete ?? [],
141
+ async ({ id, req })=>{
142
+ await req.payload.delete({
143
+ collection: OVERRIDES_SLUG,
144
+ context: {
145
+ [PART_OF_CHANGE]: true
146
+ },
147
+ overrideAccess: true,
148
+ req,
149
+ where: {
150
+ user: {
151
+ equals: id
152
+ }
153
+ }
154
+ });
155
+ }
137
156
  ]
138
157
  }
139
158
  };
package/dist/users.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/users.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport {\n getOverrides,\n getRolePermissions,\n hasPermission,\n isCMSUser,\n markActive,\n OVERRIDES_SLUG,\n relationID,\n ROLES_SLUG,\n} from './access.js'\nimport { PART_OF_CHANGE, writeAudit } from './audit.js'\nimport { MANAGE_PERMISSION } from './registry.js'\nimport { redundantOverrides } from './resolve.js'\nimport { assertCanGrant, assertNotSelf } from './rules.js'\n\nconst roleName = async (req: Parameters<typeof writeAudit>[0], id: null | number | string) => {\n if (id === null) {\n return null\n }\n const { docs } = await req.payload.find({\n collection: ROLES_SLUG,\n depth: 0,\n limit: 1,\n overrideAccess: true,\n req,\n where: { id: { equals: id } },\n })\n return (docs[0]?.name as string | undefined) ?? null\n}\n\n/** Adds the role field, last-active stamp and role-change rules to the users collection. */\nexport const extendUsersCollection = (users: CollectionConfig): CollectionConfig => {\n for (const name of ['role', 'lastActiveAt']) {\n if (users.fields.some((field) => 'name' in field && field.name === name)) {\n throw new Error(`permissions: the \"${users.slug}\" collection already has a \"${name}\" field`)\n }\n }\n\n return {\n ...users,\n fields: [\n ...users.fields,\n {\n name: 'role',\n type: 'relationship',\n access: {\n create: ({ req }) => hasPermission(req, MANAGE_PERMISSION),\n update: async ({ id, req }) =>\n !(isCMSUser(req.payload, req.user) && String(req.user.id) === String(id)) &&\n hasPermission(req, MANAGE_PERMISSION),\n },\n admin: { position: 'sidebar' },\n index: true,\n relationTo: ROLES_SLUG,\n },\n {\n name: 'lastActiveAt',\n type: 'date',\n admin: {\n date: { pickerAppearance: 'dayAndTime' },\n description: 'Last login or edit.',\n position: 'sidebar',\n readOnly: true,\n },\n },\n ],\n hooks: {\n ...users.hooks,\n afterChange: [\n ...(users.hooks?.afterChange ?? []),\n async ({ doc, operation, previousDoc, req }) => {\n const was = operation === 'create' ? null : relationID(previousDoc?.role)\n const now = relationID(doc.role)\n if (String(was) === String(now)) {\n return\n }\n\n const rolePermissions = await getRolePermissions(req.payload, now, req)\n const dropped = redundantOverrides(\n await getOverrides(req.payload, doc.id, req),\n rolePermissions,\n )\n if (dropped.length) {\n await req.payload.delete({\n collection: OVERRIDES_SLUG,\n context: { [PART_OF_CHANGE]: true },\n overrideAccess: true,\n req,\n where: { id: { in: dropped.map((o) => o.id) } },\n })\n }\n\n const fromName = await roleName(req, was)\n const toName = await roleName(req, now)\n await writeAudit(req, {\n action: 'user.role',\n after: {\n droppedOverrides: dropped.map(({ effect, permission }) => ({ effect, permission })),\n role: toName,\n },\n before: { role: fromName },\n role: now,\n summary: `Role changed from ${fromName ?? 'none'} to ${toName ?? 'none'}`,\n user: doc.id,\n })\n },\n ],\n afterLogin: [\n ...(users.hooks?.afterLogin ?? []),\n ({ req, user }) => markActive(req, { ...user, collection: users.slug }),\n ],\n beforeChange: [\n ...(users.hooks?.beforeChange ?? []),\n async ({ data, originalDoc, req }) => {\n if (data.role === undefined) {\n return data\n }\n const now = relationID(data.role)\n if (String(relationID(originalDoc?.role)) === String(now)) {\n return data\n }\n if (originalDoc) {\n assertNotSelf(req, originalDoc.id)\n }\n if (isCMSUser(req.payload, req.user)) {\n // Read outside the transaction: Payload runs beforeChange work concurrently\n // and Mongo rejects parallel operations racing to start a transaction.\n await assertCanGrant(req, await getRolePermissions(req.payload, now))\n }\n return data\n },\n ],\n },\n }\n}\n"],"names":["getOverrides","getRolePermissions","hasPermission","isCMSUser","markActive","OVERRIDES_SLUG","relationID","ROLES_SLUG","PART_OF_CHANGE","writeAudit","MANAGE_PERMISSION","redundantOverrides","assertCanGrant","assertNotSelf","roleName","req","id","docs","payload","find","collection","depth","limit","overrideAccess","where","equals","name","extendUsersCollection","users","fields","some","field","Error","slug","type","access","create","update","user","String","admin","position","index","relationTo","date","pickerAppearance","description","readOnly","hooks","afterChange","doc","operation","previousDoc","was","role","now","rolePermissions","dropped","length","delete","context","in","map","o","fromName","toName","action","after","droppedOverrides","effect","permission","before","summary","afterLogin","beforeChange","data","originalDoc","undefined"],"mappings":"AAEA,SACEA,YAAY,EACZC,kBAAkB,EAClBC,aAAa,EACbC,SAAS,EACTC,UAAU,EACVC,cAAc,EACdC,UAAU,EACVC,UAAU,QACL,cAAa;AACpB,SAASC,cAAc,EAAEC,UAAU,QAAQ,aAAY;AACvD,SAASC,iBAAiB,QAAQ,gBAAe;AACjD,SAASC,kBAAkB,QAAQ,eAAc;AACjD,SAASC,cAAc,EAAEC,aAAa,QAAQ,aAAY;AAE1D,MAAMC,WAAW,OAAOC,KAAuCC;IAC7D,IAAIA,OAAO,MAAM;QACf,OAAO;IACT;IACA,MAAM,EAAEC,IAAI,EAAE,GAAG,MAAMF,IAAIG,OAAO,CAACC,IAAI,CAAC;QACtCC,YAAYb;QACZc,OAAO;QACPC,OAAO;QACPC,gBAAgB;QAChBR;QACAS,OAAO;YAAER,IAAI;gBAAES,QAAQT;YAAG;QAAE;IAC9B;IACA,OAAO,AAACC,IAAI,CAAC,EAAE,EAAES,QAA+B;AAClD;AAEA,0FAA0F,GAC1F,OAAO,MAAMC,wBAAwB,CAACC;IACpC,KAAK,MAAMF,QAAQ;QAAC;QAAQ;KAAe,CAAE;QAC3C,IAAIE,MAAMC,MAAM,CAACC,IAAI,CAAC,CAACC,QAAU,UAAUA,SAASA,MAAML,IAAI,KAAKA,OAAO;YACxE,MAAM,IAAIM,MAAM,CAAC,kBAAkB,EAAEJ,MAAMK,IAAI,CAAC,4BAA4B,EAAEP,KAAK,OAAO,CAAC;QAC7F;IACF;IAEA,OAAO;QACL,GAAGE,KAAK;QACRC,QAAQ;eACHD,MAAMC,MAAM;YACf;gBACEH,MAAM;gBACNQ,MAAM;gBACNC,QAAQ;oBACNC,QAAQ,CAAC,EAAErB,GAAG,EAA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;AACF,EAAC"}
1
+ {"version":3,"sources":["../src/users.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport {\n getOverrides,\n getRolePermissions,\n hasPermission,\n isCMSUser,\n markActive,\n OVERRIDES_SLUG,\n relationID,\n ROLES_SLUG,\n} from './access.js'\nimport { PART_OF_CHANGE, writeAudit } from './audit.js'\nimport { MANAGE_PERMISSION } from './registry.js'\nimport { redundantOverrides } from './resolve.js'\nimport { assertCanGrant, assertNotSelf } from './rules.js'\n\nconst roleName = async (req: Parameters<typeof writeAudit>[0], id: null | number | string) => {\n if (id === null) {\n return null\n }\n const { docs } = await req.payload.find({\n collection: ROLES_SLUG,\n depth: 0,\n limit: 1,\n overrideAccess: true,\n req,\n where: { id: { equals: id } },\n })\n return (docs[0]?.name as string | undefined) ?? null\n}\n\n/** Adds the role field, last-active stamp and role-change rules to the users collection. */\nexport const extendUsersCollection = (users: CollectionConfig): CollectionConfig => {\n for (const name of ['role', 'lastActiveAt']) {\n if (users.fields.some((field) => 'name' in field && field.name === name)) {\n throw new Error(`permissions: the \"${users.slug}\" collection already has a \"${name}\" field`)\n }\n }\n\n return {\n ...users,\n fields: [\n ...users.fields,\n {\n name: 'role',\n type: 'relationship',\n access: {\n create: ({ req }) => hasPermission(req, MANAGE_PERMISSION),\n update: async ({ id, req }) =>\n !(isCMSUser(req.payload, req.user) && String(req.user.id) === String(id)) &&\n hasPermission(req, MANAGE_PERMISSION),\n },\n admin: { position: 'sidebar' },\n index: true,\n relationTo: ROLES_SLUG,\n },\n {\n name: 'lastActiveAt',\n type: 'date',\n admin: {\n date: { pickerAppearance: 'dayAndTime' },\n description: 'Last login or edit.',\n position: 'sidebar',\n readOnly: true,\n },\n },\n ],\n hooks: {\n ...users.hooks,\n // The override's user is required, so the database can't just null it out.\n afterChange: [\n ...(users.hooks?.afterChange ?? []),\n async ({ doc, operation, previousDoc, req }) => {\n const was = operation === 'create' ? null : relationID(previousDoc?.role)\n const now = relationID(doc.role)\n if (String(was) === String(now)) {\n return\n }\n\n const rolePermissions = await getRolePermissions(req.payload, now, req)\n const dropped = redundantOverrides(\n await getOverrides(req.payload, doc.id, req),\n rolePermissions,\n )\n if (dropped.length) {\n await req.payload.delete({\n collection: OVERRIDES_SLUG,\n context: { [PART_OF_CHANGE]: true },\n overrideAccess: true,\n req,\n where: { id: { in: dropped.map((o) => o.id) } },\n })\n }\n\n const fromName = await roleName(req, was)\n const toName = await roleName(req, now)\n await writeAudit(req, {\n action: 'user.role',\n after: {\n droppedOverrides: dropped.map(({ effect, permission }) => ({ effect, permission })),\n role: toName,\n },\n before: { role: fromName },\n role: now,\n summary: `Role changed from ${fromName ?? 'none'} to ${toName ?? 'none'}`,\n user: doc.id,\n })\n },\n ],\n afterLogin: [\n ...(users.hooks?.afterLogin ?? []),\n ({ req, user }) => markActive(req, { ...user, collection: users.slug }),\n ],\n beforeChange: [\n ...(users.hooks?.beforeChange ?? []),\n async ({ data, originalDoc, req }) => {\n if (data.role === undefined) {\n return data\n }\n const now = relationID(data.role)\n if (String(relationID(originalDoc?.role)) === String(now)) {\n return data\n }\n if (originalDoc) {\n assertNotSelf(req, originalDoc.id)\n }\n if (isCMSUser(req.payload, req.user)) {\n // Read outside the transaction: Payload runs beforeChange work concurrently\n // and Mongo rejects parallel operations racing to start a transaction.\n await assertCanGrant(req, await getRolePermissions(req.payload, now))\n }\n return data\n },\n ],\n beforeDelete: [\n ...(users.hooks?.beforeDelete ?? []),\n async ({ id, req }) => {\n await req.payload.delete({\n collection: OVERRIDES_SLUG,\n context: { [PART_OF_CHANGE]: true },\n overrideAccess: true,\n req,\n where: { user: { equals: id } },\n })\n },\n ],\n },\n }\n}\n"],"names":["getOverrides","getRolePermissions","hasPermission","isCMSUser","markActive","OVERRIDES_SLUG","relationID","ROLES_SLUG","PART_OF_CHANGE","writeAudit","MANAGE_PERMISSION","redundantOverrides","assertCanGrant","assertNotSelf","roleName","req","id","docs","payload","find","collection","depth","limit","overrideAccess","where","equals","name","extendUsersCollection","users","fields","some","field","Error","slug","type","access","create","update","user","String","admin","position","index","relationTo","date","pickerAppearance","description","readOnly","hooks","afterChange","doc","operation","previousDoc","was","role","now","rolePermissions","dropped","length","delete","context","in","map","o","fromName","toName","action","after","droppedOverrides","effect","permission","before","summary","afterLogin","beforeChange","data","originalDoc","undefined","beforeDelete"],"mappings":"AAEA,SACEA,YAAY,EACZC,kBAAkB,EAClBC,aAAa,EACbC,SAAS,EACTC,UAAU,EACVC,cAAc,EACdC,UAAU,EACVC,UAAU,QACL,cAAa;AACpB,SAASC,cAAc,EAAEC,UAAU,QAAQ,aAAY;AACvD,SAASC,iBAAiB,QAAQ,gBAAe;AACjD,SAASC,kBAAkB,QAAQ,eAAc;AACjD,SAASC,cAAc,EAAEC,aAAa,QAAQ,aAAY;AAE1D,MAAMC,WAAW,OAAOC,KAAuCC;IAC7D,IAAIA,OAAO,MAAM;QACf,OAAO;IACT;IACA,MAAM,EAAEC,IAAI,EAAE,GAAG,MAAMF,IAAIG,OAAO,CAACC,IAAI,CAAC;QACtCC,YAAYb;QACZc,OAAO;QACPC,OAAO;QACPC,gBAAgB;QAChBR;QACAS,OAAO;YAAER,IAAI;gBAAES,QAAQT;YAAG;QAAE;IAC9B;IACA,OAAO,AAACC,IAAI,CAAC,EAAE,EAAES,QAA+B;AAClD;AAEA,0FAA0F,GAC1F,OAAO,MAAMC,wBAAwB,CAACC;IACpC,KAAK,MAAMF,QAAQ;QAAC;QAAQ;KAAe,CAAE;QAC3C,IAAIE,MAAMC,MAAM,CAACC,IAAI,CAAC,CAACC,QAAU,UAAUA,SAASA,MAAML,IAAI,KAAKA,OAAO;YACxE,MAAM,IAAIM,MAAM,CAAC,kBAAkB,EAAEJ,MAAMK,IAAI,CAAC,4BAA4B,EAAEP,KAAK,OAAO,CAAC;QAC7F;IACF;IAEA,OAAO;QACL,GAAGE,KAAK;QACRC,QAAQ;eACHD,MAAMC,MAAM;YACf;gBACEH,MAAM;gBACNQ,MAAM;gBACNC,QAAQ;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AO,EAAEqC;oBAClE;oBACA,OAAOoB;gBACT;aACD;YACDG,cAAc;mBACRlD,MAAMoB,KAAK,EAAE8B,gBAAgB,EAAE;gBACnC,OAAO,EAAE9D,EAAE,EAAED,GAAG,EAAE;oBAChB,MAAMA,IAAIG,OAAO,CAACyC,MAAM,CAAC;wBACvBvC,YAAYf;wBACZuD,SAAS;4BAAE,CAACpD,eAAe,EAAE;wBAAK;wBAClCe,gBAAgB;wBAChBR;wBACAS,OAAO;4BAAEc,MAAM;gCAAEb,QAAQT;4BAAG;wBAAE;oBAChC;gBACF;aACD;QACH;IACF;AACF,EAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foundrykit/permissions-plugin",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Granular permissions for Payload CMS 3: area.action permissions, editable roles, per-user overrides and an audit log",
5
5
  "license": "MIT",
6
6
  "repository": {