@xeplr/auth 1.1.4 → 1.1.6
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 +574 -0
- package/index.js +9 -0
- package/lib/accessMiddleware.js +37 -8
- package/lib/accessService.js +72 -17
- package/lib/adminRouter.js +228 -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/models/Api.js +2 -0
- package/models/Role.js +1 -0
- package/package.json +1 -1
package/lib/accessMiddleware.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
const { verifyToken } = require('./authHelper');
|
|
2
|
-
const
|
|
2
|
+
const accessService = require('./accessService');
|
|
3
|
+
const { getApiRule, userApiState } = accessService;
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Access-aware middleware.
|
|
6
|
-
* Uses Redis-cached API rules: isPublic → unmapped →
|
|
7
|
+
* Uses Redis-cached API rules: isPublic → unmapped → the user's state.
|
|
8
|
+
* Only 'enabled' goes through; 'disabled' and 'hidden' are refused, each with
|
|
9
|
+
* its own code so a UI can tell them apart.
|
|
7
10
|
*
|
|
8
11
|
* Usage:
|
|
9
12
|
* app.use('/api', accessMiddleware());
|
|
@@ -42,13 +45,39 @@ function accessMiddleware(options = {}) {
|
|
|
42
45
|
|
|
43
46
|
req.user = decoded;
|
|
44
47
|
|
|
45
|
-
//
|
|
46
|
-
|
|
47
|
-
if (
|
|
48
|
-
|
|
48
|
+
// The user's state for this API (also cached)
|
|
49
|
+
var state = await userApiState(decoded.id, apiName);
|
|
50
|
+
if (state === 'enabled') return next();
|
|
51
|
+
if (state === 'disabled') {
|
|
52
|
+
return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED' });
|
|
49
53
|
}
|
|
54
|
+
return res.status(403).json({ error: 'Access denied', code: 'HIDDEN' });
|
|
55
|
+
};
|
|
56
|
+
}
|
|
50
57
|
|
|
51
|
-
|
|
58
|
+
/**
|
|
59
|
+
* The access check for auth's OWN routes, in-process. The same answer the
|
|
60
|
+
* other apps get from GET /verify: the catalog row this request matches
|
|
61
|
+
* (method, path, :params), then the user's state for it. Mount after the
|
|
62
|
+
* token check, so req.user is set.
|
|
63
|
+
*
|
|
64
|
+
* Refuses on error: "cannot tell" is never "allowed".
|
|
65
|
+
*/
|
|
66
|
+
function accessGate() {
|
|
67
|
+
return async function(req, res, next) {
|
|
68
|
+
var path = (req.baseUrl || '') + (req.path || '');
|
|
69
|
+
var answer;
|
|
70
|
+
try {
|
|
71
|
+
answer = await accessService.requestApiState(req.user && req.user.id, req.method, path);
|
|
72
|
+
} catch (err) {
|
|
73
|
+
if (req.log) req.log.error('access check failed: ' + err.message);
|
|
74
|
+
return res.status(503).json({ error: 'Access rules are unavailable; try again shortly' });
|
|
75
|
+
}
|
|
76
|
+
if (answer.state === 'enabled') return next();
|
|
77
|
+
if (answer.state === 'disabled') {
|
|
78
|
+
return res.status(403).json({ error: 'This is disabled for you', code: 'DISABLED' });
|
|
79
|
+
}
|
|
80
|
+
return res.status(403).json({ error: 'Access denied', code: 'HIDDEN' });
|
|
52
81
|
};
|
|
53
82
|
}
|
|
54
83
|
|
|
@@ -76,4 +105,4 @@ function requireRole(...roles) {
|
|
|
76
105
|
};
|
|
77
106
|
}
|
|
78
107
|
|
|
79
|
-
module.exports = { accessMiddleware, requireRole };
|
|
108
|
+
module.exports = { accessMiddleware, accessGate, requireRole };
|
package/lib/accessService.js
CHANGED
|
@@ -5,6 +5,7 @@ const UiPage = require('../models/UiPage');
|
|
|
5
5
|
const Menu = require('../models/Menu');
|
|
6
6
|
const UiElement = require('../models/UiElement');
|
|
7
7
|
const { visibleItems } = require('./menuService');
|
|
8
|
+
const { matchApi } = require('./apiMatch');
|
|
8
9
|
|
|
9
10
|
// Cache TTLs (seconds)
|
|
10
11
|
const USER_ACCESS_TTL = 300; // 5 min — user's full access object
|
|
@@ -14,6 +15,7 @@ const API_RULES_TTL = 600; // 10 min — api public/role data (changes rare
|
|
|
14
15
|
const userAccessKey = (userId) => `access:user:${userId}`;
|
|
15
16
|
const apiRulesKey = (apiName) => `access:api:${encodeURIComponent(apiName)}`;
|
|
16
17
|
const publicItemsKey = 'access:public';
|
|
18
|
+
const catalogKey = 'access:api:catalog'; // under access:api:*, so clearAccessRules() clears it
|
|
17
19
|
|
|
18
20
|
/**
|
|
19
21
|
* Fetch the full access object for a user.
|
|
@@ -138,30 +140,79 @@ async function getApiRule(apiName) {
|
|
|
138
140
|
}
|
|
139
141
|
|
|
140
142
|
/**
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
+
* Access states. A gate answers one of these, not true/false:
|
|
144
|
+
*
|
|
145
|
+
* enabled shown and usable
|
|
146
|
+
* disabled shown, greyed out, not usable: the API refuses it
|
|
147
|
+
* hidden not shown: the API refuses it
|
|
148
|
+
*
|
|
149
|
+
* Today only enabled and hidden can come out (a role mapping is there or it
|
|
150
|
+
* is not). disabled is part of the answer so callers handle it now; the
|
|
151
|
+
* stored states that produce it come next.
|
|
143
152
|
*/
|
|
144
|
-
|
|
145
|
-
const rule = await getApiRule(apiName);
|
|
153
|
+
var ACCESS_STATES = ['enabled', 'disabled', 'hidden'];
|
|
146
154
|
|
|
155
|
+
/**
|
|
156
|
+
* The state for an API rule and a user's role ids. Pure, so it can be tested
|
|
157
|
+
* without a database.
|
|
158
|
+
*/
|
|
159
|
+
function apiStateFor(rule, userRoleIds) {
|
|
147
160
|
// Not registered in DB, or marked public, or no role mappings = open
|
|
148
|
-
if (!rule.exists || rule.isPublic || rule.unmapped) return
|
|
161
|
+
if (!rule.exists || rule.isPublic || rule.unmapped) return 'enabled';
|
|
162
|
+
var userRoleSet = new Set(userRoleIds || []);
|
|
163
|
+
return rule.roleIds.some(function(id) { return userRoleSet.has(id); }) ? 'enabled' : 'hidden';
|
|
164
|
+
}
|
|
149
165
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
166
|
+
/** The user's role ids, cached for the gate. */
|
|
167
|
+
async function userRoleIdsOf(userId) {
|
|
168
|
+
var userRoleCacheKey = `access:userRoles:${userId}`;
|
|
169
|
+
var userRoleIds = await cache.get(userRoleCacheKey);
|
|
170
|
+
if (userRoleIds) return userRoleIds;
|
|
153
171
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
.withGraphFetched('roles');
|
|
172
|
+
var user = await User.query()
|
|
173
|
+
.findById(userId)
|
|
174
|
+
.withGraphFetched('roles');
|
|
158
175
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
176
|
+
userRoleIds = (user && user.roles) ? user.roles.map(function(r) { return r.id; }) : [];
|
|
177
|
+
await cache.set(userRoleCacheKey, userRoleIds, USER_ACCESS_TTL);
|
|
178
|
+
return userRoleIds;
|
|
179
|
+
}
|
|
162
180
|
|
|
163
|
-
|
|
164
|
-
|
|
181
|
+
/**
|
|
182
|
+
* A user's state for a specific API: 'enabled' | 'disabled' | 'hidden'.
|
|
183
|
+
* Uses cached API rules and cached user roles.
|
|
184
|
+
*/
|
|
185
|
+
async function userApiState(userId, apiName) {
|
|
186
|
+
var rule = await getApiRule(apiName);
|
|
187
|
+
if (!rule.exists || rule.isPublic || rule.unmapped) return 'enabled';
|
|
188
|
+
return apiStateFor(rule, await userRoleIdsOf(userId));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Every API name in the catalog, cached like the other access rules. */
|
|
192
|
+
async function catalogApiNames() {
|
|
193
|
+
var cached = await cache.get(catalogKey);
|
|
194
|
+
if (Array.isArray(cached)) return cached;
|
|
195
|
+
var rows = await Api.query().select('name');
|
|
196
|
+
var names = rows.map(function(r) { return r.name; });
|
|
197
|
+
await cache.set(catalogKey, names, API_RULES_TTL);
|
|
198
|
+
return names;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* A user's state for a REQUEST: the catalog row it matches (method, path,
|
|
203
|
+
* :params), then that row's state. Not registered → enabled (open).
|
|
204
|
+
*
|
|
205
|
+
* @returns { api, state } api is the matched name, or null
|
|
206
|
+
*/
|
|
207
|
+
async function requestApiState(userId, method, path) {
|
|
208
|
+
var api = matchApi(await catalogApiNames(), method, path);
|
|
209
|
+
if (!api) return { api: null, state: 'enabled' };
|
|
210
|
+
return { api: api, state: await userApiState(userId, api) };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** True only when the state is enabled. Kept for callers that want a yes/no. */
|
|
214
|
+
async function userHasApiAccess(userId, apiName) {
|
|
215
|
+
return (await userApiState(userId, apiName)) === 'enabled';
|
|
165
216
|
}
|
|
166
217
|
|
|
167
218
|
/**
|
|
@@ -195,8 +246,12 @@ async function clearAllAccess() {
|
|
|
195
246
|
}
|
|
196
247
|
|
|
197
248
|
module.exports = {
|
|
249
|
+
ACCESS_STATES,
|
|
250
|
+
apiStateFor,
|
|
198
251
|
clearAllAccess,
|
|
199
252
|
getUserAccess,
|
|
253
|
+
requestApiState,
|
|
254
|
+
userApiState,
|
|
200
255
|
userHasApiAccess,
|
|
201
256
|
clearUserAccess,
|
|
202
257
|
clearAccessRules,
|
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 };
|
|
@@ -209,25 +281,50 @@ function createAdminRouter() {
|
|
|
209
281
|
// ─── Master CRUD: Roles ───
|
|
210
282
|
router.get('/master/roles', async function(req, res) {
|
|
211
283
|
try {
|
|
212
|
-
var items = await
|
|
284
|
+
var items = await visibleRoles(req);
|
|
213
285
|
res.json(items);
|
|
214
286
|
} catch (err) {
|
|
215
287
|
res.status(500).json({ error: 'Something went wrong' });
|
|
216
288
|
}
|
|
217
289
|
});
|
|
218
290
|
|
|
219
|
-
router.post('/master/roles', async function(req, res) {
|
|
291
|
+
router.post('/master/roles', requireSuperAdmin('create or rename roles'), async function(req, res) {
|
|
220
292
|
try {
|
|
221
|
-
var { id, name } = req.body;
|
|
293
|
+
var { id, name, scope } = req.body;
|
|
222
294
|
if (!name) return res.status(400).json({ error: 'name is required' });
|
|
295
|
+
if (scope != null && scope !== 'system' && scope !== 'company') {
|
|
296
|
+
return res.status(400).json({ error: "scope must be 'system' or 'company'" });
|
|
297
|
+
}
|
|
223
298
|
|
|
224
299
|
if (id) {
|
|
225
|
-
await
|
|
300
|
+
var current = await findVisibleRole(req, id);
|
|
301
|
+
if (!current) return res.status(404).json({ error: 'Role not found in this company' });
|
|
302
|
+
if (await nameTaken(current.mtId1, name, id)) {
|
|
303
|
+
return res.status(409).json({ error: 'A role called "' + name + '" already exists here' });
|
|
304
|
+
}
|
|
305
|
+
var patch = { name: name };
|
|
306
|
+
if (scope) patch.scope = scope;
|
|
307
|
+
await Role.query().findById(id).patch(patch);
|
|
226
308
|
await hooks.fire('roles', 'update', id);
|
|
227
309
|
res.json({ id: id });
|
|
228
310
|
} else {
|
|
311
|
+
// A system role belongs to the whole install. Any other role belongs
|
|
312
|
+
// to the company it is created in — even when Super Admin creates it —
|
|
313
|
+
// so creating one with no company selected is refused.
|
|
314
|
+
var rowScope = scope || 'company';
|
|
315
|
+
var t = tenantOf(req);
|
|
316
|
+
var mtId1 = GENERIC;
|
|
317
|
+
if (rowScope !== 'system' && t.multiTenant) {
|
|
318
|
+
if (!t.companyId) {
|
|
319
|
+
return res.status(400).json({ error: 'Choose a company first: a role belongs to the company it is created in', code: 'NO_COMPANY' });
|
|
320
|
+
}
|
|
321
|
+
mtId1 = t.companyId;
|
|
322
|
+
}
|
|
323
|
+
if (await nameTaken(mtId1, name)) {
|
|
324
|
+
return res.status(409).json({ error: 'A role called "' + name + '" already exists here' });
|
|
325
|
+
}
|
|
229
326
|
var newId = generateId();
|
|
230
|
-
await Role.query().insert({ id: newId, name: name });
|
|
327
|
+
await Role.query().insert({ id: newId, name: name, scope: rowScope, mtId1: mtId1 });
|
|
231
328
|
await hooks.fire('roles', 'create', newId);
|
|
232
329
|
res.json({ id: newId });
|
|
233
330
|
}
|
|
@@ -236,10 +333,87 @@ function createAdminRouter() {
|
|
|
236
333
|
}
|
|
237
334
|
});
|
|
238
335
|
|
|
239
|
-
|
|
336
|
+
// ─── Copy roles to other companies (Super Admin) ───
|
|
337
|
+
//
|
|
338
|
+
// Five companies wanting the same roles get five independent copies: same
|
|
339
|
+
// name, same grants (apis, pages, elements, menus), each then theirs to
|
|
340
|
+
// change. A company that already has a role of that name keeps its own —
|
|
341
|
+
// the copy is skipped and reported, never overwritten.
|
|
342
|
+
var MAPPINGS = [
|
|
343
|
+
{ Model: ApisRolesMapping, fk: 'apiId' },
|
|
344
|
+
{ Model: UiPagesRolesMapping, fk: 'uiPageId' },
|
|
345
|
+
{ Model: UiElementsRolesMapping, fk: 'uiElementId' },
|
|
346
|
+
{ Model: MenuRolesMapping, fk: 'menuId' }
|
|
347
|
+
];
|
|
348
|
+
|
|
349
|
+
router.post('/master/roles/copy', requireSuperAdmin('copy roles between companies'), async function(req, res) {
|
|
350
|
+
try {
|
|
351
|
+
var roleIds = Array.isArray(req.body.roleIds) ? req.body.roleIds : [];
|
|
352
|
+
var companyIds = Array.isArray(req.body.companyIds) ? req.body.companyIds : [];
|
|
353
|
+
if (!roleIds.length || !companyIds.length) {
|
|
354
|
+
return res.status(400).json({ error: 'roleIds and companyIds are required' });
|
|
355
|
+
}
|
|
356
|
+
var sources = await Role.query().select('id', 'name', 'scope').whereIn('id', roleIds);
|
|
357
|
+
var copied = [], skipped = [];
|
|
358
|
+
roleIds.forEach(function(rid) {
|
|
359
|
+
if (!sources.some(function(r) { return r.id === rid; })) skipped.push({ roleId: rid, reason: 'not found' });
|
|
360
|
+
});
|
|
361
|
+
var by = req.user ? req.user.id : null;
|
|
362
|
+
|
|
363
|
+
for (var i = 0; i < sources.length; i++) {
|
|
364
|
+
var src = sources[i];
|
|
365
|
+
if (src.scope === 'system') {
|
|
366
|
+
skipped.push({ roleId: src.id, reason: 'a system role belongs to the whole install and is not copied' });
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
var grants = [];
|
|
370
|
+
for (var m = 0; m < MAPPINGS.length; m++) {
|
|
371
|
+
var rows = await MAPPINGS[m].Model.query().select(MAPPINGS[m].fk).where('roleId', src.id);
|
|
372
|
+
grants.push(rows.map(function(r) { return r[MAPPINGS[m].fk]; }));
|
|
373
|
+
}
|
|
374
|
+
for (var c = 0; c < companyIds.length; c++) {
|
|
375
|
+
var companyId = String(companyIds[c] || '').trim();
|
|
376
|
+
if (!companyId || companyId === GENERIC) {
|
|
377
|
+
skipped.push({ roleId: src.id, companyId: companyId, reason: 'not a company id' });
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
if (await nameTaken(companyId, src.name)) {
|
|
381
|
+
skipped.push({ roleId: src.id, companyId: companyId, reason: 'a role called "' + src.name + '" already exists there' });
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
var copyId = generateId();
|
|
385
|
+
await Role.transaction(async function(trx) {
|
|
386
|
+
await Role.query(trx).insert({ id: copyId, name: src.name, scope: 'company', mtId1: companyId, recordCreatedBy: by });
|
|
387
|
+
for (var k = 0; k < MAPPINGS.length; k++) {
|
|
388
|
+
for (var g = 0; g < grants[k].length; g++) {
|
|
389
|
+
var row = { id: generateId(), roleId: copyId, isActive: true, recordCreatedBy: by };
|
|
390
|
+
row[MAPPINGS[k].fk] = grants[k][g];
|
|
391
|
+
await MAPPINGS[k].Model.query(trx).insert(row);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
});
|
|
395
|
+
await hooks.fire('roles', 'create', copyId);
|
|
396
|
+
copied.push({ roleId: src.id, companyId: companyId, newRoleId: copyId });
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if (copied.length) await clearAccessRules();
|
|
400
|
+
res.json({ copied: copied, skipped: skipped });
|
|
401
|
+
} catch (err) {
|
|
402
|
+
res.status(500).json({ error: 'Something went wrong' });
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
router.post('/master/roles/delete', requireSuperAdmin('delete roles'), async function(req, res) {
|
|
240
407
|
try {
|
|
241
408
|
var { id } = req.body;
|
|
242
409
|
if (!id) return res.status(400).json({ error: 'id is required' });
|
|
410
|
+
// Deleting the role that holds system scope would leave nobody able to
|
|
411
|
+
// manage the install. Refused, whoever asks.
|
|
412
|
+
var target = await findVisibleRole(req, id);
|
|
413
|
+
if (!target) return res.status(404).json({ error: 'Role not found in this company' });
|
|
414
|
+
if (target.name === SUPER_ADMIN_ROLE) {
|
|
415
|
+
return res.status(400).json({ error: 'The Super Admin role cannot be deleted' });
|
|
416
|
+
}
|
|
243
417
|
await Role.query().deleteById(id);
|
|
244
418
|
await clearAccessRules();
|
|
245
419
|
await hooks.fire('roles', 'delete', id);
|
|
@@ -255,11 +429,7 @@ function createAdminRouter() {
|
|
|
255
429
|
// sortOrder and isHidden are what the app's "Configure UI" screen edits.
|
|
256
430
|
var menuItems = createMenuService({ Menu: Menu, MenuRolesMapping: MenuRolesMapping, clearAll: clearAllAccess });
|
|
257
431
|
|
|
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
|
-
}
|
|
432
|
+
var superAdminOnly = requireSuperAdmin('change the menu');
|
|
263
433
|
|
|
264
434
|
function menuRoute(fn) {
|
|
265
435
|
return [superAdminOnly, async function(req, res) {
|
|
@@ -284,12 +454,53 @@ function createAdminRouter() {
|
|
|
284
454
|
menus: { Model: Menu, fields: ['name', 'menuGroup', 'isPublic'] }
|
|
285
455
|
};
|
|
286
456
|
|
|
457
|
+
// A system API row is managed by migrations only. Renaming or deleting it
|
|
458
|
+
// here would leave the route it names unguarded, so both are refused.
|
|
459
|
+
async function refuseSystemApiRow(typeKey, id, res) {
|
|
460
|
+
if (typeKey !== 'apis' || !id) return false;
|
|
461
|
+
var row = await Api.query().select('scope').findById(id);
|
|
462
|
+
if (row && row.scope === 'system') {
|
|
463
|
+
res.status(400).json({ error: 'A system API is managed by migrations and cannot be changed here', code: 'SYSTEM_SCOPE' });
|
|
464
|
+
return true;
|
|
465
|
+
}
|
|
466
|
+
return false;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// ─── "Super Admin only": move an API in or out of system scope ───
|
|
470
|
+
//
|
|
471
|
+
// Super Admin's switch in Master Settings, so an API can become system
|
|
472
|
+
// without code or SQL. Effective at once: the guard's cached list is
|
|
473
|
+
// cleared. A locked row (pinned by a migration) cannot be switched off.
|
|
474
|
+
// Role mappings are kept, so switching an API back restores who had it.
|
|
475
|
+
router.post('/master/apis/scope', requireSuperAdmin('change which APIs are Super Admin only'), async function(req, res) {
|
|
476
|
+
try {
|
|
477
|
+
var { id, scope } = req.body;
|
|
478
|
+
if (!id) return res.status(400).json({ error: 'id is required' });
|
|
479
|
+
if (scope !== 'system' && scope !== 'company') {
|
|
480
|
+
return res.status(400).json({ error: "scope must be 'system' or 'company'" });
|
|
481
|
+
}
|
|
482
|
+
var row = await Api.query().select('id', 'scope', 'scopeLocked').findById(id);
|
|
483
|
+
if (!row) return res.status(404).json({ error: 'API not found' });
|
|
484
|
+
if (row.scopeLocked) {
|
|
485
|
+
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' });
|
|
486
|
+
}
|
|
487
|
+
if (row.scope !== scope) {
|
|
488
|
+
await Api.query().findById(id).patch({ scope: scope });
|
|
489
|
+
await clearAccessRules();
|
|
490
|
+
await hooks.fire('apis', 'update', id);
|
|
491
|
+
}
|
|
492
|
+
res.json({ id: id, scope: scope });
|
|
493
|
+
} catch (err) {
|
|
494
|
+
res.status(500).json({ error: 'Something went wrong' });
|
|
495
|
+
}
|
|
496
|
+
});
|
|
497
|
+
|
|
287
498
|
Object.keys(masterTypes).forEach(function(typeKey) {
|
|
288
499
|
var cfg = masterTypes[typeKey];
|
|
289
500
|
|
|
290
501
|
router.get('/master/' + typeKey, async function(req, res) {
|
|
291
502
|
try {
|
|
292
|
-
var selectFields = ['id'].concat(cfg.fields);
|
|
503
|
+
var selectFields = ['id'].concat(cfg.fields, typeKey === 'apis' ? ['scope', 'scopeLocked'] : []);
|
|
293
504
|
var items = await cfg.Model.query().select(selectFields);
|
|
294
505
|
res.json(items);
|
|
295
506
|
} catch (err) {
|
|
@@ -306,6 +517,7 @@ function createAdminRouter() {
|
|
|
306
517
|
});
|
|
307
518
|
|
|
308
519
|
if (!data.name) return res.status(400).json({ error: 'name is required' });
|
|
520
|
+
if (await refuseSystemApiRow(typeKey, id, res)) return;
|
|
309
521
|
|
|
310
522
|
if (id) {
|
|
311
523
|
await cfg.Model.query().findById(id).patch(data);
|
|
@@ -327,6 +539,7 @@ function createAdminRouter() {
|
|
|
327
539
|
try {
|
|
328
540
|
var id = req.body.id;
|
|
329
541
|
if (!id) return res.status(400).json({ error: 'id is required' });
|
|
542
|
+
if (await refuseSystemApiRow(typeKey, id, res)) return;
|
|
330
543
|
await cfg.Model.query().deleteById(id);
|
|
331
544
|
await clearAccessRules();
|
|
332
545
|
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 };
|