@xeplr/auth 1.4.0 → 1.5.1
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 +16 -4
- package/lib/accessMiddleware.js +9 -3
- package/lib/accessService.js +72 -14
- package/lib/authRouter.js +18 -22
- package/lib/authService.js +58 -18
- package/lib/mtMembershipMiddleware.js +41 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -68,7 +68,7 @@ To act on auth tables from another service (invite a user, assign roles) while a
|
|
|
68
68
|
var auth = require('@xeplr/auth').attach() // AUTH_DB_NAME + the connection env
|
|
69
69
|
await auth.ready()
|
|
70
70
|
await auth.model('UserRolesMapping').query().insert({ /* … */ })
|
|
71
|
-
await auth.service.invite({ email, name, invitedBy, inviterName, appName })
|
|
71
|
+
await auth.service.invite({ email, name, invitedBy, inviterName, appName }) // → { id, isNew, isActivated, resent? } — not yet activated: the invite goes again
|
|
72
72
|
```
|
|
73
73
|
|
|
74
74
|
## Exports
|
|
@@ -292,6 +292,7 @@ Client code must read the header and replace its stored token, or the session en
|
|
|
292
292
|
2. **Activate** — by the emailed link, or by an admin (`POST /admin/users/:id/activate`). Both grant the `AUTH_REGISTER_ROLES` roles in the same transaction, so an activated account always has a role.
|
|
293
293
|
3. **Lost the mail?** `POST /resend-activation` sends a new link.
|
|
294
294
|
4. **Invited people** set their password on the accept-invite page (`/invite-preview`, `/invite-accept`); they get whatever roles the inviter grants, not the sign-up roles.
|
|
295
|
+
5. **Nobody is left stuck.** Inviting an address whose account is **not activated** sends the invite **again** — a fresh link, the old one stops working (`invite()` answers `resent: true`); an activated account is left alone. And a completed **password reset activates** an account that never was: the reset link proves the address just as an activation or invite link does. Invited (no password until the reset): activated as accepting the invite would. Signed up: activated as the emailed link would, with the sign-up roles. A password set meanwhile does not block accepting an invite.
|
|
295
296
|
|
|
296
297
|
### `/auth/api`
|
|
297
298
|
|
|
@@ -300,14 +301,14 @@ Client code must read the header and replace its stored token, or the session en
|
|
|
300
301
|
| `POST /register` | — | `{ email, password, name?, phoneNumber? }` → `201 { message, user }`; `409` if the email is registered. Sends the activation email. `503 { error, code }` when a sign-up setting is missing or the mail cannot be sent — in every such case **no account is created**, so trying again works |
|
|
301
302
|
| `POST /resend-activation` | — | `{ email }` → the same message whether or not the address has an account waiting; sends a new link and the old one stops working. Invited accounts are skipped (they use their invite link) |
|
|
302
303
|
| `GET /activate` | — | `?token=…&workflowKey=…` → `{ message, user }`; grants the `AUTH_REGISTER_ROLES` roles. An invite token is refused here (it would leave an account with no password) |
|
|
303
|
-
| `GET /invite-preview` | — | `?token=…` → `{ email, name }` |
|
|
304
|
+
| `GET /invite-preview` | — | `?token=…` → `{ email, name }` for an account not yet activated (a password set by a reset meanwhile does not matter) |
|
|
304
305
|
| `POST /invite-accept` | — | `{ token, password, name? }` → sets the password and activates |
|
|
305
306
|
| `POST /login` | — | `{ email, password }` → `{ accessToken, refreshToken, user, access }`; `401` wrong password or deactivated (an invited account with no password yet is a wrong password); `403 { error, code: 'NOT_ACTIVATED' }` not yet activated — check `code`, not the wording |
|
|
306
307
|
| `POST /refresh` | — | `{ refreshToken }` → a new `{ accessToken, refreshToken, user, access }` |
|
|
307
308
|
| `POST /logout` | — | `{ refreshToken }` → ends that session |
|
|
308
309
|
| `POST /forgot-password` | — | `{ email }` → the same message whether or not the address exists; emails `AUTH_RESET_URL?token=…` (or `<resetBaseUrl>/auth/reset-password` when the router is given `resetBaseUrl`). `503` for every address alike when the reset address or mail is not set up |
|
|
309
|
-
| `POST /reset-password` | — | `{ token, newPassword }`; `400` once the link is older than `AUTH_RESET_TOKEN_EXPIRY_MINUTES
|
|
310
|
-
| `GET /me` | ✓ | `{ user, access }` — `user` is the token's claims |
|
|
310
|
+
| `POST /reset-password` | — | `{ token, newPassword }`; `400` once the link is older than `AUTH_RESET_TOKEN_EXPIRY_MINUTES`. Activates an account that was never activated (the link proves the address) |
|
|
311
|
+
| `GET /me` | ✓ | `{ user, access }` — `user` is the token's claims. With `x-verify-tenant` (`{ "l1": "<company>", "l2": "<workspace>" }`), `access` is as the user is there: their own roles plus the ones their membership gives them ([roles held in a company](#roles-held-in-a-company-or-workspace)). Not a member: `403 NOT_A_MEMBER`; unreadable: `400 BAD_TENANT` |
|
|
311
312
|
| `GET /verify` | ✓ | the check every app's gate makes on every request — see [Every request is checked](#every-request-is-checked) |
|
|
312
313
|
| `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
|
|
313
314
|
| `POST /profile/avatar` | ✓ | multipart `avatar`, an image up to 2 MB; stores the file name only — serving `UPLOAD_DIR` is the app's job |
|
|
@@ -584,6 +585,15 @@ auth.boot()
|
|
|
584
585
|
|
|
585
586
|
`@xeplr/db`'s `mtMiddleware` trusts whatever tenant header it is given. `mtMembershipMiddleware` is what checks it: for each configured slot whose header is present, the caller needs an active membership row with that value, or gets `403 Not authorized for <slot> "<value>"`. An absent header is left alone. It does nothing when multi-tenancy is not enabled. **Super Admin passes whatever the headers say**: the role runs the whole install, so it goes into every company and workspace without a membership row.
|
|
586
587
|
|
|
588
|
+
### Roles held in a company or workspace
|
|
589
|
+
|
|
590
|
+
A membership row's `roleId` is the role the user holds **there**. Whenever a request names that company or workspace, the roles that count are the user's own roles **plus** the roles on their own membership rows for the values it names. Outside it they don't apply. **Whoever creates a company is its CompanyAdmin this way** (Xeplr BI grants it when the company is made), while their own role stays what it was everywhere else: a self-registered Viewer is a Viewer on the platform and the admin of the one company they made.
|
|
591
|
+
|
|
592
|
+
- **Where it counts:** `/verify` (with `x-verify-tenant`, as an app's gate sends it), `/me` (with the same header), `accessMiddleware` and `accessGate` (`x-verify-tenant`, else the app's own MT headers when the process registered them, `tenantsOfRequest`). One function, `accessService.tenantRoleIdsOf(userId, tenants)`.
|
|
593
|
+
- **Naming a company gives nothing by itself.** Only the user's own active rows are read, so a header naming another company finds no role there; `/verify` and `/me` refuse it as `NOT_A_MEMBER` first.
|
|
594
|
+
- **A company role counts in all of its workspaces**, a workspace role only in that workspace: a request naming `{ l1, l2 }` reads both rows.
|
|
595
|
+
- **Cached per user and tenant** under `access:user:<id>:…`, 5 minutes. After changing a membership's role, `clearUserAccess(userId)` makes it count at once.
|
|
596
|
+
|
|
587
597
|
### Roles belong to a company
|
|
588
598
|
|
|
589
599
|
Two separate questions: **where** a row belongs (`mtId1`) and **who** may use it (`scope`, see [system scope](#system-scope)).
|
|
@@ -636,6 +646,8 @@ npm test # node --test test/*.test.js
|
|
|
636
646
|
|
|
637
647
|
`test/signUpFlow.test.js` runs the whole sign-up flow over HTTP against a local PostgreSQL and Redis, with real mail: nodemailer (the workspace dev dependency) talks SMTP to a small listener inside the test. It is skipped when any of the three is missing.
|
|
638
648
|
|
|
649
|
+
`test/scopedRoles.test.js` checks roles held in a company or workspace (local PostgreSQL and Redis; skipped without either): the company a Viewer created lets them import there and only there (`HIDDEN` naming none, or another company where they are a plain member; `NOT_A_MEMBER` naming a stranger's); a workspace role counts in that workspace and the company role in all of its workspaces; `/me` answers as the user is in the company named; a role taken away is gone after `clearUserAccess`; an app running auth in-process (`accessMiddleware`) reads the company from the request.
|
|
650
|
+
|
|
639
651
|
`test/verifyTenant.test.js` checks the membership answer on real memberships (local PostgreSQL and Redis; skipped without either): a member of company and workspace passes and is told `tenant: 'checked'`; another company, another workspace and a switched-off membership are `403 NOT_A_MEMBER`; Super Admin passes; a request naming none is not checked and does not claim to be; an unreadable `x-verify-tenant` is `400 BAD_TENANT`.
|
|
640
652
|
|
|
641
653
|
`test/menuItems.test.js` needs a local PostgreSQL (the usual `PG*` variables): it creates and drops a throwaway database, and is skipped when none is reachable. The token-decision and `REDIS_PREFIX` tests need nothing.
|
package/lib/accessMiddleware.js
CHANGED
|
@@ -2,6 +2,7 @@ const { verifyToken } = require('./authHelper');
|
|
|
2
2
|
const accessService = require('./accessService');
|
|
3
3
|
const { getApiRule, userApiState } = accessService;
|
|
4
4
|
const licence = require('./licence');
|
|
5
|
+
const { tenantsOfRequest } = require('./mtMembershipMiddleware');
|
|
5
6
|
|
|
6
7
|
/** The 403 for a state that is not 'enabled'. Anything unknown is HIDDEN: refused. */
|
|
7
8
|
function refuse(res, state) {
|
|
@@ -55,8 +56,11 @@ function accessMiddleware(options = {}) {
|
|
|
55
56
|
|
|
56
57
|
req.user = decoded;
|
|
57
58
|
|
|
58
|
-
// The user's state for this API (also cached)
|
|
59
|
-
|
|
59
|
+
// The user's state for this API (also cached) — in the company/workspace
|
|
60
|
+
// the request names, where their membership may give them a role.
|
|
61
|
+
var tenants = tenantsOfRequest(req);
|
|
62
|
+
if (tenants === false) return res.status(400).json({ error: 'x-verify-tenant must be { "l1": "<id>", … }', code: 'BAD_TENANT' });
|
|
63
|
+
var state = await userApiState(decoded.id, apiName, tenants);
|
|
60
64
|
if (state === 'enabled') return next();
|
|
61
65
|
refuse(res, state);
|
|
62
66
|
};
|
|
@@ -73,9 +77,11 @@ function accessMiddleware(options = {}) {
|
|
|
73
77
|
function accessGate() {
|
|
74
78
|
return async function(req, res, next) {
|
|
75
79
|
var path = (req.baseUrl || '') + (req.path || '');
|
|
80
|
+
var tenants = tenantsOfRequest(req);
|
|
81
|
+
if (tenants === false) return res.status(400).json({ error: 'x-verify-tenant must be { "l1": "<id>", … }', code: 'BAD_TENANT' });
|
|
76
82
|
var answer;
|
|
77
83
|
try {
|
|
78
|
-
answer = await accessService.requestApiState(req.user && req.user.id, req.method, path);
|
|
84
|
+
answer = await accessService.requestApiState(req.user && req.user.id, req.method, path, tenants);
|
|
79
85
|
} catch (err) {
|
|
80
86
|
if (req.log) req.log.error('access check failed: ' + err.message);
|
|
81
87
|
return res.status(503).json({ error: 'Access rules are unavailable; try again shortly' });
|
package/lib/accessService.js
CHANGED
|
@@ -4,6 +4,8 @@ const Api = require('../models/Api');
|
|
|
4
4
|
const UiPage = require('../models/UiPage');
|
|
5
5
|
const Menu = require('../models/Menu');
|
|
6
6
|
const UiElement = require('../models/UiElement');
|
|
7
|
+
const Role = require('../models/Role');
|
|
8
|
+
const UserTenantsMapping = require('../models/UserTenantsMapping');
|
|
7
9
|
const { visibleItems } = require('./menuService');
|
|
8
10
|
const { matchApi } = require('./apiMatch');
|
|
9
11
|
const licence = require('./licence');
|
|
@@ -13,18 +15,61 @@ const USER_ACCESS_TTL = 300; // 5 min — user's full access object
|
|
|
13
15
|
const API_RULES_TTL = 600; // 10 min — api public/role data (changes rarely)
|
|
14
16
|
|
|
15
17
|
// Cache key helpers
|
|
16
|
-
|
|
18
|
+
// With a company/workspace named, the answer includes the roles held there,
|
|
19
|
+
// so it is cached per tenant too. Both stay under access:user:<id>, which
|
|
20
|
+
// clearUserAccess() and clearAllAccess() clear.
|
|
21
|
+
const SLOT_KEYS = ['l1', 'l2', 'l3', 'l4'];
|
|
22
|
+
function tenantSuffix(tenants) {
|
|
23
|
+
if (!tenants) return '';
|
|
24
|
+
var parts = SLOT_KEYS.filter(function(k) { return tenants[k]; }).map(function(k) { return k + '=' + encodeURIComponent(String(tenants[k])); });
|
|
25
|
+
return parts.length ? ':t:' + parts.join('&') : '';
|
|
26
|
+
}
|
|
27
|
+
const userAccessKey = (userId, tenants) => `access:user:${userId}${tenantSuffix(tenants)}`;
|
|
28
|
+
const tenantRolesKey = (userId, tenants) => `access:user:${userId}:roles${tenantSuffix(tenants)}`;
|
|
17
29
|
const apiRulesKey = (apiName) => `access:api:${encodeURIComponent(apiName)}`;
|
|
18
30
|
const publicItemsKey = 'access:public';
|
|
19
31
|
const catalogKey = 'access:api:catalog'; // under access:api:*, so clearAccessRules() clears it
|
|
20
32
|
|
|
21
33
|
/**
|
|
22
|
-
*
|
|
34
|
+
* THE ROLES A USER HOLDS IN A COMPANY OR WORKSPACE — the roleId on their own
|
|
35
|
+
* membership rows (userTenantsMapping) for the values a request names.
|
|
36
|
+
* Whoever creates a company is its CompanyAdmin this way: in that company
|
|
37
|
+
* only, while their own role stays what it was everywhere else.
|
|
38
|
+
*
|
|
39
|
+
* Only the user's OWN rows count, so naming a company in a header can never
|
|
40
|
+
* give a role: without a membership row there, there is nothing to read
|
|
41
|
+
* (and /verify refuses the request as NOT_A_MEMBER first).
|
|
42
|
+
*
|
|
43
|
+
* @param tenants { l1: '<company>', l2: '<workspace>' }; absent → none
|
|
44
|
+
* @returns role ids, cached per user and tenant
|
|
45
|
+
*/
|
|
46
|
+
async function tenantRoleIdsOf(userId, tenants) {
|
|
47
|
+
if (!userId || !tenantSuffix(tenants)) return [];
|
|
48
|
+
var key = tenantRolesKey(userId, tenants);
|
|
49
|
+
var cached = await cache.get(key);
|
|
50
|
+
if (Array.isArray(cached)) return cached;
|
|
51
|
+
var rows = await UserTenantsMapping.query()
|
|
52
|
+
.where({ userId: userId, isActive: true })
|
|
53
|
+
.whereNotNull('roleId')
|
|
54
|
+
.where(function(q) {
|
|
55
|
+
SLOT_KEYS.forEach(function(k) {
|
|
56
|
+
if (tenants[k]) q.orWhere({ level: k, value: String(tenants[k]) });
|
|
57
|
+
});
|
|
58
|
+
})
|
|
59
|
+
.select('roleId');
|
|
60
|
+
var ids = [...new Set(rows.map(function(r) { return r.roleId; }))];
|
|
61
|
+
await cache.set(key, ids, USER_ACCESS_TTL);
|
|
62
|
+
return ids;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Fetch the full access object for a user — with `tenants`, as they are in
|
|
67
|
+
* that company/workspace: their own roles plus the ones held there.
|
|
23
68
|
* Cached in Redis. Use clearUserAccess() to invalidate.
|
|
24
69
|
*/
|
|
25
|
-
async function getUserAccess(userId) {
|
|
70
|
+
async function getUserAccess(userId, tenants) {
|
|
26
71
|
// Check cache first
|
|
27
|
-
const cached = await cache.get(userAccessKey(userId));
|
|
72
|
+
const cached = await cache.get(userAccessKey(userId, tenants));
|
|
28
73
|
if (cached) return cached;
|
|
29
74
|
|
|
30
75
|
const user = await User.query()
|
|
@@ -33,10 +78,18 @@ async function getUserAccess(userId) {
|
|
|
33
78
|
|
|
34
79
|
if (!user || !user.roles) {
|
|
35
80
|
const empty = { roles: [], pages: [], apis: [], menus: [], menuItems: [], elements: [] };
|
|
36
|
-
await cache.set(userAccessKey(userId), empty, USER_ACCESS_TTL);
|
|
81
|
+
await cache.set(userAccessKey(userId, tenants), empty, USER_ACCESS_TTL);
|
|
37
82
|
return empty;
|
|
38
83
|
}
|
|
39
84
|
|
|
85
|
+
// The roles held in the named company/workspace, beside the user's own.
|
|
86
|
+
const own = new Set(user.roles.map(function(r) { return r.id; }));
|
|
87
|
+
const scopedIds = (await tenantRoleIdsOf(userId, tenants)).filter(function(id) { return !own.has(id); });
|
|
88
|
+
const scoped = scopedIds.length
|
|
89
|
+
? await Role.query().findByIds(scopedIds).withGraphFetched('[apis, uiPages, uiElements, menus]')
|
|
90
|
+
: [];
|
|
91
|
+
const roles = user.roles.concat(scoped);
|
|
92
|
+
|
|
40
93
|
// Rows of a module this user is not licensed for are left out entirely:
|
|
41
94
|
// not greyed, not usable. See lib/licence.js.
|
|
42
95
|
const modules = await licence.modulesFor(userId);
|
|
@@ -65,7 +118,7 @@ async function getUserAccess(userId) {
|
|
|
65
118
|
}
|
|
66
119
|
}
|
|
67
120
|
|
|
68
|
-
for (const role of
|
|
121
|
+
for (const role of roles) {
|
|
69
122
|
roleNames.add(role.name);
|
|
70
123
|
sortInto(role.apis, apis, disabledApis);
|
|
71
124
|
sortInto(role.uiPages, pages, disabledPages);
|
|
@@ -112,7 +165,7 @@ async function getUserAccess(userId) {
|
|
|
112
165
|
}
|
|
113
166
|
};
|
|
114
167
|
|
|
115
|
-
await cache.set(userAccessKey(userId), access, USER_ACCESS_TTL);
|
|
168
|
+
await cache.set(userAccessKey(userId, tenants), access, USER_ACCESS_TTL);
|
|
116
169
|
return access;
|
|
117
170
|
}
|
|
118
171
|
|
|
@@ -231,13 +284,15 @@ async function userRoleIdsOf(userId) {
|
|
|
231
284
|
|
|
232
285
|
/**
|
|
233
286
|
* A user's state for a specific API: 'enabled' | 'disabled' | 'hidden'.
|
|
234
|
-
* Uses cached API rules and cached user roles
|
|
287
|
+
* Uses cached API rules and cached user roles — with `tenants`, the roles
|
|
288
|
+
* held in that company/workspace as well (tenantRoleIdsOf).
|
|
235
289
|
*/
|
|
236
|
-
async function userApiState(userId, apiName) {
|
|
290
|
+
async function userApiState(userId, apiName, tenants) {
|
|
237
291
|
var rule = await getApiRule(apiName);
|
|
238
292
|
if (rule.exists && !licence.allows(await licence.modulesFor(userId), rule.licenseModule)) return 'unlicensed';
|
|
239
293
|
if (!rule.exists || rule.isPublic || rule.unmapped) return 'enabled';
|
|
240
|
-
|
|
294
|
+
var ids = (await userRoleIdsOf(userId)).concat(await tenantRoleIdsOf(userId, tenants));
|
|
295
|
+
return apiStateFor(rule, ids);
|
|
241
296
|
}
|
|
242
297
|
|
|
243
298
|
/** Every API name in the catalog, cached like the other access rules. */
|
|
@@ -256,15 +311,15 @@ async function catalogApiNames() {
|
|
|
256
311
|
*
|
|
257
312
|
* @returns { api, state } api is the matched name, or null
|
|
258
313
|
*/
|
|
259
|
-
async function requestApiState(userId, method, path) {
|
|
314
|
+
async function requestApiState(userId, method, path, tenants) {
|
|
260
315
|
var api = matchApi(await catalogApiNames(), method, path);
|
|
261
316
|
if (!api) return { api: null, state: 'enabled' };
|
|
262
|
-
return { api: api, state: await userApiState(userId, api) };
|
|
317
|
+
return { api: api, state: await userApiState(userId, api, tenants) };
|
|
263
318
|
}
|
|
264
319
|
|
|
265
320
|
/** True only when the state is enabled. Kept for callers that want a yes/no. */
|
|
266
|
-
async function userHasApiAccess(userId, apiName) {
|
|
267
|
-
return (await userApiState(userId, apiName)) === 'enabled';
|
|
321
|
+
async function userHasApiAccess(userId, apiName, tenants) {
|
|
322
|
+
return (await userApiState(userId, apiName, tenants)) === 'enabled';
|
|
268
323
|
}
|
|
269
324
|
|
|
270
325
|
/**
|
|
@@ -274,6 +329,8 @@ async function userHasApiAccess(userId, apiName) {
|
|
|
274
329
|
async function clearUserAccess(userId) {
|
|
275
330
|
await Promise.all([
|
|
276
331
|
cache.del(userAccessKey(userId)),
|
|
332
|
+
// Per company/workspace, and the roles held there.
|
|
333
|
+
cache.delPattern(`access:user:${userId}:*`),
|
|
277
334
|
cache.del(`access:userRoles:${userId}`)
|
|
278
335
|
]);
|
|
279
336
|
}
|
|
@@ -303,6 +360,7 @@ module.exports = {
|
|
|
303
360
|
clearAllAccess,
|
|
304
361
|
getUserAccess,
|
|
305
362
|
requestApiState,
|
|
363
|
+
tenantRoleIdsOf,
|
|
306
364
|
userApiState,
|
|
307
365
|
userHasApiAccess,
|
|
308
366
|
clearUserAccess,
|
package/lib/authRouter.js
CHANGED
|
@@ -5,7 +5,7 @@ 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 { refusedTenant,
|
|
8
|
+
const { refusedTenant, readTenants } = require('./mtMembershipMiddleware');
|
|
9
9
|
const { accessGate } = require('./accessMiddleware');
|
|
10
10
|
|
|
11
11
|
// Signed in AND allowed this route by the catalog: the same two checks every
|
|
@@ -19,24 +19,6 @@ const User = require('../models/User');
|
|
|
19
19
|
// path on the user; serving it back over HTTP is the consuming app's concern
|
|
20
20
|
// (same as any other uploaded asset), so wire a static route to the same
|
|
21
21
|
// directory wherever it makes sense for your deployment.
|
|
22
|
-
/**
|
|
23
|
-
* x-verify-tenant → { l1: '…', … }, or null when it is not one: an object of
|
|
24
|
-
* known levels (l1–l4), each a non-empty id. Anything else is refused rather
|
|
25
|
-
* than read past — a check that cannot read what it was asked must not pass.
|
|
26
|
-
*/
|
|
27
|
-
function readTenants(header) {
|
|
28
|
-
var parsed;
|
|
29
|
-
try { parsed = JSON.parse(header); } catch (e) { return null; }
|
|
30
|
-
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
31
|
-
var keys = Object.keys(parsed);
|
|
32
|
-
if (!keys.length) return null;
|
|
33
|
-
for (var i = 0; i < keys.length; i++) {
|
|
34
|
-
var v = parsed[keys[i]];
|
|
35
|
-
if (SLOT_KEYS.indexOf(keys[i]) === -1 || typeof v !== 'string' || !v || v.length > 255) return null;
|
|
36
|
-
}
|
|
37
|
-
return parsed;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
22
|
const avatarUploader = new FileUploader({ allowedTypes: ['image/*'], maxSize: 2 * 1024 * 1024 });
|
|
41
23
|
|
|
42
24
|
function logError(req, err) {
|
|
@@ -261,9 +243,20 @@ function createAuthRouter(options = {}) {
|
|
|
261
243
|
}
|
|
262
244
|
});
|
|
263
245
|
|
|
246
|
+
// What this user may see and do — with x-verify-tenant ({ "l1": "<company>",
|
|
247
|
+
// "l2": "<workspace>" }), as they are THERE: their own roles plus the ones
|
|
248
|
+
// their membership gives them (the company they created: CompanyAdmin).
|
|
249
|
+
// Not a member → 403 NOT_A_MEMBER, as /verify answers.
|
|
264
250
|
router.get('/me', signedInAndAllowed, async function(req, res) {
|
|
265
251
|
try {
|
|
266
|
-
|
|
252
|
+
var tenants = null;
|
|
253
|
+
if (req.headers['x-verify-tenant']) {
|
|
254
|
+
tenants = readTenants(req.headers['x-verify-tenant']);
|
|
255
|
+
if (!tenants) return res.status(400).json({ error: 'x-verify-tenant must be { "l1": "<id>", … }', code: 'BAD_TENANT' });
|
|
256
|
+
var notMember = await refusedTenant(req.user, tenants);
|
|
257
|
+
if (notMember) return res.status(403).json({ error: 'Not a member of ' + notMember.level + ' "' + notMember.value + '"', code: 'NOT_A_MEMBER' });
|
|
258
|
+
}
|
|
259
|
+
const access = await getUserAccess(req.user.id, tenants);
|
|
267
260
|
res.json({
|
|
268
261
|
user: req.user,
|
|
269
262
|
access
|
|
@@ -303,9 +296,12 @@ function createAuthRouter(options = {}) {
|
|
|
303
296
|
return res.status(403).json({ error: 'Not a member of ' + refused.level + ' "' + refused.value + '"', code: 'NOT_A_MEMBER' });
|
|
304
297
|
}
|
|
305
298
|
}
|
|
306
|
-
|
|
299
|
+
// The roles held in the named company/workspace count too: whoever
|
|
300
|
+
// created a company is its CompanyAdmin there (accessService
|
|
301
|
+
// tenantRoleIdsOf), and only there.
|
|
302
|
+
var answer = await requestApiState(req.user.id, method, path, tenants);
|
|
307
303
|
if (answer.state === 'enabled') {
|
|
308
|
-
var access = await getUserAccess(req.user.id);
|
|
304
|
+
var access = await getUserAccess(req.user.id, tenants);
|
|
309
305
|
var ok = { user: req.user, access: access, state: 'enabled', api: answer.api };
|
|
310
306
|
if (tenants) ok.tenant = 'checked';
|
|
311
307
|
return res.json(ok);
|
package/lib/authService.js
CHANGED
|
@@ -379,22 +379,43 @@ async function login({ email, password }) {
|
|
|
379
379
|
* activation token. Sends an "accept invite" email pointing the user to a page
|
|
380
380
|
* where they set their own password and activate.
|
|
381
381
|
*
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
*
|
|
382
|
+
* On an email that already has an account:
|
|
383
|
+
* - activated: returned as it is — nothing sent, nothing changed;
|
|
384
|
+
* - NOT activated (never accepted, the link lost or broken): INVITED AGAIN —
|
|
385
|
+
* a fresh link replaces the old one and the email goes out again
|
|
386
|
+
* (`resent: true`). Nobody is left with an account they cannot get into.
|
|
387
|
+
* The caller can then layer additional roles/mappings on top (isNew only).
|
|
385
388
|
*/
|
|
386
389
|
async function invite({ email, name, phoneNumber, invitedBy, inviterName, appName, knex }) {
|
|
387
390
|
const UserM = knex ? User.bindKnex(knex) : User;
|
|
388
391
|
const normalized = normalizeEmail(email);
|
|
389
392
|
|
|
390
393
|
const existing = await UserM.query().findOne({ normalizedEmail: normalized });
|
|
394
|
+
if (existing && existing.isActivated) {
|
|
395
|
+
return {
|
|
396
|
+
id: existing.id,
|
|
397
|
+
email: existing.email,
|
|
398
|
+
name: existing.name,
|
|
399
|
+
isNew: false,
|
|
400
|
+
isActivated: true
|
|
401
|
+
};
|
|
402
|
+
}
|
|
391
403
|
if (existing) {
|
|
404
|
+
const freshToken = crypto.randomBytes(32).toString('hex');
|
|
405
|
+
await UserM.query().findById(existing.id).patch({
|
|
406
|
+
activationToken: freshToken,
|
|
407
|
+
recordModifiedDate: formatDbDateTime(),
|
|
408
|
+
recordModifiedBy: invitedBy || existing.id
|
|
409
|
+
});
|
|
410
|
+
await sendInviteEmail(email, name || existing.name, inviterName, appName, freshToken);
|
|
411
|
+
await hooks.fire('user', 'update', existing.id);
|
|
392
412
|
return {
|
|
393
413
|
id: existing.id,
|
|
394
414
|
email: existing.email,
|
|
395
415
|
name: existing.name,
|
|
396
416
|
isNew: false,
|
|
397
|
-
isActivated:
|
|
417
|
+
isActivated: false,
|
|
418
|
+
resent: true
|
|
398
419
|
};
|
|
399
420
|
}
|
|
400
421
|
|
|
@@ -422,12 +443,26 @@ async function invite({ email, name, phoneNumber, invitedBy, inviterName, appNam
|
|
|
422
443
|
recordModifiedBy: inviter
|
|
423
444
|
});
|
|
424
445
|
|
|
446
|
+
await sendInviteEmail(email, name, inviterName, appName, activationToken);
|
|
447
|
+
|
|
448
|
+
await hooks.fire('user', 'create', user.id);
|
|
449
|
+
|
|
450
|
+
return {
|
|
451
|
+
id: user.id,
|
|
452
|
+
email: user.email,
|
|
453
|
+
name: user.name,
|
|
454
|
+
isNew: true,
|
|
455
|
+
isActivated: false
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** The invite email: the link where they set their password and accept. */
|
|
460
|
+
async function sendInviteEmail(email, name, inviterName, appName, activationToken) {
|
|
425
461
|
const inviteUrl = linkFor('invite');
|
|
426
462
|
if (!inviteUrl) {
|
|
427
463
|
throw new Error('AUTH_INVITE_URL is required to send invite emails (the full address of your ' +
|
|
428
464
|
'accept-invite page, e.g. http://localhost:19100/auth/accept-invite).');
|
|
429
465
|
}
|
|
430
|
-
|
|
431
466
|
const acceptLink = withToken(inviteUrl, activationToken);
|
|
432
467
|
const app = appName || 'the app';
|
|
433
468
|
const subject = 'You have been invited to ' + app;
|
|
@@ -436,30 +471,19 @@ async function invite({ email, name, phoneNumber, invitedBy, inviterName, appNam
|
|
|
436
471
|
+ (inviterName ? '<p>' + inviterName + ' has invited you to join ' + app + '.</p>' : '<p>You have been invited to join ' + app + '.</p>')
|
|
437
472
|
+ '<p>Click below to set your password and accept the invite:</p>'
|
|
438
473
|
+ '<p><a href="' + acceptLink + '">' + acceptLink + '</a></p>';
|
|
439
|
-
|
|
440
474
|
await sendEmail(email, subject, html);
|
|
441
|
-
|
|
442
|
-
await hooks.fire('user', 'create', user.id);
|
|
443
|
-
|
|
444
|
-
return {
|
|
445
|
-
id: user.id,
|
|
446
|
-
email: user.email,
|
|
447
|
-
name: user.name,
|
|
448
|
-
isNew: true,
|
|
449
|
-
isActivated: false
|
|
450
|
-
};
|
|
451
475
|
}
|
|
452
476
|
|
|
453
477
|
/**
|
|
454
478
|
* Preview an invite — returns invitee info if the token matches a pending
|
|
455
|
-
* invite (user exists
|
|
479
|
+
* invite (user exists and is not activated). A password set meanwhile — by a
|
|
480
|
+
* reset, say — does not stop it: accepting sets the password again.
|
|
456
481
|
*/
|
|
457
482
|
async function previewInvite(token, options = {}) {
|
|
458
483
|
const UserM = options.knex ? User.bindKnex(options.knex) : User;
|
|
459
484
|
const user = await UserM.query().findOne({ activationToken: token });
|
|
460
485
|
if (!user) throw new Error('Invalid or expired invite');
|
|
461
486
|
if (user.isActivated) throw new Error('Invite already accepted');
|
|
462
|
-
if (user.pwd) throw new Error('This account already has a password — use the activation link instead');
|
|
463
487
|
|
|
464
488
|
return { email: user.email, name: user.name };
|
|
465
489
|
}
|
|
@@ -561,6 +585,7 @@ async function resetPassword({ token, newPassword }) {
|
|
|
561
585
|
}
|
|
562
586
|
|
|
563
587
|
const { hash, salt } = await hashPassword(newPassword);
|
|
588
|
+
const invited = !user.pwd;
|
|
564
589
|
|
|
565
590
|
await User.query().findById(user.id).patch({
|
|
566
591
|
pwd: hash,
|
|
@@ -570,6 +595,21 @@ async function resetPassword({ token, newPassword }) {
|
|
|
570
595
|
recordModifiedDate: formatDbDateTime()
|
|
571
596
|
});
|
|
572
597
|
|
|
598
|
+
// A RESET PROVES THE ADDRESS, as an activation or invite link does — the
|
|
599
|
+
// link was opened from that inbox. So an account never activated is
|
|
600
|
+
// activated now, instead of being left with a password it cannot sign in
|
|
601
|
+
// with. Invited (no password until now): as accepting the invite does — its
|
|
602
|
+
// roles came with the invite. Signed up: as the activation link does — with
|
|
603
|
+
// the sign-up roles.
|
|
604
|
+
if (!user.isActivated) {
|
|
605
|
+
if (invited) {
|
|
606
|
+
const now = formatDbDateTime();
|
|
607
|
+
await User.query().findById(user.id).patch({ isActivated: true, activatedOn: now, activatedBy: user.id, activationToken: null, recordModifiedDate: now });
|
|
608
|
+
} else {
|
|
609
|
+
await markActivated(user, user.id);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
573
613
|
await destroyAllUserSessions(user.id);
|
|
574
614
|
await clearUserAccess(user.id);
|
|
575
615
|
|
|
@@ -54,6 +54,45 @@ async function refusedTenant(user, tenants, Model) {
|
|
|
54
54
|
return null;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/**
|
|
58
|
+
* x-verify-tenant → { l1: '…', … }, or null when it is not one: an object of
|
|
59
|
+
* known levels (l1–l4), each a non-empty id. Anything else is refused rather
|
|
60
|
+
* than read past — a check that cannot read what it was asked must not pass.
|
|
61
|
+
*/
|
|
62
|
+
function readTenants(header) {
|
|
63
|
+
var parsed;
|
|
64
|
+
try { parsed = JSON.parse(header); } catch (e) { return null; }
|
|
65
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
66
|
+
var keys = Object.keys(parsed);
|
|
67
|
+
if (!keys.length) return null;
|
|
68
|
+
for (var i = 0; i < keys.length; i++) {
|
|
69
|
+
var v = parsed[keys[i]];
|
|
70
|
+
if (SLOT_KEYS.indexOf(keys[i]) === -1 || typeof v !== 'string' || !v || v.length > 255) return null;
|
|
71
|
+
}
|
|
72
|
+
return parsed;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The company/workspace a request is about, as levels: x-verify-tenant when
|
|
77
|
+
* it says (an app's gate asking /verify, a UI asking /me), else the app's own
|
|
78
|
+
* MT headers when this process registered them. null when neither names one;
|
|
79
|
+
* false when x-verify-tenant is there but unreadable.
|
|
80
|
+
*/
|
|
81
|
+
function tenantsOfRequest(req) {
|
|
82
|
+
var header = req.headers && req.headers['x-verify-tenant'];
|
|
83
|
+
if (header) return readTenants(header) || false;
|
|
84
|
+
var mtConfig;
|
|
85
|
+
try { mtConfig = getMtConfig(); } catch (e) { return null; }
|
|
86
|
+
if (!mtConfig || !mtConfig.enabled) return null;
|
|
87
|
+
var tenants = {};
|
|
88
|
+
SLOT_KEYS.forEach(function(key) {
|
|
89
|
+
var slot = mtConfig.slots[key];
|
|
90
|
+
var value = slot && req.headers[slot.header];
|
|
91
|
+
if (typeof value === 'string' && value) tenants[key] = value;
|
|
92
|
+
});
|
|
93
|
+
return Object.keys(tenants).length ? tenants : null;
|
|
94
|
+
}
|
|
95
|
+
|
|
57
96
|
function mtMembershipMiddleware(options) {
|
|
58
97
|
options = options || {};
|
|
59
98
|
var Model = options.userTenantsMapping || UserTenantsMapping;
|
|
@@ -83,3 +122,5 @@ function mtMembershipMiddleware(options) {
|
|
|
83
122
|
module.exports = mtMembershipMiddleware;
|
|
84
123
|
module.exports.refusedTenant = refusedTenant;
|
|
85
124
|
module.exports.SLOT_KEYS = SLOT_KEYS;
|
|
125
|
+
module.exports.readTenants = readTenants;
|
|
126
|
+
module.exports.tenantsOfRequest = tenantsOfRequest;
|