@aventoapp/framework 0.1.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.
- package/dist/index.js +6 -0
- package/dist/index.js.map +7 -0
- package/dist/native/index.js +2522 -0
- package/dist/native/index.js.map +7 -0
- package/dist/server/index.js +2776 -0
- package/dist/server/index.js.map +7 -0
- package/dist/server/workflow/index.js +537 -0
- package/dist/server/workflow/index.js.map +7 -0
- package/dist/shared/index.js +62 -0
- package/dist/shared/index.js.map +7 -0
- package/dist/web/index.js +7323 -0
- package/dist/web/index.js.map +7 -0
- package/package.json +81 -0
- package/schemas/Workflow.json +14 -0
- package/schemas/WorkflowHistory.json +22 -0
- package/schemas/WorkflowInstance.json +16 -0
- package/schemas/WorkflowState.json +18 -0
- package/schemas/WorkflowTransition.json +27 -0
- package/src/index.js +8 -0
- package/src/native/components/NativeAuthProvider.jsx +249 -0
- package/src/native/components/NativeDetail.jsx +270 -0
- package/src/native/components/NativeForm.jsx +543 -0
- package/src/native/components/NativeGrid.jsx +90 -0
- package/src/native/components/NativeJsonGrid.jsx +213 -0
- package/src/native/components/NativeJsonView.jsx +454 -0
- package/src/native/components/NativeJsonViewContext.js +17 -0
- package/src/native/components/NativeShell.jsx +68 -0
- package/src/native/components/NativeViewComponent.jsx +351 -0
- package/src/native/extensions/NativeExtensionRegistry.js +81 -0
- package/src/native/hooks/useNativeStore.js +72 -0
- package/src/native/index.js +15 -0
- package/src/native/layouts/NativeStackLayout.jsx +30 -0
- package/src/native/layouts/NativeTabLayout.jsx +96 -0
- package/src/native/storage.js +13 -0
- package/src/native/stores/NativeBaseStore.js +348 -0
- package/src/native/stores/NativeStoreContext.jsx +53 -0
- package/src/server/ai/capabilities-routes.js +106 -0
- package/src/server/ai/index.js +1 -0
- package/src/server/cache/MemoryCache.js +153 -0
- package/src/server/cache/index.js +2 -0
- package/src/server/cache/middleware.js +12 -0
- package/src/server/db/index.js +14 -0
- package/src/server/db/mongo.js +137 -0
- package/src/server/db/postgres.js +144 -0
- package/src/server/index.js +38 -0
- package/src/server/middleware/auth.js +682 -0
- package/src/server/middleware/can-flags.js +132 -0
- package/src/server/middleware/entityRoles.js +105 -0
- package/src/server/middleware/index.js +58 -0
- package/src/server/middleware/permissions.js +240 -0
- package/src/server/middleware/tenant.js +203 -0
- package/src/server/realtime/EventBus.js +45 -0
- package/src/server/realtime/WebSocketServer.js +105 -0
- package/src/server/realtime/index.js +3 -0
- package/src/server/realtime/middleware.js +18 -0
- package/src/server/services/email-templates.js +157 -0
- package/src/server/services/email.js +78 -0
- package/src/server/services/index.js +15 -0
- package/src/server/services/storage.js +119 -0
- package/src/server/utils/index.js +16 -0
- package/src/server/utils/paginate.js +65 -0
- package/src/server/utils/query-builder.js +293 -0
- package/src/server/utils/route-loader.js +61 -0
- package/src/server/workflow/WorkflowEngine.js +494 -0
- package/src/server/workflow/index.js +2 -0
- package/src/server/workflow/workflow-routes.js +174 -0
- package/src/shared/index.js +10 -0
- package/src/shared/utils/field-accessor.js +108 -0
- package/src/shared/utils/index.js +7 -0
- package/src/shared/utils/validation-utils.js +83 -0
- package/src/web/components/AppRouter/AppRouter.jsx +130 -0
- package/src/web/components/AppRouter/index.js +1 -0
- package/src/web/components/AppShell/AppShell.jsx +101 -0
- package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -0
- package/src/web/components/AppShell/ShellConfig.js +53 -0
- package/src/web/components/AppShell/index.js +3 -0
- package/src/web/components/AuthProvider.jsx +426 -0
- package/src/web/components/CardList/CardList.jsx +272 -0
- package/src/web/components/CardList/index.js +2 -0
- package/src/web/components/DetailView/DetailView.jsx +281 -0
- package/src/web/components/DetailView/index.js +2 -0
- package/src/web/components/Form/Form.jsx +300 -0
- package/src/web/components/Form/FormField.jsx +226 -0
- package/src/web/components/Form/index.js +3 -0
- package/src/web/components/Grid/Grid.jsx +304 -0
- package/src/web/components/Grid/index.js +2 -0
- package/src/web/components/IconRegistry/IconRegistry.jsx +127 -0
- package/src/web/components/IconRegistry/index.js +1 -0
- package/src/web/components/JsonView/JsonView.jsx +647 -0
- package/src/web/components/JsonView/ViewComponent.jsx +1045 -0
- package/src/web/components/JsonView/ViewToolbar.jsx +141 -0
- package/src/web/components/JsonView/index.js +14 -0
- package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -0
- package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -0
- package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -0
- package/src/web/components/JsonView/layouts/index.js +8 -0
- package/src/web/components/Layout.jsx +265 -0
- package/src/web/components/MobileLayout/MobileLayout.jsx +385 -0
- package/src/web/components/MobileLayout/index.js +1 -0
- package/src/web/components/Navigation/Navigation.jsx +248 -0
- package/src/web/components/Navigation/index.js +1 -0
- package/src/web/components/NotificationProvider.jsx +55 -0
- package/src/web/components/Pagination/InfiniteScroll.jsx +82 -0
- package/src/web/components/Pagination/Pagination.jsx +73 -0
- package/src/web/components/Pagination/index.js +8 -0
- package/src/web/components/SimpleList/SimpleList.jsx +177 -0
- package/src/web/components/SimpleList/index.js +2 -0
- package/src/web/components/TenantProvider.jsx +121 -0
- package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -0
- package/src/web/components/WorkflowActions/index.js +1 -0
- package/src/web/components/WorkflowField/WorkflowField.jsx +176 -0
- package/src/web/components/WorkflowField/index.js +2 -0
- package/src/web/components/WorkflowField/workflowColors.js +32 -0
- package/src/web/components/auth/DevTenantSelector.jsx +90 -0
- package/src/web/components/auth/ForgotPasswordForm.jsx +94 -0
- package/src/web/components/auth/RegisterForm.jsx +168 -0
- package/src/web/components/auth/ResetPasswordForm.jsx +121 -0
- package/src/web/components/auth/VerifyEmailView.jsx +85 -0
- package/src/web/components/auth/index.js +5 -0
- package/src/web/components/index.js +39 -0
- package/src/web/components/layouts/CardListLayout.jsx +68 -0
- package/src/web/components/layouts/FullscreenLayout.jsx +30 -0
- package/src/web/components/layouts/MobileStackLayout.jsx +28 -0
- package/src/web/components/layouts/WizardLayout.jsx +86 -0
- package/src/web/components/layouts/index.js +4 -0
- package/src/web/components/mobile/Badge.jsx +105 -0
- package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -0
- package/src/web/components/mobile/EmptyState.jsx +30 -0
- package/src/web/components/mobile/QuickActionButton.jsx +77 -0
- package/src/web/components/mobile/ServerAutocomplete.jsx +123 -0
- package/src/web/components/mobile/StarRating.jsx +42 -0
- package/src/web/components/mobile/StatCard.jsx +65 -0
- package/src/web/components/mobile/index.js +7 -0
- package/src/web/extensions/ExtensionRegistry.js +79 -0
- package/src/web/extensions/index.js +7 -0
- package/src/web/hooks/index.js +15 -0
- package/src/web/hooks/useApi.js +76 -0
- package/src/web/hooks/useAuth.js +37 -0
- package/src/web/hooks/useDebouncedSave.js +158 -0
- package/src/web/hooks/useIsMobile.js +14 -0
- package/src/web/hooks/useOfflineQueue.js +99 -0
- package/src/web/hooks/useSelectionModel.js +143 -0
- package/src/web/hooks/useServerAutocomplete.js +146 -0
- package/src/web/hooks/useStore.js +107 -0
- package/src/web/hooks/useSubscription.js +130 -0
- package/src/web/hooks/useTenant.js +39 -0
- package/src/web/hooks/useTenantResolver.js +65 -0
- package/src/web/hooks/useUndoRedo.js +77 -0
- package/src/web/hooks/useViews.js +113 -0
- package/src/web/hooks/useWorkflow.js +190 -0
- package/src/web/index.js +117 -0
- package/src/web/stores/BaseStore.js +439 -0
- package/src/web/stores/StoreContext.jsx +93 -0
- package/src/web/stores/index.js +3 -0
- package/src/web/theme/index.js +3 -0
- package/src/web/theme/mui-theme.js +228 -0
- package/src/web/utils/formatTimeAgo.js +22 -0
- package/src/web/utils/index.js +1 -0
- package/src/web/views/ViewRegistry.js +235 -0
- package/src/web/views/index.js +2 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* computeCanFlags
|
|
3
|
+
*
|
|
4
|
+
* Computes a _can capability object for a record given the current user,
|
|
5
|
+
* schema definition, and optionally available workflow transitions.
|
|
6
|
+
*
|
|
7
|
+
* The result is embedded in API responses as { ...record, _can: {...} }.
|
|
8
|
+
* The UI reads these boolean flags to show/hide controls.
|
|
9
|
+
* Permission names NEVER leave the server — the client only sees booleans.
|
|
10
|
+
*
|
|
11
|
+
* Access priority:
|
|
12
|
+
* 1. user.permissions (new system) — strings like 'aircraft.update.any'
|
|
13
|
+
* 2. user.roles + schema.permissions (backward compat) — legacy role arrays
|
|
14
|
+
* 3. If neither is configured: allow (authenticated = allow by default)
|
|
15
|
+
*
|
|
16
|
+
* Ownership scopes (when schema declares `ownership: fieldName`):
|
|
17
|
+
* {prefix}.update.any — can update any record
|
|
18
|
+
* {prefix}.update.own — can update only records they own
|
|
19
|
+
* {prefix}.delete.any / .own — same for delete
|
|
20
|
+
*
|
|
21
|
+
* Future scopes (not yet implemented, documented for extensibility):
|
|
22
|
+
* {prefix}.update.group — can update records belonging to the same group
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {Object} user - req.user (must have .id, optionally .permissions, .roles)
|
|
27
|
+
* @param {Object} schema - Enriched schema (_meta.permissionPrefix, _meta.ownershipField, etc.)
|
|
28
|
+
* @param {Object} [record=null] - The record being evaluated (for ownership checks)
|
|
29
|
+
* @param {Object[]} [availableTransitions=[]] - Transitions already filtered by WorkflowEngine
|
|
30
|
+
* @returns {Object} Capability flags: { read, create, update, delete, [fieldName]: {read,write}, [actionName]: bool }
|
|
31
|
+
*/
|
|
32
|
+
export function computeCanFlags(user, schema, record = null, availableTransitions = []) {
|
|
33
|
+
const perms = user?.permissions || [];
|
|
34
|
+
const roles = user?.roles || [];
|
|
35
|
+
const prefix = schema?._meta?.permissionPrefix;
|
|
36
|
+
const ownerField = schema?._meta?.ownershipField;
|
|
37
|
+
const schemaPerms = schema?.permissions || {};
|
|
38
|
+
|
|
39
|
+
function isOwner() {
|
|
40
|
+
if (!ownerField || !record || !user?.id) return false;
|
|
41
|
+
return String(record[ownerField]) === String(user.id);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Backward compat: check if user has a role in the schema permission list
|
|
45
|
+
function hasLegacyAccess(op) {
|
|
46
|
+
const allowed = schemaPerms[op];
|
|
47
|
+
if (!allowed || allowed.length === 0) return true; // no restriction = allow
|
|
48
|
+
return roles.some(r => allowed.includes(r));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function canOp(op) {
|
|
52
|
+
if (perms.length > 0) {
|
|
53
|
+
// Explicit scoped permissions
|
|
54
|
+
if (perms.includes(`${prefix}.${op}.any`)) return true;
|
|
55
|
+
if (perms.includes(`${prefix}.${op}.own`) && isOwner()) return true;
|
|
56
|
+
// Base permission (implies .any scope)
|
|
57
|
+
if (perms.includes(`${prefix}.${op}`)) return true;
|
|
58
|
+
// Schema permission list may contain permission strings (not roles)
|
|
59
|
+
const schemaList = schemaPerms[op] || [];
|
|
60
|
+
if (schemaList.length > 0 && schemaList.some(p => perms.includes(p))) return true;
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
// Role-based fallback
|
|
64
|
+
return hasLegacyAccess(op);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const flags = {
|
|
68
|
+
read: canOp('read'),
|
|
69
|
+
create: canOp('create'),
|
|
70
|
+
update: canOp('update'),
|
|
71
|
+
delete: canOp('delete')
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
// Field-level flags — only evaluated under the new permission system
|
|
75
|
+
// A field permission is additive restriction: entity access AND field access required.
|
|
76
|
+
if (perms.length > 0) {
|
|
77
|
+
for (const field of (schema?.fields || [])) {
|
|
78
|
+
if (field.permission) {
|
|
79
|
+
const fp = field.permission;
|
|
80
|
+
const canRead = flags.read && perms.includes(`${fp}.read`);
|
|
81
|
+
const canWrite = flags.update && perms.includes(`${fp}.write`);
|
|
82
|
+
// Only emit when the field is more restricted than the entity
|
|
83
|
+
if (!canRead || !canWrite) {
|
|
84
|
+
flags[field.name] = { read: canRead, write: canWrite };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Action flags
|
|
91
|
+
for (const action of (schema?._meta?.actions || [])) {
|
|
92
|
+
if (action.permission) {
|
|
93
|
+
if (perms.length > 0) {
|
|
94
|
+
flags[action.name] = perms.includes(action.permission);
|
|
95
|
+
} else {
|
|
96
|
+
// Backward compat: show action if user can update
|
|
97
|
+
flags[action.name] = flags.update;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Workflow: include names of available transitions (server already filtered by role/permission)
|
|
103
|
+
if (availableTransitions.length > 0) {
|
|
104
|
+
flags._transitions = availableTransitions.map(t => t.name || t.action);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return flags;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Express middleware that wraps res.json to inject _can flags into single-record responses.
|
|
112
|
+
*
|
|
113
|
+
* Usage: router.get('/:id', attachCanFlags(schema), yourHandler)
|
|
114
|
+
*
|
|
115
|
+
* Alternatively, call computeCanFlags() directly in your route handler for more control
|
|
116
|
+
* (e.g., when you need to pass availableTransitions from the workflow engine).
|
|
117
|
+
*
|
|
118
|
+
* @param {Object} schema - Enriched schema object
|
|
119
|
+
*/
|
|
120
|
+
export function attachCanFlags(schema) {
|
|
121
|
+
return (req, res, next) => {
|
|
122
|
+
const originalJson = res.json.bind(res);
|
|
123
|
+
res.json = (data) => {
|
|
124
|
+
if (data && typeof data === 'object' && !Array.isArray(data) && !data.error) {
|
|
125
|
+
const flags = computeCanFlags(req.user, schema, data);
|
|
126
|
+
return originalJson({ ...data, _can: flags });
|
|
127
|
+
}
|
|
128
|
+
return originalJson(data);
|
|
129
|
+
};
|
|
130
|
+
next();
|
|
131
|
+
};
|
|
132
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Entity-scoped roles — generic, reusable by any app.
|
|
3
|
+
*
|
|
4
|
+
* Owns the `user_entity_roles` table schema, creation helper,
|
|
5
|
+
* query helpers, and Express middleware.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Create the `user_entity_roles` table if it doesn't exist.
|
|
10
|
+
* Idempotent — safe to call on every startup.
|
|
11
|
+
*/
|
|
12
|
+
export async function ensureEntityRolesTable(db) {
|
|
13
|
+
await db.query(`
|
|
14
|
+
CREATE TABLE IF NOT EXISTS user_entity_roles (
|
|
15
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
16
|
+
tenant_id UUID NOT NULL REFERENCES tenants(id),
|
|
17
|
+
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
18
|
+
entity_type TEXT NOT NULL,
|
|
19
|
+
entity_id UUID NOT NULL,
|
|
20
|
+
role TEXT NOT NULL,
|
|
21
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
22
|
+
created_by UUID REFERENCES users(id),
|
|
23
|
+
UNIQUE (tenant_id, user_id, entity_type, entity_id, role)
|
|
24
|
+
)
|
|
25
|
+
`);
|
|
26
|
+
|
|
27
|
+
// Indexes (IF NOT EXISTS keeps this idempotent)
|
|
28
|
+
await db.query(`
|
|
29
|
+
CREATE INDEX IF NOT EXISTS idx_uer_user_id ON user_entity_roles (user_id)
|
|
30
|
+
`);
|
|
31
|
+
await db.query(`
|
|
32
|
+
CREATE INDEX IF NOT EXISTS idx_uer_entity ON user_entity_roles (entity_type, entity_id)
|
|
33
|
+
`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Check whether a user holds any of the given roles for a specific entity.
|
|
38
|
+
*
|
|
39
|
+
* @param {object} db – pg pool / client with .query()
|
|
40
|
+
* @param {string} tenantId – tenant UUID
|
|
41
|
+
* @param {string} userId – user UUID
|
|
42
|
+
* @param {string} entityType – e.g. 'course'
|
|
43
|
+
* @param {string} entityId – entity UUID
|
|
44
|
+
* @param {string[]} roles – roles to check (OR logic)
|
|
45
|
+
* @returns {Promise<boolean>}
|
|
46
|
+
*/
|
|
47
|
+
export async function hasEntityRole(db, tenantId, userId, entityType, entityId, roles) {
|
|
48
|
+
const result = await db.query(
|
|
49
|
+
`SELECT 1 FROM user_entity_roles
|
|
50
|
+
WHERE tenant_id = $1
|
|
51
|
+
AND user_id = $2
|
|
52
|
+
AND entity_type = $3
|
|
53
|
+
AND entity_id = $4
|
|
54
|
+
AND role = ANY($5)
|
|
55
|
+
LIMIT 1`,
|
|
56
|
+
[tenantId, userId, entityType, entityId, roles]
|
|
57
|
+
);
|
|
58
|
+
return result.rows.length > 0;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Express middleware factory.
|
|
63
|
+
*
|
|
64
|
+
* Passes if the user has any of `globalRoles` on `req.user.roles`,
|
|
65
|
+
* OR if the user has a matching entity role in `user_entity_roles`.
|
|
66
|
+
*
|
|
67
|
+
* @param {string} entityType – e.g. 'course'
|
|
68
|
+
* @param {(req) => Promise<string>} getEntityId – extracts entity ID from the request
|
|
69
|
+
* @param {...string} globalRoles – global roles that also grant access
|
|
70
|
+
* @returns {Function} Express middleware
|
|
71
|
+
*/
|
|
72
|
+
export function requireEntityRoleOr(entityType, getEntityId, ...globalRoles) {
|
|
73
|
+
return async (req, res, next) => {
|
|
74
|
+
try {
|
|
75
|
+
const userRoles = req.user?.roles || [];
|
|
76
|
+
|
|
77
|
+
// Check global roles first (fast path)
|
|
78
|
+
if (globalRoles.some(r => userRoles.includes(r))) {
|
|
79
|
+
return next();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Resolve entity ID and check entity-scoped roles
|
|
83
|
+
const entityId = await getEntityId(req);
|
|
84
|
+
if (!entityId) {
|
|
85
|
+
return res.status(403).json({ error: 'Insufficient permissions' });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const has = await hasEntityRole(
|
|
89
|
+
req.db,
|
|
90
|
+
req.tenant.id,
|
|
91
|
+
req.user.id,
|
|
92
|
+
entityType,
|
|
93
|
+
entityId,
|
|
94
|
+
[entityType.toUpperCase() + '_MAINTAINER'] // convention: COURSE_MAINTAINER, etc.
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
if (has) return next();
|
|
98
|
+
|
|
99
|
+
return res.status(403).json({ error: 'Insufficient permissions' });
|
|
100
|
+
} catch (err) {
|
|
101
|
+
console.error('[requireEntityRoleOr] Error:', err);
|
|
102
|
+
return res.status(500).json({ error: 'Permission check failed' });
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Re-export all from tenant
|
|
2
|
+
export {
|
|
3
|
+
tenantMiddleware,
|
|
4
|
+
requireTenant,
|
|
5
|
+
getTenantId,
|
|
6
|
+
assertTenant,
|
|
7
|
+
isValidUUID,
|
|
8
|
+
createTenantLookupHandler,
|
|
9
|
+
createTenantListHandler
|
|
10
|
+
} from './tenant.js';
|
|
11
|
+
|
|
12
|
+
// Re-export all from auth
|
|
13
|
+
export {
|
|
14
|
+
configurePassport,
|
|
15
|
+
initAuth,
|
|
16
|
+
requireAuth,
|
|
17
|
+
optionalAuth,
|
|
18
|
+
generateToken,
|
|
19
|
+
generateRefreshToken,
|
|
20
|
+
verifyToken,
|
|
21
|
+
hashPassword,
|
|
22
|
+
comparePassword,
|
|
23
|
+
generateSecureToken,
|
|
24
|
+
generateTokenExpiry,
|
|
25
|
+
createLoginHandler,
|
|
26
|
+
createRefreshHandler,
|
|
27
|
+
createRegisterHandler,
|
|
28
|
+
createForgotPasswordHandler,
|
|
29
|
+
createResetPasswordHandler,
|
|
30
|
+
createVerifyEmailHandler
|
|
31
|
+
} from './auth.js';
|
|
32
|
+
|
|
33
|
+
// Re-export all from permissions
|
|
34
|
+
export {
|
|
35
|
+
hasAnyRole,
|
|
36
|
+
hasAllRoles,
|
|
37
|
+
requireRoles,
|
|
38
|
+
requireAllRoles,
|
|
39
|
+
requireAdmin,
|
|
40
|
+
createPermissionChecker,
|
|
41
|
+
requireOwnership,
|
|
42
|
+
hasPermission,
|
|
43
|
+
hasAnyPermission,
|
|
44
|
+
requirePermission
|
|
45
|
+
} from './permissions.js';
|
|
46
|
+
|
|
47
|
+
// Re-export can-flags utility
|
|
48
|
+
export {
|
|
49
|
+
computeCanFlags,
|
|
50
|
+
attachCanFlags
|
|
51
|
+
} from './can-flags.js';
|
|
52
|
+
|
|
53
|
+
// Re-export all from entity roles
|
|
54
|
+
export {
|
|
55
|
+
ensureEntityRolesTable,
|
|
56
|
+
hasEntityRole,
|
|
57
|
+
requireEntityRoleOr
|
|
58
|
+
} from './entityRoles.js';
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Permissions Middleware
|
|
3
|
+
*
|
|
4
|
+
* Checks if the authenticated user has the required roles/permissions
|
|
5
|
+
* to access a resource or perform an action.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Check if user has any of the required roles
|
|
10
|
+
*/
|
|
11
|
+
export function hasAnyRole(userRoles, requiredRoles) {
|
|
12
|
+
if (!userRoles || !Array.isArray(userRoles)) return false;
|
|
13
|
+
if (!requiredRoles || requiredRoles.length === 0) return true;
|
|
14
|
+
|
|
15
|
+
return requiredRoles.some(role => userRoles.includes(role));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Check if user has all of the required roles
|
|
20
|
+
*/
|
|
21
|
+
export function hasAllRoles(userRoles, requiredRoles) {
|
|
22
|
+
if (!userRoles || !Array.isArray(userRoles)) return false;
|
|
23
|
+
if (!requiredRoles || requiredRoles.length === 0) return true;
|
|
24
|
+
|
|
25
|
+
return requiredRoles.every(role => userRoles.includes(role));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Middleware to require specific roles (ANY of the roles)
|
|
30
|
+
*
|
|
31
|
+
* @param {...string} roles - Required roles (user needs at least one)
|
|
32
|
+
*/
|
|
33
|
+
export function requireRoles(...roles) {
|
|
34
|
+
return (req, res, next) => {
|
|
35
|
+
if (!req.user) {
|
|
36
|
+
return res.status(401).json({
|
|
37
|
+
error: 'Unauthorized',
|
|
38
|
+
message: 'Authentication required'
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (!hasAnyRole(req.user.roles, roles)) {
|
|
43
|
+
return res.status(403).json({
|
|
44
|
+
error: 'Forbidden',
|
|
45
|
+
message: `This action requires one of the following roles: ${roles.join(', ')}`
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
next();
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Middleware to require ALL specified roles
|
|
55
|
+
*
|
|
56
|
+
* @param {...string} roles - Required roles (user needs all of them)
|
|
57
|
+
*/
|
|
58
|
+
export function requireAllRoles(...roles) {
|
|
59
|
+
return (req, res, next) => {
|
|
60
|
+
if (!req.user) {
|
|
61
|
+
return res.status(401).json({
|
|
62
|
+
error: 'Unauthorized',
|
|
63
|
+
message: 'Authentication required'
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (!hasAllRoles(req.user.roles, roles)) {
|
|
68
|
+
return res.status(403).json({
|
|
69
|
+
error: 'Forbidden',
|
|
70
|
+
message: `This action requires all of the following roles: ${roles.join(', ')}`
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
next();
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Middleware to require admin role
|
|
80
|
+
*/
|
|
81
|
+
export function requireAdmin() {
|
|
82
|
+
return requireRoles('admin');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Check if user has a specific named permission (looks in user.permissions array)
|
|
87
|
+
*/
|
|
88
|
+
export function hasPermission(userPermissions, requiredPermission) {
|
|
89
|
+
if (!userPermissions || !Array.isArray(userPermissions)) return false;
|
|
90
|
+
return userPermissions.includes(requiredPermission);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Check if user has any of the required permissions
|
|
95
|
+
*/
|
|
96
|
+
export function hasAnyPermission(userPermissions, requiredPermissions) {
|
|
97
|
+
if (!requiredPermissions || requiredPermissions.length === 0) return true;
|
|
98
|
+
if (!userPermissions || !Array.isArray(userPermissions)) return false;
|
|
99
|
+
return requiredPermissions.some(p => userPermissions.includes(p));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Middleware requiring a specific named permission string
|
|
104
|
+
*
|
|
105
|
+
* @param {string} permission - e.g. 'aircraft.update', 'purchase.approve'
|
|
106
|
+
*/
|
|
107
|
+
export function requirePermission(permission) {
|
|
108
|
+
return (req, res, next) => {
|
|
109
|
+
if (!req.user) {
|
|
110
|
+
return res.status(401).json({ error: 'Unauthorized', message: 'Authentication required' });
|
|
111
|
+
}
|
|
112
|
+
if (!hasPermission(req.user.permissions, permission)) {
|
|
113
|
+
return res.status(403).json({ error: 'Forbidden', message: 'Insufficient permissions' });
|
|
114
|
+
}
|
|
115
|
+
next();
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Create a permission checker for schema-defined permissions.
|
|
121
|
+
* Supports both new permission strings and legacy role names in the allowed list.
|
|
122
|
+
*
|
|
123
|
+
* @param {Object} schemaPermissions - e.g. { read: ['aircraft.read'], create: ['admin'] }
|
|
124
|
+
*/
|
|
125
|
+
export function createPermissionChecker(schemaPermissions) {
|
|
126
|
+
return {
|
|
127
|
+
/**
|
|
128
|
+
* Check if user can perform operation.
|
|
129
|
+
* Checks user.permissions first, then user.roles (backward compat).
|
|
130
|
+
*/
|
|
131
|
+
canPerform(user, operation) {
|
|
132
|
+
const allowedList = schemaPermissions[operation];
|
|
133
|
+
if (!allowedList) return false;
|
|
134
|
+
|
|
135
|
+
// New: check permission strings in user.permissions
|
|
136
|
+
if (user?.permissions?.length && allowedList.some(p => user.permissions.includes(p))) return true;
|
|
137
|
+
// Backward compat: role check
|
|
138
|
+
return hasAnyRole(user?.roles, allowedList);
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Middleware for checking read permission
|
|
143
|
+
*/
|
|
144
|
+
canRead() {
|
|
145
|
+
return this._createMiddleware('read');
|
|
146
|
+
},
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Middleware for checking create permission
|
|
150
|
+
*/
|
|
151
|
+
canCreate() {
|
|
152
|
+
return this._createMiddleware('create');
|
|
153
|
+
},
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Middleware for checking update permission
|
|
157
|
+
*/
|
|
158
|
+
canUpdate() {
|
|
159
|
+
return this._createMiddleware('update');
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Middleware for checking delete permission
|
|
164
|
+
*/
|
|
165
|
+
canDelete() {
|
|
166
|
+
return this._createMiddleware('delete');
|
|
167
|
+
},
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Create middleware for a specific operation.
|
|
171
|
+
* Checks user.permissions first, then user.roles (backward compat).
|
|
172
|
+
*/
|
|
173
|
+
_createMiddleware(operation) {
|
|
174
|
+
const allowedList = schemaPermissions[operation] || [];
|
|
175
|
+
|
|
176
|
+
return (req, res, next) => {
|
|
177
|
+
if (!req.user) {
|
|
178
|
+
return res.status(401).json({
|
|
179
|
+
error: 'Unauthorized',
|
|
180
|
+
message: 'Authentication required'
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const hasAccess =
|
|
185
|
+
(req.user.permissions?.some(p => allowedList.includes(p))) ||
|
|
186
|
+
hasAnyRole(req.user.roles, allowedList);
|
|
187
|
+
|
|
188
|
+
if (!hasAccess) {
|
|
189
|
+
return res.status(403).json({
|
|
190
|
+
error: 'Forbidden',
|
|
191
|
+
message: `You don't have permission to ${operation} this resource`
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
next();
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Middleware to check resource ownership
|
|
203
|
+
* Allows access if user owns the resource OR has admin role
|
|
204
|
+
*
|
|
205
|
+
* @param {Function} getOwnerId - Function to extract owner ID from request (receives req)
|
|
206
|
+
*/
|
|
207
|
+
export function requireOwnership(getOwnerId) {
|
|
208
|
+
return async (req, res, next) => {
|
|
209
|
+
if (!req.user) {
|
|
210
|
+
return res.status(401).json({
|
|
211
|
+
error: 'Unauthorized',
|
|
212
|
+
message: 'Authentication required'
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Admins bypass ownership check
|
|
217
|
+
if (req.user.roles?.includes('admin')) {
|
|
218
|
+
return next();
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
try {
|
|
222
|
+
const ownerId = await getOwnerId(req);
|
|
223
|
+
|
|
224
|
+
if (ownerId !== req.user.id) {
|
|
225
|
+
return res.status(403).json({
|
|
226
|
+
error: 'Forbidden',
|
|
227
|
+
message: 'You can only access your own resources'
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
next();
|
|
232
|
+
} catch (err) {
|
|
233
|
+
console.error('[Permissions] Ownership check error:', err);
|
|
234
|
+
return res.status(500).json({
|
|
235
|
+
error: 'Permission check failed',
|
|
236
|
+
message: 'Unable to verify resource ownership'
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
}
|