@proteinjs/user-ui 1.8.0 → 1.9.0

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.
Files changed (31) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/generated/index.d.ts.map +1 -1
  3. package/dist/generated/index.js +3 -1
  4. package/dist/generated/index.js.map +1 -1
  5. package/dist/src/form/UserRecordFormCustomization.d.ts +22 -0
  6. package/dist/src/form/UserRecordFormCustomization.d.ts.map +1 -0
  7. package/dist/src/form/UserRecordFormCustomization.js +73 -0
  8. package/dist/src/form/UserRecordFormCustomization.js.map +1 -0
  9. package/dist/src/form/UserRolesField.d.ts +16 -0
  10. package/dist/src/form/UserRolesField.d.ts.map +1 -0
  11. package/dist/src/form/UserRolesField.js +114 -0
  12. package/dist/src/form/UserRolesField.js.map +1 -0
  13. package/dist/src/form/UserStatusField.d.ts +11 -0
  14. package/dist/src/form/UserStatusField.d.ts.map +1 -0
  15. package/dist/src/form/UserStatusField.js +24 -0
  16. package/dist/src/form/UserStatusField.js.map +1 -0
  17. package/dist/test/UserRecordFormCustomization.test.d.ts +5 -0
  18. package/dist/test/UserRecordFormCustomization.test.d.ts.map +1 -0
  19. package/dist/test/UserRecordFormCustomization.test.js +363 -0
  20. package/dist/test/UserRecordFormCustomization.test.js.map +1 -0
  21. package/dist/test/adminAccessGrantPrincipalRendering.test.d.ts +5 -0
  22. package/dist/test/adminAccessGrantPrincipalRendering.test.d.ts.map +1 -0
  23. package/dist/test/adminAccessGrantPrincipalRendering.test.js +199 -0
  24. package/dist/test/adminAccessGrantPrincipalRendering.test.js.map +1 -0
  25. package/generated/index.ts +3 -1
  26. package/package.json +3 -3
  27. package/src/form/UserRecordFormCustomization.tsx +54 -0
  28. package/src/form/UserRolesField.tsx +96 -0
  29. package/src/form/UserStatusField.tsx +30 -0
  30. package/test/UserRecordFormCustomization.test.tsx +242 -0
  31. package/test/adminAccessGrantPrincipalRendering.test.tsx +128 -0
@@ -9,11 +9,12 @@ import '@proteinjs/user';
9
9
  /** Generate Source Graph */
10
10
 
11
11
  const sourceGraph =
12
- '{"options":{"directed":true,"multigraph":false,"compound":false},"nodes":[{"v":"/Omit"},{"v":"@proteinjs/user-ui/InviteRecordFormCustomization","value":{"packageName":"@proteinjs/user-ui","name":"InviteRecordFormCustomization","filePath":"src/form/InviteRecordFormCustomization.tsx","qualifiedName":"@proteinjs/user-ui/InviteRecordFormCustomization","isAbstract":false,"isStatic":false,"visibility":"public","properties":[{"name":"table","type":null,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"public"}],"methods":[{"name":"getFieldLayout","returnType":{"packageName":"","name":"string[] | string[][]","filePath":null,"qualifiedName":"/string[] | string[][]","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"public","parameters":[{"name":"invite","type":{"packageName":"","name":"Invite | undefined","filePath":null,"qualifiedName":"/Invite | undefined","typeParameters":null,"directParents":null}},{"name":"defaultFieldLayout","type":{"packageName":"","name":"string[] | string[][]","filePath":null,"qualifiedName":"/string[] | string[][]","typeParameters":null,"directParents":null}}]},{"name":"getFormButtons","returnType":{"packageName":"","name":"FormButtons<any>","filePath":null,"qualifiedName":"/FormButtons<any>","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"public","parameters":[{"name":"invite","type":{"packageName":"","name":"Invite | undefined","filePath":null,"qualifiedName":"/Invite | undefined","typeParameters":null,"directParents":null}},{"name":"defaultFormButtons","type":{"packageName":"","name":"FormButtons<any>","filePath":null,"qualifiedName":"/FormButtons<any>","typeParameters":null,"directParents":null}}]},{"name":"sendButton","returnType":{"packageName":"","name":"FormButton<any>","filePath":null,"qualifiedName":"/FormButton<any>","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"private","parameters":[{"name":"invite","type":{"packageName":"","name":"Invite | undefined","filePath":null,"qualifiedName":"/Invite | undefined","typeParameters":null,"directParents":null}}]},{"name":"revokeButton","returnType":{"packageName":"","name":"FormButton<any>","filePath":null,"qualifiedName":"/FormButton<any>","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"private","parameters":[{"name":"invite","type":{"packageName":"","name":"Invite | undefined","filePath":null,"qualifiedName":"/Invite | undefined","typeParameters":null,"directParents":null}}]},{"name":"canManageUsers","returnType":{"packageName":"","name":"boolean","filePath":null,"qualifiedName":"/boolean","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"private","parameters":[]}],"typeParameters":[],"directParentInterfaces":[],"directParentClasses":[{"packageName":"@proteinjs/db-ui","name":"RecordFormCustomization","filePath":null,"qualifiedName":"@proteinjs/db-ui/RecordFormCustomization","isAbstract":false,"isStatic":false,"visibility":"public","properties":[],"methods":[],"typeParameters":[],"directParentInterfaces":[],"directParentClasses":[]}],"sourceType":2}},{"v":"@proteinjs/db-ui/RecordFormCustomization"},{"v":"@proteinjs/user-ui/forgotPasswordPage","value":{"packageName":"@proteinjs/user-ui","name":"forgotPasswordPage","filePath":"src/pages/ForgotPassword.tsx","qualifiedName":"@proteinjs/user-ui/forgotPasswordPage","type":{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":[{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":null}]},"isExported":true,"isConst":true,"sourceType":0}},{"v":"@proteinjs/ui/Page"},{"v":"@proteinjs/user-ui/loginPage","value":{"packageName":"@proteinjs/user-ui","name":"loginPage","filePath":"src/pages/Login.tsx","qualifiedName":"@proteinjs/user-ui/loginPage","type":{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":[{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":null}]},"isExported":true,"isConst":true,"sourceType":0}},{"v":"@proteinjs/user-ui/passwordResetPage","value":{"packageName":"@proteinjs/user-ui","name":"passwordResetPage","filePath":"src/pages/PasswordReset.tsx","qualifiedName":"@proteinjs/user-ui/passwordResetPage","type":{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":[{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":null}]},"isExported":true,"isConst":true,"sourceType":0}},{"v":"@proteinjs/user-ui/signupPage","value":{"packageName":"@proteinjs/user-ui","name":"signupPage","filePath":"src/pages/Signup.tsx","qualifiedName":"@proteinjs/user-ui/signupPage","type":{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":[{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":null}]},"isExported":true,"isConst":true,"sourceType":0}}],"edges":[{"v":"@proteinjs/user-ui/InviteRecordFormCustomization","w":"@proteinjs/db-ui/RecordFormCustomization","value":"extends class"},{"v":"@proteinjs/user-ui/forgotPasswordPage","w":"@proteinjs/ui/Page","value":"has type"},{"v":"@proteinjs/user-ui/loginPage","w":"@proteinjs/ui/Page","value":"has type"},{"v":"@proteinjs/user-ui/passwordResetPage","w":"@proteinjs/ui/Page","value":"has type"},{"v":"@proteinjs/user-ui/signupPage","w":"@proteinjs/ui/Page","value":"has type"}]}';
12
+ '{"options":{"directed":true,"multigraph":false,"compound":false},"nodes":[{"v":"/Omit"},{"v":"@proteinjs/user-ui/InviteRecordFormCustomization","value":{"packageName":"@proteinjs/user-ui","name":"InviteRecordFormCustomization","filePath":"src/form/InviteRecordFormCustomization.tsx","qualifiedName":"@proteinjs/user-ui/InviteRecordFormCustomization","isAbstract":false,"isStatic":false,"visibility":"public","properties":[{"name":"table","type":null,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"public"}],"methods":[{"name":"getFieldLayout","returnType":{"packageName":"","name":"string[] | string[][]","filePath":null,"qualifiedName":"/string[] | string[][]","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"public","parameters":[{"name":"invite","type":{"packageName":"","name":"Invite | undefined","filePath":null,"qualifiedName":"/Invite | undefined","typeParameters":null,"directParents":null}},{"name":"defaultFieldLayout","type":{"packageName":"","name":"string[] | string[][]","filePath":null,"qualifiedName":"/string[] | string[][]","typeParameters":null,"directParents":null}}]},{"name":"getFormButtons","returnType":{"packageName":"","name":"FormButtons<any>","filePath":null,"qualifiedName":"/FormButtons<any>","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"public","parameters":[{"name":"invite","type":{"packageName":"","name":"Invite | undefined","filePath":null,"qualifiedName":"/Invite | undefined","typeParameters":null,"directParents":null}},{"name":"defaultFormButtons","type":{"packageName":"","name":"FormButtons<any>","filePath":null,"qualifiedName":"/FormButtons<any>","typeParameters":null,"directParents":null}}]},{"name":"sendButton","returnType":{"packageName":"","name":"FormButton<any>","filePath":null,"qualifiedName":"/FormButton<any>","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"private","parameters":[{"name":"invite","type":{"packageName":"","name":"Invite | undefined","filePath":null,"qualifiedName":"/Invite | undefined","typeParameters":null,"directParents":null}}]},{"name":"revokeButton","returnType":{"packageName":"","name":"FormButton<any>","filePath":null,"qualifiedName":"/FormButton<any>","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"private","parameters":[{"name":"invite","type":{"packageName":"","name":"Invite | undefined","filePath":null,"qualifiedName":"/Invite | undefined","typeParameters":null,"directParents":null}}]},{"name":"canManageUsers","returnType":{"packageName":"","name":"boolean","filePath":null,"qualifiedName":"/boolean","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"private","parameters":[]}],"typeParameters":[],"directParentInterfaces":[],"directParentClasses":[{"packageName":"@proteinjs/db-ui","name":"RecordFormCustomization","filePath":null,"qualifiedName":"@proteinjs/db-ui/RecordFormCustomization","isAbstract":false,"isStatic":false,"visibility":"public","properties":[],"methods":[],"typeParameters":[],"directParentInterfaces":[],"directParentClasses":[]}],"sourceType":2}},{"v":"@proteinjs/db-ui/RecordFormCustomization"},{"v":"@proteinjs/user-ui/UserRecordFormCustomization","value":{"packageName":"@proteinjs/user-ui","name":"UserRecordFormCustomization","filePath":"src/form/UserRecordFormCustomization.tsx","qualifiedName":"@proteinjs/user-ui/UserRecordFormCustomization","isAbstract":false,"isStatic":false,"visibility":"public","properties":[{"name":"table","type":null,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"public"}],"methods":[{"name":"getFieldRenderer","returnType":{"packageName":"","name":"RecordFormFieldRenderer<User> | undefined","filePath":null,"qualifiedName":"/RecordFormFieldRenderer<User> | undefined","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"public","parameters":[{"name":"fieldName","type":{"packageName":"","name":"string","filePath":null,"qualifiedName":"/string","typeParameters":null,"directParents":null}},{"name":"user","type":{"packageName":"@proteinjs/user","name":"User","filePath":null,"qualifiedName":"@proteinjs/user/User","typeParameters":null,"directParents":null}}]},{"name":"getFieldLayout","returnType":{"packageName":"","name":"string[] | string[][]","filePath":null,"qualifiedName":"/string[] | string[][]","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"public","parameters":[{"name":"user","type":{"packageName":"","name":"User | undefined","filePath":null,"qualifiedName":"/User | undefined","typeParameters":null,"directParents":null}},{"name":"defaultFieldLayout","type":{"packageName":"","name":"string[] | string[][]","filePath":null,"qualifiedName":"/string[] | string[][]","typeParameters":null,"directParents":null}}]},{"name":"asRows","returnType":{"packageName":"","name":"string[][]","filePath":null,"qualifiedName":"/string[][]","typeParameters":null,"directParents":null},"isAsync":false,"isOptional":false,"isAbstract":false,"isStatic":false,"visibility":"private","parameters":[{"name":"layout","type":{"packageName":"","name":"string[] | string[][]","filePath":null,"qualifiedName":"/string[] | string[][]","typeParameters":null,"directParents":null}}]}],"typeParameters":[],"directParentInterfaces":[],"directParentClasses":[{"packageName":"@proteinjs/db-ui","name":"RecordFormCustomization","filePath":null,"qualifiedName":"@proteinjs/db-ui/RecordFormCustomization","isAbstract":false,"isStatic":false,"visibility":"public","properties":[],"methods":[],"typeParameters":[],"directParentInterfaces":[],"directParentClasses":[]}],"sourceType":2}},{"v":"@proteinjs/user-ui/forgotPasswordPage","value":{"packageName":"@proteinjs/user-ui","name":"forgotPasswordPage","filePath":"src/pages/ForgotPassword.tsx","qualifiedName":"@proteinjs/user-ui/forgotPasswordPage","type":{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":[{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":null}]},"isExported":true,"isConst":true,"sourceType":0}},{"v":"@proteinjs/ui/Page"},{"v":"@proteinjs/user-ui/loginPage","value":{"packageName":"@proteinjs/user-ui","name":"loginPage","filePath":"src/pages/Login.tsx","qualifiedName":"@proteinjs/user-ui/loginPage","type":{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":[{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":null}]},"isExported":true,"isConst":true,"sourceType":0}},{"v":"@proteinjs/user-ui/passwordResetPage","value":{"packageName":"@proteinjs/user-ui","name":"passwordResetPage","filePath":"src/pages/PasswordReset.tsx","qualifiedName":"@proteinjs/user-ui/passwordResetPage","type":{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":[{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":null}]},"isExported":true,"isConst":true,"sourceType":0}},{"v":"@proteinjs/user-ui/signupPage","value":{"packageName":"@proteinjs/user-ui","name":"signupPage","filePath":"src/pages/Signup.tsx","qualifiedName":"@proteinjs/user-ui/signupPage","type":{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":[{"packageName":"@proteinjs/ui","name":"Page","filePath":null,"qualifiedName":"@proteinjs/ui/Page","typeParameters":[],"directParents":null}]},"isExported":true,"isConst":true,"sourceType":0}}],"edges":[{"v":"@proteinjs/user-ui/InviteRecordFormCustomization","w":"@proteinjs/db-ui/RecordFormCustomization","value":"extends class"},{"v":"@proteinjs/user-ui/UserRecordFormCustomization","w":"@proteinjs/db-ui/RecordFormCustomization","value":"extends class"},{"v":"@proteinjs/user-ui/forgotPasswordPage","w":"@proteinjs/ui/Page","value":"has type"},{"v":"@proteinjs/user-ui/loginPage","w":"@proteinjs/ui/Page","value":"has type"},{"v":"@proteinjs/user-ui/passwordResetPage","w":"@proteinjs/ui/Page","value":"has type"},{"v":"@proteinjs/user-ui/signupPage","w":"@proteinjs/ui/Page","value":"has type"}]}';
13
13
 
14
14
  /** Generate Source Links */
15
15
 
16
16
  import { InviteRecordFormCustomization } from '../src/form/InviteRecordFormCustomization';
17
+ import { UserRecordFormCustomization } from '../src/form/UserRecordFormCustomization';
17
18
  import { forgotPasswordPage } from '../src/pages/ForgotPassword';
18
19
  import { loginPage } from '../src/pages/Login';
19
20
  import { passwordResetPage } from '../src/pages/PasswordReset';
@@ -21,6 +22,7 @@ import { signupPage } from '../src/pages/Signup';
21
22
 
22
23
  const sourceLinks = {
23
24
  '@proteinjs/user-ui/InviteRecordFormCustomization': InviteRecordFormCustomization,
25
+ '@proteinjs/user-ui/UserRecordFormCustomization': UserRecordFormCustomization,
24
26
  '@proteinjs/user-ui/forgotPasswordPage': forgotPasswordPage,
25
27
  '@proteinjs/user-ui/loginPage': loginPage,
26
28
  '@proteinjs/user-ui/passwordResetPage': passwordResetPage,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@proteinjs/user-ui",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "User ui components",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -29,7 +29,7 @@
29
29
  "@proteinjs/reflection": "^1.2.0",
30
30
  "@proteinjs/server-api": "^3.0.11",
31
31
  "@proteinjs/ui": "^4.5.0",
32
- "@proteinjs/user": "^1.12.0",
32
+ "@proteinjs/user": "^1.13.0",
33
33
  "@proteinjs/util": "^1.6.1",
34
34
  "moment": "2.29.4",
35
35
  "react": "18.2.0",
@@ -56,5 +56,5 @@
56
56
  },
57
57
  "main": "./dist/generated/index.js",
58
58
  "types": "./dist/generated/index.d.ts",
59
- "gitHead": "96ebc933680809c62b8c55bb14604d85a80912a9"
59
+ "gitHead": "fd6695114449df3a990504f37aab15e4342240cf"
60
60
  }
@@ -0,0 +1,54 @@
1
+ import { RecordFormCustomization, RecordFormFieldRenderer } from '@proteinjs/db-ui';
2
+ import { tables, User } from '@proteinjs/user';
3
+ import { UserRolesField } from './UserRolesField';
4
+ import { UserStatusField } from './UserStatusField';
5
+
6
+ /**
7
+ * Makes the user record form tell the truth about its two service-owned columns:
8
+ * - `roles` is an ArrayColumn the default form hides; it renders as chips of the held roles with
9
+ * grant/revoke through `RolesService` (the one audited write path) for holders of the 'roles'
10
+ * permission — see `UserRolesField`;
11
+ * - `status` is written only by SetUserStatus; it renders read-only instead of as an editable box
12
+ * whose edits the form's save would silently drop — see `UserStatusField`.
13
+ */
14
+ export class UserRecordFormCustomization extends RecordFormCustomization {
15
+ public table = tables.User;
16
+
17
+ getFieldRenderer(fieldName: string, user: User): RecordFormFieldRenderer<User> | undefined {
18
+ if (fieldName === 'roles') {
19
+ return UserRolesField;
20
+ }
21
+
22
+ if (fieldName === 'status') {
23
+ return UserStatusField;
24
+ }
25
+
26
+ return undefined;
27
+ }
28
+
29
+ /**
30
+ * Roles get their own full-width row right after the identity row: chips plus a grant control
31
+ * need the width, and managing access is the main reason to open a user record. The rest of the
32
+ * fields re-pair so no row is left with an orphan.
33
+ */
34
+ getFieldLayout(user: User | undefined, defaultFieldLayout: string[] | string[][]): string[] | string[][] {
35
+ if (!user) {
36
+ return defaultFieldLayout;
37
+ }
38
+
39
+ const rows = this.asRows(defaultFieldLayout);
40
+ const rowWidth = Math.max(...rows.map((row) => row.length));
41
+ const fields = ([] as string[]).concat(...rows).filter((field) => field !== 'roles');
42
+ const identityRow = fields.splice(0, Math.min(rowWidth, fields.length));
43
+ const layout: string[][] = [identityRow, ['roles']];
44
+ for (let i = 0; i < fields.length; i += rowWidth) {
45
+ layout.push(fields.slice(i, i + rowWidth));
46
+ }
47
+
48
+ return layout;
49
+ }
50
+
51
+ private asRows(layout: string[] | string[][]): string[][] {
52
+ return layout.map((row) => (Array.isArray(row) ? row : [row]));
53
+ }
54
+ }
@@ -0,0 +1,96 @@
1
+ import React from 'react';
2
+ import { Chip, FormHelperText, ListItemText, Menu, MenuItem, Stack, Typography } from '@mui/material';
3
+ import AddIcon from '@mui/icons-material/Add';
4
+ import { RecordFormFieldProps } from '@proteinjs/db-ui';
5
+ import { getRolesService, RoleCatalogEntry, RolesCatalog, User, UserAuth, USER_PERMISSIONS } from '@proteinjs/user';
6
+
7
+ /**
8
+ * The `user.roles` slot on the user record form: chips of the held roles, and — for a holder of
9
+ * the 'roles' permission — a grant control fed by the roles catalog plus a revoke on each chip.
10
+ * Every change goes through `RolesService` (the one write path, audited per change) and then
11
+ * reloads the record, so the chips show what is stored rather than what was asked.
12
+ *
13
+ * Read-only for everyone else, and for machine accounts regardless of permission: their roles
14
+ * are declared in code and reverted to the declaration on every boot (the service refuses the
15
+ * write too; the control just doesn't offer what can only fail). The break-glass role is never
16
+ * in the pick-list — it is held by nobody day-to-day and is granted by bootstrap, not from here.
17
+ */
18
+ export function UserRolesField({ record: user, value, label, reload }: RecordFormFieldProps<User, string[] | null>) {
19
+ const heldRoles = value ?? [];
20
+ const isMachineAccount = user.isLoadedFromSource === true;
21
+ const canManage = UserAuth.hasPermission(USER_PERMISSIONS.roles) && !isMachineAccount;
22
+ const grantable = RolesCatalog.getEntries().filter((entry) => !entry.breakGlass && !heldRoles.includes(entry.role));
23
+ const [menuAnchor, setMenuAnchor] = React.useState<HTMLElement | null>(null);
24
+ const [inFlight, setInFlight] = React.useState(false);
25
+ const [error, setError] = React.useState<string>();
26
+
27
+ const change = async (write: () => Promise<void>) => {
28
+ setMenuAnchor(null);
29
+ setInFlight(true);
30
+ setError(undefined);
31
+ try {
32
+ await write();
33
+ await reload();
34
+ } catch (e: any) {
35
+ setError(e.message);
36
+ } finally {
37
+ setInFlight(false);
38
+ }
39
+ };
40
+
41
+ const grant = (entry: RoleCatalogEntry) => change(() => getRolesService().grantRole(user.id, entry.role));
42
+ const revoke = (role: string) => change(() => getRolesService().revokeRole(user.id, role));
43
+
44
+ return (
45
+ <Stack spacing={0.5} data-user-roles>
46
+ <Typography variant='caption' color='text.secondary'>
47
+ {label}
48
+ </Typography>
49
+ <Stack direction='row' sx={{ flexWrap: 'wrap', gap: 1, alignItems: 'center', minHeight: 32 }}>
50
+ {heldRoles.map((role) => (
51
+ <Chip
52
+ key={role}
53
+ label={role}
54
+ title={RolesCatalog.getEntry(role)?.description}
55
+ data-role-chip
56
+ disabled={inFlight}
57
+ onDelete={canManage ? () => revoke(role) : undefined}
58
+ />
59
+ ))}
60
+ {heldRoles.length === 0 && !canManage && (
61
+ <Typography variant='body2' color='text.secondary'>
62
+ None
63
+ </Typography>
64
+ )}
65
+ {canManage && grantable.length > 0 && (
66
+ <Chip
67
+ label='Grant role'
68
+ icon={<AddIcon />}
69
+ variant='outlined'
70
+ clickable
71
+ data-grant-role
72
+ disabled={inFlight}
73
+ onClick={(event) => setMenuAnchor(event.currentTarget)}
74
+ />
75
+ )}
76
+ </Stack>
77
+ {/* Descriptions are sentences: a capped paper + wrapping items keep the list inside the viewport on a phone */}
78
+ <Menu
79
+ open={!!menuAnchor}
80
+ anchorEl={menuAnchor}
81
+ onClose={() => setMenuAnchor(null)}
82
+ PaperProps={{ sx: { maxWidth: 360 } }}
83
+ >
84
+ {grantable.map((entry) => (
85
+ <MenuItem key={entry.role} onClick={() => grant(entry)} sx={{ whiteSpace: 'normal' }}>
86
+ <ListItemText primary={entry.role} secondary={entry.description} />
87
+ </MenuItem>
88
+ ))}
89
+ </Menu>
90
+ {isMachineAccount && (
91
+ <FormHelperText>Declared in code — a machine account's roles change with its declaration.</FormHelperText>
92
+ )}
93
+ {error && <FormHelperText error>{error}</FormHelperText>}
94
+ </Stack>
95
+ );
96
+ }
@@ -0,0 +1,30 @@
1
+ import React from 'react';
2
+ import { Chip, Stack, Typography } from '@mui/material';
3
+ import { RecordFormFieldProps } from '@proteinjs/db-ui';
4
+ import { User, UserStatus } from '@proteinjs/user';
5
+
6
+ /**
7
+ * The `user.status` slot on the user record form: the account's standing, read-only. Its only
8
+ * writer is the SetUserStatus service (audited per change); an editable box here would take edits
9
+ * the form's save silently drops. A null status (rows predating the column) reads as active —
10
+ * the same reading every gate applies.
11
+ */
12
+ export function UserStatusField({ value, label }: RecordFormFieldProps<User, UserStatus | null | undefined>) {
13
+ const status: UserStatus = value ?? 'active';
14
+
15
+ return (
16
+ <Stack spacing={0.5} data-user-status>
17
+ <Typography variant='caption' color='text.secondary'>
18
+ {label}
19
+ </Typography>
20
+ <Stack direction='row' sx={{ alignItems: 'center', minHeight: 32 }}>
21
+ <Chip
22
+ label={status === 'deactivated' ? 'Deactivated' : 'Active'}
23
+ variant='outlined'
24
+ color={status === 'deactivated' ? 'default' : 'success'}
25
+ size='small'
26
+ />
27
+ </Stack>
28
+ </Stack>
29
+ );
30
+ }
@@ -0,0 +1,242 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ * @jest-environment-options {"customExportConditions": ["node", "node-addons"]}
4
+ *
5
+ * The user record form presents the two service-owned columns instead of hiding or faking them:
6
+ * - `roles` (an ArrayColumn, hidden by the default form — the founder opened the user form to
7
+ * change roles and found no roles at all) renders as chips of the held roles; a holder of the
8
+ * 'roles' permission also gets a grant control fed by the roles catalog and a revoke on each
9
+ * chip. Both write through `RolesService` — the one audited write path — and then reload the
10
+ * record, so the chips show what is stored, not what was asked;
11
+ * - `status` renders read-only (its only writer is SetUserStatus) rather than as an editable box
12
+ * the form's save would silently drop.
13
+ *
14
+ * `UserAuth` reads from a static repo; stubbing it directly is how the invite customization test
15
+ * and the server-side authz tests do it.
16
+ */
17
+ import React from 'react';
18
+ import { createRoot, Root } from 'react-dom/client';
19
+ import { act } from 'react-dom/test-utils';
20
+ import { Column } from '@proteinjs/db';
21
+ import { RecordFormFieldProps } from '@proteinjs/db-ui';
22
+ import { RoleCatalogEntry, RolesCatalog, tables, User, UserAuth } from '@proteinjs/user';
23
+ import { UserRecordFormCustomization } from '../src/form/UserRecordFormCustomization';
24
+
25
+ declare global {
26
+ // eslint-disable-next-line no-var
27
+ var IS_REACT_ACT_ENVIRONMENT: boolean;
28
+ }
29
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
30
+
31
+ /** The stored user row the (stubbed) Roles service writes and `reload` reads back. */
32
+ let stored: User;
33
+
34
+ const rolesService = {
35
+ grantRole: jest.fn(async (userId: string, role: string) => {
36
+ stored = { ...stored, roles: [...(stored.roles ?? []), role] };
37
+ }),
38
+ revokeRole: jest.fn(async (userId: string, role: string) => {
39
+ stored = { ...stored, roles: (stored.roles ?? []).filter((held) => held !== role) };
40
+ }),
41
+ };
42
+
43
+ jest.mock('@proteinjs/user', () => ({
44
+ ...jest.requireActual('@proteinjs/user'),
45
+ getRolesService: () => rolesService,
46
+ }));
47
+
48
+ type UserAuthInternals = {
49
+ userRepo?: { getUser: () => { email: string; roles: string[] } };
50
+ permissionRolesMapping?: { getRoles: (permission: string) => string[] | undefined };
51
+ };
52
+
53
+ const setCallerRoles = (roles: string[]) => {
54
+ (UserAuth as unknown as UserAuthInternals).userRepo = {
55
+ getUser: () => ({ email: 'caller@n3xa.io', roles }),
56
+ };
57
+ };
58
+
59
+ const setMapping = (mapping: { [permission: string]: string[] }) => {
60
+ (UserAuth as unknown as UserAuthInternals).permissionRolesMapping = {
61
+ getRoles: (permission: string) => mapping[permission],
62
+ };
63
+ };
64
+
65
+ const catalog: RoleCatalogEntry[] = [
66
+ { role: 'admin', description: 'Break-glass superuser.', breakGlass: true },
67
+ { role: 'ops', description: 'Runs the product: tickets, issues, cost.' },
68
+ { role: 'dev', description: 'Engineering surfaces.' },
69
+ ];
70
+
71
+ const userRecord = (overrides: Partial<User> = {}): User =>
72
+ ({
73
+ id: 'user-1',
74
+ name: 'Ada',
75
+ email: 'ada@n3xa.io',
76
+ roles: ['ops'],
77
+ status: 'active',
78
+ ...overrides,
79
+ }) as User;
80
+
81
+ describe('User record form customization', () => {
82
+ let container: HTMLDivElement;
83
+ let root: Root;
84
+ const customization = new UserRecordFormCustomization();
85
+
86
+ beforeEach(() => {
87
+ jest.clearAllMocks();
88
+ jest.spyOn(RolesCatalog, 'getEntries').mockReturnValue(catalog);
89
+ setCallerRoles(['admin']);
90
+ stored = userRecord();
91
+ container = document.createElement('div');
92
+ document.body.appendChild(container);
93
+ root = createRoot(container);
94
+ });
95
+
96
+ afterEach(async () => {
97
+ await act(async () => root.unmount());
98
+ container.remove();
99
+ (UserAuth as unknown as UserAuthInternals).userRepo = undefined;
100
+ (UserAuth as unknown as UserAuthInternals).permissionRolesMapping = undefined;
101
+ jest.restoreAllMocks();
102
+ });
103
+
104
+ /**
105
+ * Renders the field the way RecordForm's slot does: value from the record; reload re-reads the
106
+ * stored row and re-renders. Reload runs inside the click's act scope, so it renders bare —
107
+ * a nested act would overlap the outer one.
108
+ */
109
+ const renderField = async (fieldName: 'roles' | 'status') => {
110
+ const Renderer = customization.getFieldRenderer(fieldName, stored);
111
+ if (!Renderer) {
112
+ throw new Error(`No renderer for ${fieldName}`);
113
+ }
114
+
115
+ const element = () => {
116
+ const props: RecordFormFieldProps<User> = {
117
+ table: tables.User,
118
+ column: (tables.User.columns as any)[fieldName] as Column<User, any>,
119
+ fieldName,
120
+ label: fieldName === 'roles' ? 'Roles' : 'Status',
121
+ record: stored,
122
+ value: (stored as any)[fieldName],
123
+ reload: async () => {
124
+ root.render(element());
125
+ },
126
+ };
127
+ return <Renderer {...props} />;
128
+ };
129
+ await act(async () => {
130
+ root.render(element());
131
+ });
132
+ };
133
+
134
+ const chips = () => Array.from(document.querySelectorAll('[data-role-chip]')).map((chip) => chip.textContent);
135
+ const grantControl = () => document.querySelector('[data-grant-role]');
136
+ const revokeButtons = () => Array.from(document.querySelectorAll('[data-role-chip] [data-testid="CancelIcon"]'));
137
+
138
+ const click = async (element: Element) => {
139
+ await act(async () => {
140
+ element.dispatchEvent(new MouseEvent('click', { bubbles: true }));
141
+ });
142
+ await act(async () => {
143
+ await Promise.resolve();
144
+ });
145
+ };
146
+
147
+ it('renders the held roles as chips', async () => {
148
+ stored = userRecord({ roles: ['ops', 'dev'] });
149
+ await renderField('roles');
150
+
151
+ expect(chips()).toEqual(['ops', 'dev']);
152
+ });
153
+
154
+ it('offers the grant control and revoke only to a holder of the roles permission', async () => {
155
+ await renderField('roles');
156
+ expect(grantControl()).not.toBeNull();
157
+ expect(revokeButtons()).toHaveLength(1);
158
+
159
+ setCallerRoles([]);
160
+ await renderField('roles');
161
+ expect(chips()).toEqual(['ops']);
162
+ expect(grantControl()).toBeNull();
163
+ expect(revokeButtons()).toHaveLength(0);
164
+
165
+ setCallerRoles(['support']);
166
+ setMapping({ roles: ['support'] });
167
+ await renderField('roles');
168
+ expect(grantControl()).not.toBeNull();
169
+ });
170
+
171
+ it('grants through the Roles service and shows the stored roles afterwards', async () => {
172
+ await renderField('roles');
173
+
174
+ await click(grantControl()!);
175
+ // The pick-list is the catalog minus what is already held — and never the break-glass role
176
+ const options = Array.from(document.querySelectorAll('[role="menuitem"]'));
177
+ expect(options.map((item) => item.querySelector('.MuiListItemText-primary')?.textContent)).toEqual(['dev']);
178
+ expect(options[0].textContent).toContain('Engineering surfaces.');
179
+ await click(options[0]);
180
+
181
+ expect(rolesService.grantRole).toHaveBeenCalledWith('user-1', 'dev');
182
+ expect(stored.roles).toEqual(['ops', 'dev']);
183
+ expect(chips()).toEqual(['ops', 'dev']);
184
+ });
185
+
186
+ it('revokes through the Roles service from the chip', async () => {
187
+ await renderField('roles');
188
+
189
+ await click(revokeButtons()[0]);
190
+
191
+ expect(rolesService.revokeRole).toHaveBeenCalledWith('user-1', 'ops');
192
+ expect(stored.roles).toEqual([]);
193
+ expect(chips()).toEqual([]);
194
+ });
195
+
196
+ it('shows a machine account read-only: its roles are declared in code', async () => {
197
+ stored = userRecord({ isLoadedFromSource: true });
198
+ await renderField('roles');
199
+
200
+ expect(chips()).toEqual(['ops']);
201
+ expect(grantControl()).toBeNull();
202
+ expect(revokeButtons()).toHaveLength(0);
203
+ expect(document.body.textContent).toContain('machine account');
204
+ });
205
+
206
+ it('renders status read-only (null reads as active), and leaves every other field to the form', async () => {
207
+ await renderField('status');
208
+ expect(document.body.textContent).toContain('Active');
209
+ expect(document.querySelector('input')).toBeNull();
210
+
211
+ stored = userRecord({ status: 'deactivated' });
212
+ await renderField('status');
213
+ expect(document.body.textContent).toContain('Deactivated');
214
+
215
+ stored = userRecord({ status: null });
216
+ await renderField('status');
217
+ expect(document.body.textContent).toContain('Active');
218
+
219
+ for (const fieldName of ['name', 'email', 'emailVerified', 'invitedBy']) {
220
+ expect(customization.getFieldRenderer(fieldName, stored)).toBeUndefined();
221
+ }
222
+ });
223
+
224
+ it('gives roles its own full-width row after the identity row', () => {
225
+ const defaultLayout = [
226
+ ['name', 'email'],
227
+ ['password', 'emailVerified'],
228
+ ['roles', 'invitedBy'],
229
+ ['status', 'created'],
230
+ ['updated'],
231
+ ];
232
+ expect(customization.getFieldLayout(userRecord(), defaultLayout)).toEqual([
233
+ ['name', 'email'],
234
+ ['roles'],
235
+ ['password', 'emailVerified'],
236
+ ['invitedBy', 'status'],
237
+ ['created', 'updated'],
238
+ ]);
239
+ // The new-record form has no roles to show; its layout is untouched
240
+ expect(customization.getFieldLayout(undefined, ['name', 'email'])).toEqual(['name', 'email']);
241
+ });
242
+ });
@@ -0,0 +1,128 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ * @jest-environment-options {"customExportConditions": ["node", "node-addons"]}
4
+ *
5
+ * The admin AccessGrants table renders `principal` as the referenced USER's name, linked to
6
+ * their record form — the same ReferenceCellValue surface the Users/Invites tables use for
7
+ * `invitedBy`. What this suite binds is the REAL AccessGrantTable declaration reaching it:
8
+ * rows are built the way the db layer builds them — `deserialize` stamps the COLUMN
9
+ * DECLARATION's reference-table name onto every read-back Reference — so a declaration naming
10
+ * the class (`'UserTable'`) instead of the table (`'user'`) fails these assertions (the
11
+ * resolver finds no such table; the link would point at `?table=UserTable`).
12
+ */
13
+ import React from 'react';
14
+ import { createRoot, Root } from 'react-dom/client';
15
+ import { act } from 'react-dom/test-utils';
16
+ import { MemoryRouter } from 'react-router-dom';
17
+ import { QueryClient, QueryClientProvider } from 'react-query';
18
+ import { StaticTableLoader } from '@proteinjs/ui';
19
+
20
+ // ReferenceCellValue resolves through Reference.get(); the fake resolves the principal to a
21
+ // named user record so the enrichment path is observable without a db. Note the fake only
22
+ // answers for the real table name 'user' — a declaration-corrupted table name gets nothing.
23
+ jest.mock('@proteinjs/db', () => {
24
+ const actual = jest.requireActual('@proteinjs/db');
25
+ class FakeReference {
26
+ constructor(
27
+ public _table: string,
28
+ public _id?: string
29
+ ) {}
30
+ async get() {
31
+ if (this._table === 'user' && this._id === 'principal-1') {
32
+ return { id: 'principal-1', name: 'Priya Principal' };
33
+ }
34
+ throw new Error('not visible');
35
+ }
36
+ }
37
+ return { ...actual, Reference: FakeReference };
38
+ });
39
+
40
+ import { Reference, ReferenceColumn } from '@proteinjs/db';
41
+ import { RecordTable, clearReferenceNameCache } from '@proteinjs/db-ui';
42
+ import { tables, AccessGrant, User } from '@proteinjs/user';
43
+
44
+ declare global {
45
+ // eslint-disable-next-line no-var
46
+ var IS_REACT_ACT_ENVIRONMENT: boolean;
47
+ }
48
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
49
+
50
+ class StubIntersectionObserver {
51
+ observe() {}
52
+ unobserve() {}
53
+ disconnect() {}
54
+ }
55
+ (globalThis as any).IntersectionObserver = StubIntersectionObserver;
56
+
57
+ /**
58
+ * The principal reference exactly as the db layer would hand it to the table: the reference's
59
+ * table name comes from the COLUMN DECLARATION (ReferenceColumn.deserialize stamps
60
+ * `this.referenceTable`), never from stored data — stored cells are bare ids.
61
+ */
62
+ const principalReference = () => {
63
+ const principalColumn = tables.AccessGrant.columns.principal as unknown as ReferenceColumn<User>;
64
+ return new Reference<User>(principalColumn.referenceTable, 'principal-1');
65
+ };
66
+
67
+ const grantRow = {
68
+ id: 'grant-1',
69
+ principal: principalReference(),
70
+ resource: new Reference('thought', 'thought-1'),
71
+ resourceTable: 'thought',
72
+ accessLevel: 'read',
73
+ } as unknown as AccessGrant;
74
+
75
+ describe('the admin AccessGrants table renders principal as the linked user', () => {
76
+ let container: HTMLDivElement;
77
+ let root: Root;
78
+ let client: QueryClient;
79
+
80
+ beforeEach(() => {
81
+ clearReferenceNameCache();
82
+ container = document.createElement('div');
83
+ document.body.appendChild(container);
84
+ root = createRoot(container);
85
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, cacheTime: 0 } } });
86
+ });
87
+
88
+ afterEach(() => {
89
+ act(() => root.unmount());
90
+ container.remove();
91
+ });
92
+
93
+ const mount = async (rows: AccessGrant[]) => {
94
+ await act(async () => {
95
+ root.render(
96
+ <QueryClientProvider client={client}>
97
+ <MemoryRouter>
98
+ <RecordTable
99
+ table={tables.AccessGrant}
100
+ tableLoader={
101
+ new StaticTableLoader(rows, { dataKey: `grant-principal-${Math.random()}`, dataQueryKey: 'all' })
102
+ }
103
+ hideButtons
104
+ columns={['accessLevel', 'principal'] as any}
105
+ />
106
+ </MemoryRouter>
107
+ </QueryClientProvider>
108
+ );
109
+ });
110
+ // one macrotask for the name resolution to land
111
+ await act(async () => {
112
+ await new Promise((resolve) => setTimeout(resolve, 0));
113
+ });
114
+ await act(async () => {
115
+ await new Promise((resolve) => setTimeout(resolve, 0));
116
+ });
117
+ };
118
+
119
+ const principalCell = () => container.querySelectorAll('tbody td')[1] as HTMLElement;
120
+
121
+ it('links the principal by name to their user record', async () => {
122
+ await mount([grantRow]);
123
+ const link = principalCell().querySelector('a') as HTMLAnchorElement;
124
+ expect(link).not.toBeNull();
125
+ expect(link.getAttribute('href')).toBe('/record/form?table=user&record=principal-1');
126
+ expect(principalCell().textContent).toBe('Priya Principal');
127
+ });
128
+ });