@xeplr/auth 1.1.5 → 1.1.7
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 +158 -4
- package/index.js +9 -0
- package/lib/accessMiddleware.js +37 -8
- package/lib/accessService.js +118 -32
- package/lib/adminRouter.js +315 -15
- package/lib/apiMatch.js +56 -0
- package/lib/authRouter.js +42 -9
- package/lib/systemScope.js +79 -0
- package/lib/tenant.js +41 -0
- package/migrations/0010_system_scope.sql +78 -0
- package/migrations/0011_verify_api.sql +11 -0
- package/migrations/0012_default_role_access.sql +29 -0
- package/migrations/0013_mapping_state.sql +44 -0
- package/models/Api.js +3 -1
- package/models/ApisRolesMapping.js +1 -0
- package/models/MenuRolesMapping.js +1 -0
- package/models/Role.js +5 -4
- package/models/UiElementsRolesMapping.js +1 -0
- package/models/UiPagesRolesMapping.js +1 -0
- package/package.json +1 -1
package/lib/adminRouter.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
var express = require('express');
|
|
2
2
|
var { generateId } = require('./authHelper');
|
|
3
3
|
var { clearUserAccess, clearAccessRules, clearAllAccess } = require('./accessService');
|
|
4
|
+
var { accessGate } = require('./accessMiddleware');
|
|
4
5
|
var { createMenuService } = require('./menuService');
|
|
5
6
|
var authMiddleware = require('./authMiddleware');
|
|
6
7
|
var hooks = require('./hooks');
|
|
8
|
+
var { isSuperAdmin, systemScopeGuard, SUPER_ADMIN_ROLE } = require('./systemScope');
|
|
9
|
+
var { tenantOf, visibleTenants, GENERIC } = require('./tenant');
|
|
7
10
|
var User = require('../models/User');
|
|
8
11
|
var Role = require('../models/Role');
|
|
9
12
|
var Api = require('../models/Api');
|
|
@@ -37,6 +40,62 @@ function createAdminRouter() {
|
|
|
37
40
|
// Every admin route requires a valid JWT — populates req.user (with roles).
|
|
38
41
|
router.use(authMiddleware);
|
|
39
42
|
|
|
43
|
+
// SUPER ADMIN ONLY, checked here on the server. Hiding a screen does not
|
|
44
|
+
// stop anyone calling its route, so every route that changes roles carries
|
|
45
|
+
// this guard. (The menu routes below use it too.)
|
|
46
|
+
function requireSuperAdmin(action) {
|
|
47
|
+
return function(req, res, next) {
|
|
48
|
+
if (!isSuperAdmin(req.user)) {
|
|
49
|
+
return res.status(403).json({ error: 'Only Super Admin can ' + action });
|
|
50
|
+
}
|
|
51
|
+
next();
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// SYSTEM APIs (apis.scope = 'system') are Super Admin only, read from the
|
|
56
|
+
// catalog — so a route becomes a system action by adding its row, with no
|
|
57
|
+
// change here. The explicit requireSuperAdmin on the role routes below
|
|
58
|
+
// stays as a second line: those must hold even before migrations run.
|
|
59
|
+
router.use(systemScopeGuard());
|
|
60
|
+
|
|
61
|
+
// And every admin route is checked against the catalog like any other app's
|
|
62
|
+
// routes: a Viewer cannot call user-role or access-role just by being signed
|
|
63
|
+
// in. Which roles reach which admin route is data (role mappings), set by
|
|
64
|
+
// migrations and changed from the Access Matrix.
|
|
65
|
+
router.use(accessGate());
|
|
66
|
+
|
|
67
|
+
// A system role is seen, edited and assigned by Super Admin only.
|
|
68
|
+
async function refuseSystemRole(req, res, roleId) {
|
|
69
|
+
if (isSuperAdmin(req.user)) return false;
|
|
70
|
+
var role = await Role.query().select('scope').findById(roleId);
|
|
71
|
+
if (role && role.scope === 'system') {
|
|
72
|
+
res.status(403).json({ error: 'This is a system role: only Super Admin can assign or change it', code: 'SYSTEM_SCOPE' });
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Roles visible to this request: the current company's and the generic
|
|
79
|
+
// ('*') ones — and system roles only to Super Admin.
|
|
80
|
+
function visibleRoles(req) {
|
|
81
|
+
var q = Role.query().select('id', 'name', 'scope', 'mtId1');
|
|
82
|
+
if (!isSuperAdmin(req.user)) q = q.where('scope', '<>', 'system');
|
|
83
|
+
var tenants = visibleTenants(tenantOf(req));
|
|
84
|
+
if (tenants) q = q.whereIn('mtId1', tenants);
|
|
85
|
+
return q;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function findVisibleRole(req, id) {
|
|
89
|
+
return visibleRoles(req).findById(id);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// A role name is unique within the company it belongs to.
|
|
93
|
+
async function nameTaken(mtId1, name, exceptId) {
|
|
94
|
+
var q = Role.query().select('id').where('mtId1', mtId1).whereRaw('lower(name) = lower(?)', [name]);
|
|
95
|
+
if (exceptId) q = q.where('id', '<>', exceptId);
|
|
96
|
+
return !!(await q.first());
|
|
97
|
+
}
|
|
98
|
+
|
|
40
99
|
// ─── Users with their roles ───
|
|
41
100
|
router.get('/users', async function(req, res) {
|
|
42
101
|
try {
|
|
@@ -52,7 +111,7 @@ function createAdminRouter() {
|
|
|
52
111
|
// ─── Roles ───
|
|
53
112
|
router.get('/roles', async function(req, res) {
|
|
54
113
|
try {
|
|
55
|
-
var roles = await
|
|
114
|
+
var roles = await visibleRoles(req);
|
|
56
115
|
res.json(roles);
|
|
57
116
|
} catch (err) {
|
|
58
117
|
res.status(500).json({ error: 'Something went wrong' });
|
|
@@ -63,7 +122,8 @@ function createAdminRouter() {
|
|
|
63
122
|
router.get('/access-items', async function(req, res) {
|
|
64
123
|
try {
|
|
65
124
|
var [apis, pages, elements, menus] = await Promise.all([
|
|
66
|
-
|
|
125
|
+
// System APIs are not granted to roles, so they are not offered here.
|
|
126
|
+
Api.query().select('id', 'name', 'apiGroup', 'isPublic').where('scope', '<>', 'system').withGraphFetched('roles'),
|
|
67
127
|
UiPage.query().select('id', 'name', 'uiPagesGroup', 'isPublic').withGraphFetched('roles'),
|
|
68
128
|
UiElement.query().select('id', 'name', 'uiElementsGroup').withGraphFetched('roles'),
|
|
69
129
|
Menu.query().select('id', 'name', 'menuGroup', 'isPublic').withGraphFetched('roles')
|
|
@@ -82,6 +142,7 @@ function createAdminRouter() {
|
|
|
82
142
|
if (!userId || !roleId) {
|
|
83
143
|
return res.status(400).json({ error: 'userId and roleId are required' });
|
|
84
144
|
}
|
|
145
|
+
if (await refuseSystemRole(req, res, roleId)) return;
|
|
85
146
|
|
|
86
147
|
if (assign) {
|
|
87
148
|
var existing = await UserRolesMapping.query()
|
|
@@ -128,6 +189,13 @@ function createAdminRouter() {
|
|
|
128
189
|
if (!mapping) {
|
|
129
190
|
return res.status(400).json({ error: 'Invalid type. Use: apis, pages, elements, menus' });
|
|
130
191
|
}
|
|
192
|
+
if (await refuseSystemRole(req, res, roleId)) return;
|
|
193
|
+
if (type === 'apis') {
|
|
194
|
+
var api = await Api.query().select('scope').findById(itemId);
|
|
195
|
+
if (api && api.scope === 'system') {
|
|
196
|
+
return res.status(400).json({ error: 'A system API is not granted to roles: only Super Admin can use it', code: 'SYSTEM_SCOPE' });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
131
199
|
|
|
132
200
|
var where = { roleId: roleId };
|
|
133
201
|
where[mapping.fk] = itemId;
|
|
@@ -163,6 +231,7 @@ function createAdminRouter() {
|
|
|
163
231
|
if (!moduleName || !action || !roleId) {
|
|
164
232
|
return res.status(400).json({ error: 'module, action, and roleId are required' });
|
|
165
233
|
}
|
|
234
|
+
if (await refuseSystemRole(req, res, roleId)) return;
|
|
166
235
|
|
|
167
236
|
var groupValue = moduleName + ':' + action;
|
|
168
237
|
var createdBy = req.user ? req.user.id : null;
|
|
@@ -177,7 +246,10 @@ function createAdminRouter() {
|
|
|
177
246
|
var promises = types.map(async function(cfg) {
|
|
178
247
|
var where = {};
|
|
179
248
|
where[cfg.groupField] = groupValue;
|
|
180
|
-
var
|
|
249
|
+
var q = cfg.Model.query().select('id').where(where);
|
|
250
|
+
// A system API in the same group is still never granted.
|
|
251
|
+
if (cfg.type === 'apis') q = q.where('scope', '<>', 'system');
|
|
252
|
+
var items = await q;
|
|
181
253
|
|
|
182
254
|
for (var i = 0; i < items.length; i++) {
|
|
183
255
|
var itemWhere = { roleId: roleId };
|
|
@@ -206,28 +278,140 @@ function createAdminRouter() {
|
|
|
206
278
|
}
|
|
207
279
|
});
|
|
208
280
|
|
|
281
|
+
// ─── Module states: DISABLED, per role ───
|
|
282
|
+
// Enabled and Hidden are the role mapping (module-role above). Disabled is
|
|
283
|
+
// the mapping row's `state`: the role still sees the item, greyed out, and
|
|
284
|
+
// the API refuses it. Only roles for now; a workspace or user override is
|
|
285
|
+
// not stored, and says so.
|
|
286
|
+
var STATE_TYPES = [
|
|
287
|
+
{ Model: Api, MappingModel: ApisRolesMapping, fk: 'apiId', groupField: 'apiGroup', table: 'apis', mapping: 'apisRolesMapping' },
|
|
288
|
+
{ Model: UiPage, MappingModel: UiPagesRolesMapping, fk: 'uiPageId', groupField: 'uiPagesGroup', table: 'uiPages', mapping: 'uiPagesRolesMapping' },
|
|
289
|
+
{ Model: UiElement, MappingModel: UiElementsRolesMapping, fk: 'uiElementId', groupField: 'uiElementsGroup', table: 'uiElements', mapping: 'uiElementsRolesMapping' },
|
|
290
|
+
{ Model: Menu, MappingModel: MenuRolesMapping, fk: 'menuId', groupField: 'menuGroup', table: 'menus', mapping: 'menuRolesMapping' }
|
|
291
|
+
];
|
|
292
|
+
|
|
293
|
+
function onlyRoleScope(req, res, scope) {
|
|
294
|
+
if (scope === 'role') return false;
|
|
295
|
+
res.status(400).json({ error: 'Only role states are stored so far', code: 'SCOPE_NOT_SUPPORTED' });
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// "configuration:access:view" → module "configuration:access", action "view".
|
|
300
|
+
function splitGroup(group) {
|
|
301
|
+
var i = String(group || '').lastIndexOf(':');
|
|
302
|
+
return i <= 0 ? null : { module: group.slice(0, i), action: group.slice(i + 1) };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
router.get('/module-states', async function(req, res) {
|
|
306
|
+
try {
|
|
307
|
+
if (onlyRoleScope(req, res, req.query.scope)) return;
|
|
308
|
+
var roleIds = (await visibleRoles(req)).map(function(r) { return r.id; });
|
|
309
|
+
var seen = {};
|
|
310
|
+
var out = [];
|
|
311
|
+
for (var i = 0; i < STATE_TYPES.length; i++) {
|
|
312
|
+
var cfg = STATE_TYPES[i];
|
|
313
|
+
var rows = await cfg.MappingModel.query()
|
|
314
|
+
.select(cfg.mapping + '.roleId', cfg.table + '.' + cfg.groupField + ' as grp')
|
|
315
|
+
.join(cfg.table, cfg.table + '.id', cfg.mapping + '.' + cfg.fk)
|
|
316
|
+
.where(cfg.mapping + '.state', 'disabled')
|
|
317
|
+
.whereIn(cfg.mapping + '.roleId', roleIds);
|
|
318
|
+
rows.forEach(function(r) {
|
|
319
|
+
var g = splitGroup(r.grp);
|
|
320
|
+
var key = r.grp + '|' + r.roleId;
|
|
321
|
+
if (!g || seen[key]) return;
|
|
322
|
+
seen[key] = true;
|
|
323
|
+
out.push({ module: g.module, action: g.action, roleId: r.roleId, state: 'disabled' });
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
res.json(out);
|
|
327
|
+
} catch (err) {
|
|
328
|
+
res.status(500).json({ error: 'Something went wrong' });
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
// { scope: 'role', roleId, module, action, state }. state 'disabled' greys
|
|
333
|
+
// out every item of that module/action the role is mapped to; 'enabled',
|
|
334
|
+
// 'inherit' or null clears it. Hidden is not a state to store: it is no
|
|
335
|
+
// mapping, set through module-role.
|
|
336
|
+
router.post('/module-state', async function(req, res) {
|
|
337
|
+
try {
|
|
338
|
+
var { scope, module: moduleName, action, roleId, state } = req.body || {};
|
|
339
|
+
if (onlyRoleScope(req, res, scope)) return;
|
|
340
|
+
if (!moduleName || !action || !roleId) {
|
|
341
|
+
return res.status(400).json({ error: 'module, action, and roleId are required' });
|
|
342
|
+
}
|
|
343
|
+
var next = (state === 'disabled') ? 'disabled' : (state == null || state === 'enabled' || state === 'inherit') ? 'enabled' : null;
|
|
344
|
+
if (!next) {
|
|
345
|
+
return res.status(400).json({ error: 'state must be disabled, enabled or inherit; hidden is removing the mapping', code: 'BAD_STATE' });
|
|
346
|
+
}
|
|
347
|
+
if (await refuseSystemRole(req, res, roleId)) return;
|
|
348
|
+
|
|
349
|
+
var groupValue = moduleName + ':' + action;
|
|
350
|
+
var changed = 0;
|
|
351
|
+
for (var i = 0; i < STATE_TYPES.length; i++) {
|
|
352
|
+
var cfg = STATE_TYPES[i];
|
|
353
|
+
var items = cfg.Model.query().select('id').where(cfg.groupField, groupValue);
|
|
354
|
+
if (cfg.table === 'apis') items = items.where('scope', '<>', 'system');
|
|
355
|
+
changed += await cfg.MappingModel.query()
|
|
356
|
+
.patch({ state: next, recordModifiedBy: req.user ? req.user.id : null })
|
|
357
|
+
.where('roleId', roleId)
|
|
358
|
+
.whereIn(cfg.fk, items);
|
|
359
|
+
}
|
|
360
|
+
// Every cached answer: the API rules and each user's access object.
|
|
361
|
+
await clearAllAccess();
|
|
362
|
+
res.json({ ok: true, changed: changed });
|
|
363
|
+
} catch (err) {
|
|
364
|
+
res.status(500).json({ error: 'Something went wrong' });
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
|
|
209
368
|
// ─── Master CRUD: Roles ───
|
|
210
369
|
router.get('/master/roles', async function(req, res) {
|
|
211
370
|
try {
|
|
212
|
-
var items = await
|
|
371
|
+
var items = await visibleRoles(req);
|
|
213
372
|
res.json(items);
|
|
214
373
|
} catch (err) {
|
|
215
374
|
res.status(500).json({ error: 'Something went wrong' });
|
|
216
375
|
}
|
|
217
376
|
});
|
|
218
377
|
|
|
219
|
-
router.post('/master/roles', async function(req, res) {
|
|
378
|
+
router.post('/master/roles', requireSuperAdmin('create or rename roles'), async function(req, res) {
|
|
220
379
|
try {
|
|
221
|
-
var { id, name } = req.body;
|
|
380
|
+
var { id, name, scope } = req.body;
|
|
222
381
|
if (!name) return res.status(400).json({ error: 'name is required' });
|
|
382
|
+
if (scope != null && scope !== 'system' && scope !== 'company') {
|
|
383
|
+
return res.status(400).json({ error: "scope must be 'system' or 'company'" });
|
|
384
|
+
}
|
|
223
385
|
|
|
224
386
|
if (id) {
|
|
225
|
-
await
|
|
387
|
+
var current = await findVisibleRole(req, id);
|
|
388
|
+
if (!current) return res.status(404).json({ error: 'Role not found in this company' });
|
|
389
|
+
if (await nameTaken(current.mtId1, name, id)) {
|
|
390
|
+
return res.status(409).json({ error: 'A role called "' + name + '" already exists here' });
|
|
391
|
+
}
|
|
392
|
+
var patch = { name: name };
|
|
393
|
+
if (scope) patch.scope = scope;
|
|
394
|
+
await Role.query().findById(id).patch(patch);
|
|
226
395
|
await hooks.fire('roles', 'update', id);
|
|
227
396
|
res.json({ id: id });
|
|
228
397
|
} else {
|
|
398
|
+
// A system role belongs to the whole install. Any other role belongs
|
|
399
|
+
// to the company it is created in — even when Super Admin creates it —
|
|
400
|
+
// so creating one with no company selected is refused.
|
|
401
|
+
var rowScope = scope || 'company';
|
|
402
|
+
var t = tenantOf(req);
|
|
403
|
+
var mtId1 = GENERIC;
|
|
404
|
+
if (rowScope !== 'system' && t.multiTenant) {
|
|
405
|
+
if (!t.companyId) {
|
|
406
|
+
return res.status(400).json({ error: 'Choose a company first: a role belongs to the company it is created in', code: 'NO_COMPANY' });
|
|
407
|
+
}
|
|
408
|
+
mtId1 = t.companyId;
|
|
409
|
+
}
|
|
410
|
+
if (await nameTaken(mtId1, name)) {
|
|
411
|
+
return res.status(409).json({ error: 'A role called "' + name + '" already exists here' });
|
|
412
|
+
}
|
|
229
413
|
var newId = generateId();
|
|
230
|
-
await Role.query().insert({ id: newId, name: name });
|
|
414
|
+
await Role.query().insert({ id: newId, name: name, scope: rowScope, mtId1: mtId1 });
|
|
231
415
|
await hooks.fire('roles', 'create', newId);
|
|
232
416
|
res.json({ id: newId });
|
|
233
417
|
}
|
|
@@ -236,10 +420,87 @@ function createAdminRouter() {
|
|
|
236
420
|
}
|
|
237
421
|
});
|
|
238
422
|
|
|
239
|
-
|
|
423
|
+
// ─── Copy roles to other companies (Super Admin) ───
|
|
424
|
+
//
|
|
425
|
+
// Five companies wanting the same roles get five independent copies: same
|
|
426
|
+
// name, same grants (apis, pages, elements, menus), each then theirs to
|
|
427
|
+
// change. A company that already has a role of that name keeps its own —
|
|
428
|
+
// the copy is skipped and reported, never overwritten.
|
|
429
|
+
var MAPPINGS = [
|
|
430
|
+
{ Model: ApisRolesMapping, fk: 'apiId' },
|
|
431
|
+
{ Model: UiPagesRolesMapping, fk: 'uiPageId' },
|
|
432
|
+
{ Model: UiElementsRolesMapping, fk: 'uiElementId' },
|
|
433
|
+
{ Model: MenuRolesMapping, fk: 'menuId' }
|
|
434
|
+
];
|
|
435
|
+
|
|
436
|
+
router.post('/master/roles/copy', requireSuperAdmin('copy roles between companies'), async function(req, res) {
|
|
437
|
+
try {
|
|
438
|
+
var roleIds = Array.isArray(req.body.roleIds) ? req.body.roleIds : [];
|
|
439
|
+
var companyIds = Array.isArray(req.body.companyIds) ? req.body.companyIds : [];
|
|
440
|
+
if (!roleIds.length || !companyIds.length) {
|
|
441
|
+
return res.status(400).json({ error: 'roleIds and companyIds are required' });
|
|
442
|
+
}
|
|
443
|
+
var sources = await Role.query().select('id', 'name', 'scope').whereIn('id', roleIds);
|
|
444
|
+
var copied = [], skipped = [];
|
|
445
|
+
roleIds.forEach(function(rid) {
|
|
446
|
+
if (!sources.some(function(r) { return r.id === rid; })) skipped.push({ roleId: rid, reason: 'not found' });
|
|
447
|
+
});
|
|
448
|
+
var by = req.user ? req.user.id : null;
|
|
449
|
+
|
|
450
|
+
for (var i = 0; i < sources.length; i++) {
|
|
451
|
+
var src = sources[i];
|
|
452
|
+
if (src.scope === 'system') {
|
|
453
|
+
skipped.push({ roleId: src.id, reason: 'a system role belongs to the whole install and is not copied' });
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
var grants = [];
|
|
457
|
+
for (var m = 0; m < MAPPINGS.length; m++) {
|
|
458
|
+
var rows = await MAPPINGS[m].Model.query().select(MAPPINGS[m].fk).where('roleId', src.id);
|
|
459
|
+
grants.push(rows.map(function(r) { return r[MAPPINGS[m].fk]; }));
|
|
460
|
+
}
|
|
461
|
+
for (var c = 0; c < companyIds.length; c++) {
|
|
462
|
+
var companyId = String(companyIds[c] || '').trim();
|
|
463
|
+
if (!companyId || companyId === GENERIC) {
|
|
464
|
+
skipped.push({ roleId: src.id, companyId: companyId, reason: 'not a company id' });
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
if (await nameTaken(companyId, src.name)) {
|
|
468
|
+
skipped.push({ roleId: src.id, companyId: companyId, reason: 'a role called "' + src.name + '" already exists there' });
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
var copyId = generateId();
|
|
472
|
+
await Role.transaction(async function(trx) {
|
|
473
|
+
await Role.query(trx).insert({ id: copyId, name: src.name, scope: 'company', mtId1: companyId, recordCreatedBy: by });
|
|
474
|
+
for (var k = 0; k < MAPPINGS.length; k++) {
|
|
475
|
+
for (var g = 0; g < grants[k].length; g++) {
|
|
476
|
+
var row = { id: generateId(), roleId: copyId, isActive: true, recordCreatedBy: by };
|
|
477
|
+
row[MAPPINGS[k].fk] = grants[k][g];
|
|
478
|
+
await MAPPINGS[k].Model.query(trx).insert(row);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
});
|
|
482
|
+
await hooks.fire('roles', 'create', copyId);
|
|
483
|
+
copied.push({ roleId: src.id, companyId: companyId, newRoleId: copyId });
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (copied.length) await clearAccessRules();
|
|
487
|
+
res.json({ copied: copied, skipped: skipped });
|
|
488
|
+
} catch (err) {
|
|
489
|
+
res.status(500).json({ error: 'Something went wrong' });
|
|
490
|
+
}
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
router.post('/master/roles/delete', requireSuperAdmin('delete roles'), async function(req, res) {
|
|
240
494
|
try {
|
|
241
495
|
var { id } = req.body;
|
|
242
496
|
if (!id) return res.status(400).json({ error: 'id is required' });
|
|
497
|
+
// Deleting the role that holds system scope would leave nobody able to
|
|
498
|
+
// manage the install. Refused, whoever asks.
|
|
499
|
+
var target = await findVisibleRole(req, id);
|
|
500
|
+
if (!target) return res.status(404).json({ error: 'Role not found in this company' });
|
|
501
|
+
if (target.name === SUPER_ADMIN_ROLE) {
|
|
502
|
+
return res.status(400).json({ error: 'The Super Admin role cannot be deleted' });
|
|
503
|
+
}
|
|
243
504
|
await Role.query().deleteById(id);
|
|
244
505
|
await clearAccessRules();
|
|
245
506
|
await hooks.fire('roles', 'delete', id);
|
|
@@ -255,11 +516,7 @@ function createAdminRouter() {
|
|
|
255
516
|
// sortOrder and isHidden are what the app's "Configure UI" screen edits.
|
|
256
517
|
var menuItems = createMenuService({ Menu: Menu, MenuRolesMapping: MenuRolesMapping, clearAll: clearAllAccess });
|
|
257
518
|
|
|
258
|
-
|
|
259
|
-
var roles = (req.user && req.user.roles) || [];
|
|
260
|
-
if (roles.indexOf('Super Admin') === -1) return res.status(403).json({ error: 'Only Super Admin can change the menu' });
|
|
261
|
-
next();
|
|
262
|
-
}
|
|
519
|
+
var superAdminOnly = requireSuperAdmin('change the menu');
|
|
263
520
|
|
|
264
521
|
function menuRoute(fn) {
|
|
265
522
|
return [superAdminOnly, async function(req, res) {
|
|
@@ -284,12 +541,53 @@ function createAdminRouter() {
|
|
|
284
541
|
menus: { Model: Menu, fields: ['name', 'menuGroup', 'isPublic'] }
|
|
285
542
|
};
|
|
286
543
|
|
|
544
|
+
// A system API row is managed by migrations only. Renaming or deleting it
|
|
545
|
+
// here would leave the route it names unguarded, so both are refused.
|
|
546
|
+
async function refuseSystemApiRow(typeKey, id, res) {
|
|
547
|
+
if (typeKey !== 'apis' || !id) return false;
|
|
548
|
+
var row = await Api.query().select('scope').findById(id);
|
|
549
|
+
if (row && row.scope === 'system') {
|
|
550
|
+
res.status(400).json({ error: 'A system API is managed by migrations and cannot be changed here', code: 'SYSTEM_SCOPE' });
|
|
551
|
+
return true;
|
|
552
|
+
}
|
|
553
|
+
return false;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// ─── "Super Admin only": move an API in or out of system scope ───
|
|
557
|
+
//
|
|
558
|
+
// Super Admin's switch in Master Settings, so an API can become system
|
|
559
|
+
// without code or SQL. Effective at once: the guard's cached list is
|
|
560
|
+
// cleared. A locked row (pinned by a migration) cannot be switched off.
|
|
561
|
+
// Role mappings are kept, so switching an API back restores who had it.
|
|
562
|
+
router.post('/master/apis/scope', requireSuperAdmin('change which APIs are Super Admin only'), async function(req, res) {
|
|
563
|
+
try {
|
|
564
|
+
var { id, scope } = req.body;
|
|
565
|
+
if (!id) return res.status(400).json({ error: 'id is required' });
|
|
566
|
+
if (scope !== 'system' && scope !== 'company') {
|
|
567
|
+
return res.status(400).json({ error: "scope must be 'system' or 'company'" });
|
|
568
|
+
}
|
|
569
|
+
var row = await Api.query().select('id', 'scope', 'scopeLocked').findById(id);
|
|
570
|
+
if (!row) return res.status(404).json({ error: 'API not found' });
|
|
571
|
+
if (row.scopeLocked) {
|
|
572
|
+
return res.status(400).json({ error: 'This API is pinned as Super Admin only by a migration and cannot be changed here', code: 'SCOPE_LOCKED' });
|
|
573
|
+
}
|
|
574
|
+
if (row.scope !== scope) {
|
|
575
|
+
await Api.query().findById(id).patch({ scope: scope });
|
|
576
|
+
await clearAccessRules();
|
|
577
|
+
await hooks.fire('apis', 'update', id);
|
|
578
|
+
}
|
|
579
|
+
res.json({ id: id, scope: scope });
|
|
580
|
+
} catch (err) {
|
|
581
|
+
res.status(500).json({ error: 'Something went wrong' });
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
|
|
287
585
|
Object.keys(masterTypes).forEach(function(typeKey) {
|
|
288
586
|
var cfg = masterTypes[typeKey];
|
|
289
587
|
|
|
290
588
|
router.get('/master/' + typeKey, async function(req, res) {
|
|
291
589
|
try {
|
|
292
|
-
var selectFields = ['id'].concat(cfg.fields);
|
|
590
|
+
var selectFields = ['id'].concat(cfg.fields, typeKey === 'apis' ? ['scope', 'scopeLocked'] : []);
|
|
293
591
|
var items = await cfg.Model.query().select(selectFields);
|
|
294
592
|
res.json(items);
|
|
295
593
|
} catch (err) {
|
|
@@ -306,6 +604,7 @@ function createAdminRouter() {
|
|
|
306
604
|
});
|
|
307
605
|
|
|
308
606
|
if (!data.name) return res.status(400).json({ error: 'name is required' });
|
|
607
|
+
if (await refuseSystemApiRow(typeKey, id, res)) return;
|
|
309
608
|
|
|
310
609
|
if (id) {
|
|
311
610
|
await cfg.Model.query().findById(id).patch(data);
|
|
@@ -327,6 +626,7 @@ function createAdminRouter() {
|
|
|
327
626
|
try {
|
|
328
627
|
var id = req.body.id;
|
|
329
628
|
if (!id) return res.status(400).json({ error: 'id is required' });
|
|
629
|
+
if (await refuseSystemApiRow(typeKey, id, res)) return;
|
|
330
630
|
await cfg.Model.query().deleteById(id);
|
|
331
631
|
await clearAccessRules();
|
|
332
632
|
await hooks.fire(typeKey, 'delete', id);
|
package/lib/apiMatch.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which `apis` row a request is. Pure, so it can be tested without a request.
|
|
3
|
+
*
|
|
4
|
+
* A row's name is "METHOD path" (that method only) or a bare path (every
|
|
5
|
+
* method), and a path may hold `:params` — "GET /widget-templates/:id"
|
|
6
|
+
* covers GET /widget-templates/abc. When several rows fit, the most exact
|
|
7
|
+
* wins:
|
|
8
|
+
*
|
|
9
|
+
* 1. more literal segments /dashboards/:id/group beats /dashboards/:id/:x
|
|
10
|
+
* 2. a method over none "POST /x" beats "/x"
|
|
11
|
+
*
|
|
12
|
+
* @param names every API name in the catalog
|
|
13
|
+
* @param method 'GET', 'POST', …
|
|
14
|
+
* @param path the request path, no query string
|
|
15
|
+
* @returns the matching name, or null (not registered)
|
|
16
|
+
*/
|
|
17
|
+
function clean(path) {
|
|
18
|
+
return String(path || '').split('?')[0].replace(/\/+$/, '') || '/';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function parse(name) {
|
|
22
|
+
var m = /^([A-Z]+)\s+(\S+)$/.exec(String(name || '').trim());
|
|
23
|
+
return m ? { method: m[1], path: clean(m[2]) } : { method: null, path: clean(name) };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Literal segments matched, or -1 when the pattern does not fit. */
|
|
27
|
+
function fit(pattern, path) {
|
|
28
|
+
var a = pattern.split('/');
|
|
29
|
+
var b = path.split('/');
|
|
30
|
+
if (a.length !== b.length) return -1;
|
|
31
|
+
var literal = 0;
|
|
32
|
+
for (var i = 0; i < a.length; i++) {
|
|
33
|
+
if (a[i].charAt(0) === ':' && b[i] !== '') continue;
|
|
34
|
+
if (a[i] !== b[i]) return -1;
|
|
35
|
+
literal++;
|
|
36
|
+
}
|
|
37
|
+
return literal;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function matchApi(names, method, path) {
|
|
41
|
+
var verb = String(method || '').toUpperCase();
|
|
42
|
+
var target = clean(path);
|
|
43
|
+
var best = null;
|
|
44
|
+
var bestScore = -1;
|
|
45
|
+
(names || []).forEach(function(name) {
|
|
46
|
+
var row = parse(name);
|
|
47
|
+
if (row.method && row.method !== verb) return;
|
|
48
|
+
var literal = fit(row.path, target);
|
|
49
|
+
if (literal < 0) return;
|
|
50
|
+
var score = literal * 2 + (row.method ? 1 : 0);
|
|
51
|
+
if (score > bestScore) { best = name; bestScore = score; }
|
|
52
|
+
});
|
|
53
|
+
return best;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
module.exports = { matchApi: matchApi };
|
package/lib/authRouter.js
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
const express = require('express');
|
|
2
2
|
const FileUploader = require('@xeplr/utils/lib/fileUploader');
|
|
3
3
|
const { register, activate, previewInvite, acceptInvite, login, forgotPassword, resetPassword, requestPhoneOtp, verifyPhoneOtp, getProfile, updateProfile, setProfilePic, changePassword } = require('./authService');
|
|
4
|
-
const { getUserAccess } = require('./accessService');
|
|
4
|
+
const { getUserAccess, requestApiState } = require('./accessService');
|
|
5
5
|
const { getSession, rotateSession, destroySession } = require('./sessionService');
|
|
6
6
|
const { issueTicket } = require('./ticketService');
|
|
7
7
|
const authMiddleware = require('./authMiddleware');
|
|
8
|
+
const { accessGate } = require('./accessMiddleware');
|
|
9
|
+
|
|
10
|
+
// Signed in AND allowed this route by the catalog: the same two checks every
|
|
11
|
+
// other app's gate asks /verify for. Login, register, refresh and the rest of
|
|
12
|
+
// the signed-out routes carry neither.
|
|
13
|
+
const signedInAndAllowed = [authMiddleware, accessGate()];
|
|
8
14
|
const User = require('../models/User');
|
|
9
15
|
|
|
10
16
|
// Avatar uploads — local disk by default (FileUploader's own default:
|
|
@@ -205,7 +211,7 @@ function createAuthRouter(options = {}) {
|
|
|
205
211
|
}
|
|
206
212
|
});
|
|
207
213
|
|
|
208
|
-
router.get('/me',
|
|
214
|
+
router.get('/me', signedInAndAllowed, async function(req, res) {
|
|
209
215
|
try {
|
|
210
216
|
const access = await getUserAccess(req.user.id);
|
|
211
217
|
res.json({
|
|
@@ -218,7 +224,34 @@ function createAuthRouter(options = {}) {
|
|
|
218
224
|
}
|
|
219
225
|
});
|
|
220
226
|
|
|
221
|
-
|
|
227
|
+
// The check every app's gate asks, on every request it serves: who is this
|
|
228
|
+
// (the token, with the same tolerance and sliding refresh as any route) AND
|
|
229
|
+
// may they call this API. Both, always; there is no way to ask one without
|
|
230
|
+
// the other. The app names the request it is serving in two headers.
|
|
231
|
+
router.get('/verify', authMiddleware, async function(req, res) {
|
|
232
|
+
var method = req.headers['x-verify-method'];
|
|
233
|
+
var path = req.headers['x-verify-path'];
|
|
234
|
+
if (!method || !path) {
|
|
235
|
+
return res.status(400).json({ error: 'x-verify-method and x-verify-path are required', code: 'NO_REQUEST' });
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
var answer = await requestApiState(req.user.id, method, path);
|
|
239
|
+
if (answer.state === 'enabled') {
|
|
240
|
+
var access = await getUserAccess(req.user.id);
|
|
241
|
+
return res.json({ user: req.user, access: access, state: 'enabled', api: answer.api });
|
|
242
|
+
}
|
|
243
|
+
if (answer.state === 'disabled') {
|
|
244
|
+
return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED', api: answer.api });
|
|
245
|
+
}
|
|
246
|
+
// hidden, or anything the gate does not know: refused.
|
|
247
|
+
return res.status(403).json({ error: 'Access denied', code: 'HIDDEN', api: answer.api });
|
|
248
|
+
} catch (err) {
|
|
249
|
+
logError(req, err);
|
|
250
|
+
res.status(500).json({ error: 'Something went wrong' });
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
router.get('/profile', signedInAndAllowed, async function(req, res) {
|
|
222
255
|
try {
|
|
223
256
|
const profile = await getProfile(req.user.id);
|
|
224
257
|
res.json(profile);
|
|
@@ -228,7 +261,7 @@ function createAuthRouter(options = {}) {
|
|
|
228
261
|
}
|
|
229
262
|
});
|
|
230
263
|
|
|
231
|
-
router.put('/profile',
|
|
264
|
+
router.put('/profile', signedInAndAllowed, async function(req, res) {
|
|
232
265
|
try {
|
|
233
266
|
const profile = await updateProfile(req.user.id, req.body);
|
|
234
267
|
res.json(profile);
|
|
@@ -238,7 +271,7 @@ function createAuthRouter(options = {}) {
|
|
|
238
271
|
}
|
|
239
272
|
});
|
|
240
273
|
|
|
241
|
-
router.post('/profile/avatar',
|
|
274
|
+
router.post('/profile/avatar', signedInAndAllowed, ...avatarUploader.single('avatar'), async function(req, res) {
|
|
242
275
|
try {
|
|
243
276
|
if (!req.file) return res.status(400).json({ error: 'avatar file is required' });
|
|
244
277
|
// Store just the generated filename — never the server's filesystem
|
|
@@ -253,7 +286,7 @@ function createAuthRouter(options = {}) {
|
|
|
253
286
|
}
|
|
254
287
|
});
|
|
255
288
|
|
|
256
|
-
router.post('/change-password',
|
|
289
|
+
router.post('/change-password', signedInAndAllowed, async function(req, res) {
|
|
257
290
|
try {
|
|
258
291
|
const { oldPassword, newPassword } = req.body;
|
|
259
292
|
if (!oldPassword || !newPassword) {
|
|
@@ -270,7 +303,7 @@ function createAuthRouter(options = {}) {
|
|
|
270
303
|
// Additive phone verification — like email activation, but for a phone
|
|
271
304
|
// number attached to an already-authenticated account. Body: { phoneNumber }
|
|
272
305
|
// optional (omit to re-send to the number already on file).
|
|
273
|
-
router.post('/request-phone-otp',
|
|
306
|
+
router.post('/request-phone-otp', signedInAndAllowed, async function(req, res) {
|
|
274
307
|
try {
|
|
275
308
|
const result = await requestPhoneOtp(req.user.id, req.body.phoneNumber);
|
|
276
309
|
res.json(result);
|
|
@@ -280,7 +313,7 @@ function createAuthRouter(options = {}) {
|
|
|
280
313
|
}
|
|
281
314
|
});
|
|
282
315
|
|
|
283
|
-
router.post('/verify-phone-otp',
|
|
316
|
+
router.post('/verify-phone-otp', signedInAndAllowed, async function(req, res) {
|
|
284
317
|
try {
|
|
285
318
|
if (!req.body.code) return res.status(400).json({ error: 'code is required' });
|
|
286
319
|
const result = await verifyPhoneOtp(req.user.id, req.body.code);
|
|
@@ -304,7 +337,7 @@ function createAuthRouter(options = {}) {
|
|
|
304
337
|
//
|
|
305
338
|
// NOTE the scopes are advisory intent — the SSE handler owns the final
|
|
306
339
|
// authorization check (see xeplr-base-apis/lib/sse.js#createHandler).
|
|
307
|
-
router.post('/sse-ticket',
|
|
340
|
+
router.post('/sse-ticket', signedInAndAllowed, async function(req, res) {
|
|
308
341
|
try {
|
|
309
342
|
var requested = (req.body && Array.isArray(req.body.scopes)) ? req.body.scopes : ['user:me:*'];
|
|
310
343
|
var { ticket, expiresIn } = await issueTicket({
|