@xeplr/auth 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -10
- package/index.js +37 -13
- package/lib/adminRouter.js +27 -12
- package/lib/authRouter.js +75 -5
- package/lib/authService.js +199 -56
- package/lib/mtMembershipMiddleware.js +36 -19
- package/lib/userRoles.js +76 -0
- package/migrations/0014_activation_routes.sql +47 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -101,7 +101,7 @@ await auth.service.invite({ email, name, invitedBy, inviterName, appName })
|
|
|
101
101
|
|
|
102
102
|
### Required
|
|
103
103
|
|
|
104
|
-
Everything in `requiredEnv`, plus a connection and an
|
|
104
|
+
Everything in `requiredEnv`, plus a connection. `requiredEnv` includes the sign-up settings — `AUTH_REGISTER_ROLES`, `AUTH_ACTIVATION_URL` and `AUTH_RESET_URL` — so an app that spreads it into its `env.required.js` refuses to start (and `check-env` fails) without them: the sign-in service would run, but nobody new could get in. The two link settings are asked for as `AUTH_ACTIVATION_BASE_URL` instead when an install uses that older form. Started without them anyway, each flow refuses with `503` naming the variable, and the banner shows `✗ NOT SET`.
|
|
105
105
|
|
|
106
106
|
| variable | default in code | meaning |
|
|
107
107
|
|---|---|---|
|
|
@@ -115,14 +115,17 @@ Everything in `requiredEnv`, plus a connection and an activation link.
|
|
|
115
115
|
| `AUTH_SUPER_ADMIN_PASSWORD` | — | its password; no quotes, spaces, `$` or `#` (substituted into SQL) |
|
|
116
116
|
| `XEPLR_AUTH_MIGRATIONS` | none | comma-separated app migration directories, run after auth's own — [details](#migrations) |
|
|
117
117
|
| `AUTH_TENANT_HEADER` | — | the header that names the company a role is created in (e.g. `x-company-id`), or `none` for a single-tenant app. No default: a multi-tenant app that forgot it would make every role visible to every company — [details](#roles-belong-to-a-company) |
|
|
118
|
-
| `AUTH_ACTIVATION_URL` | — | full address of your activation page, e.g. `http://localhost:19100/auth/activate`; `?token=…` is appended. The older `AUTH_ACTIVATION_BASE_URL` (below) also satisfies it — `requiredEnv.activationLinkVar` names whichever the install uses.
|
|
118
|
+
| `AUTH_ACTIVATION_URL` | — | full address of your activation page, e.g. `http://localhost:19100/auth/activate`; `?token=…` is appended. The older `AUTH_ACTIVATION_BASE_URL` (below) also satisfies it — `requiredEnv.activationLinkVar` names whichever the install uses. Without it registration and resend-activation are refused |
|
|
119
|
+
| `AUTH_REGISTER_ROLES` | — (refused) | the role(s) a self-registered account gets when it is activated, comma-separated, e.g. `Viewer`. **No default, on purpose:** an account with no role has every role-mapped API hidden — its own profile included — so it can sign in and do nothing. Which role fits is each app's decision. Unset, a name that is not a generic (`mtId1 = '*'`) role, or a system role (Super Admin) → registration is refused |
|
|
120
|
+
| `AUTH_RESET_URL` | — (refused) | full address of your reset-password page, e.g. `http://localhost:19100/auth/reset-password`; `?token=…` is appended. Derived from `AUTH_ACTIVATION_BASE_URL` when only that is set. **Never taken from the request:** a link built from the `Host` header lets anyone have us mail a real user a reset link to their own site. Unset → forgot-password is refused |
|
|
121
|
+
| email (`EMAIL_PROVIDER` + its settings, below) | — | registration, resend-activation, invites and password reset all send a link. `boot()` checks mail at startup; when it is known not to work those routes refuse up front (`503`, `EMAIL_NOT_SET_UP`) rather than create an account whose link never goes out |
|
|
119
122
|
|
|
120
123
|
### Optional
|
|
121
124
|
|
|
122
125
|
| variable | default | meaning |
|
|
123
126
|
|---|---|---|
|
|
124
127
|
| `AUTH_INVITE_URL` | derived | full address of your accept-invite page; `?token=…` is appended |
|
|
125
|
-
| `AUTH_ACTIVATION_BASE_URL` | — | older form: an origin; `/auth/activate` and `/auth/
|
|
128
|
+
| `AUTH_ACTIVATION_BASE_URL` | — | older form: an origin; `/auth/activate`, `/auth/accept-invite` and `/auth/reset-password` are appended when the URLs above are unset |
|
|
126
129
|
| `AUTH_ACCESS_TOKEN_TTL_MINUTES` | `15` | access token lifetime |
|
|
127
130
|
| `AUTH_REFRESH_TOKEN_TTL_DAYS` | `7` | refresh token (session) lifetime |
|
|
128
131
|
| `AUTH_ACCESS_TOKEN_TOLERANCE_SECONDS` | `0` | grace after expiry during which a token is still served and slid; `0` turns sliding refresh off |
|
|
@@ -246,6 +249,7 @@ Auth's own migrations:
|
|
|
246
249
|
| `0011_verify_api` | the `GET /auth/api/verify` row, public in the catalog |
|
|
247
250
|
| `0012_default_role_access` | auth's own routes mapped to its default roles: `account:*` to every role, `users:*` `access:*` `settings:*` to Admin, system APIs to nobody but Super Admin |
|
|
248
251
|
| `0013_mapping_state` | `state` (`enabled` / `disabled`) on the four role-mapping tables, default `enabled`; the `module-states` and `module-state` rows, mapped to Super Admin and Admin |
|
|
252
|
+
| `0014_activation_routes` | rows for `resend-activation` (public) and `admin/users/:id/activate` (`users:edit` → Super Admin, Admin), plus three routes that shipped without one: `invite-preview` and `invite-accept` (public) and `sse-ticket` (`account:view` → every base role — before this it was open to anyone); the public `Resend Activation` and `Accept Invite` pages |
|
|
249
253
|
|
|
250
254
|
## The first account
|
|
251
255
|
|
|
@@ -282,19 +286,27 @@ Client code must read the header and replace its stored token, or the session en
|
|
|
282
286
|
|
|
283
287
|
## Routes
|
|
284
288
|
|
|
289
|
+
### Sign-up and activation
|
|
290
|
+
|
|
291
|
+
1. **Register** — every check that can refuse runs *before* the account is written, and the activation mail is sent inside the same transaction, so a refusal or a failed send leaves nothing behind.
|
|
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
|
+
3. **Lost the mail?** `POST /resend-activation` sends a new link.
|
|
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
|
+
|
|
285
296
|
### `/auth/api`
|
|
286
297
|
|
|
287
298
|
| route | token | body / query → response |
|
|
288
299
|
|---|---|---|
|
|
289
|
-
| `POST /register` | — | `{ email, password, name?, phoneNumber? }` → `201 { message, user }`; `409` if the email is registered. Sends the activation email |
|
|
290
|
-
| `
|
|
300
|
+
| `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
|
+
| `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
|
+
| `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) |
|
|
291
303
|
| `GET /invite-preview` | — | `?token=…` → `{ email, name }` |
|
|
292
304
|
| `POST /invite-accept` | — | `{ token, password, name? }` → sets the password and activates |
|
|
293
|
-
| `POST /login` | — | `{ email, password }` → `{ accessToken, refreshToken, user, access }`; `401` wrong password or deactivated; `403` not yet activated |
|
|
305
|
+
| `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 |
|
|
294
306
|
| `POST /refresh` | — | `{ refreshToken }` → a new `{ accessToken, refreshToken, user, access }` |
|
|
295
307
|
| `POST /logout` | — | `{ refreshToken }` → ends that session |
|
|
296
|
-
| `POST /forgot-password` | — | `{ email }` → the same message whether or not the address exists; emails `<resetBaseUrl>/auth/reset-password
|
|
297
|
-
| `POST /reset-password` | — | `{ token, newPassword }` |
|
|
308
|
+
| `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` |
|
|
298
310
|
| `GET /me` | ✓ | `{ user, access }` — `user` is the token's claims |
|
|
299
311
|
| `GET /verify` | ✓ | the check every app's gate makes on every request — see [Every request is checked](#every-request-is-checked) |
|
|
300
312
|
| `GET /profile` · `PUT /profile` | ✓ | `{ id, email, name, phoneNumber, phoneVerified, profilePicUrl, isActivated }`; PUT takes `name`, `phoneNumber`, `email` |
|
|
@@ -310,7 +322,8 @@ Client code must read the header and replace its stored token, or the session en
|
|
|
310
322
|
|
|
311
323
|
| route | |
|
|
312
324
|
|---|---|
|
|
313
|
-
| `GET /users` | users with their roles |
|
|
325
|
+
| `GET /users` | users with their roles, `isActivated`, and `invitePending` (invited, no password set yet — they activate by accepting the invite) |
|
|
326
|
+
| `POST /users/:id/activate` | `users:edit` — activates an account without its emailed link and grants the `AUTH_REGISTER_ROLES` roles; `409` if already activated or invited without a password yet |
|
|
314
327
|
| `GET /roles` | `[{ id, name, scope, mtId1 }]`: the current company's roles and the generic ones; system roles only for Super Admin |
|
|
315
328
|
| `GET /access-items` | `{ apis, pages, elements, menus }`, each with its roles |
|
|
316
329
|
| `POST /user-role` | `{ userId, roleId, assign }` — grant or remove a role |
|
|
@@ -509,15 +522,20 @@ GET /auth/api/verify
|
|
|
509
522
|
Authorization: Bearer <the caller's token>
|
|
510
523
|
x-verify-method: GET
|
|
511
524
|
x-verify-path: /widget-templates/abc
|
|
525
|
+
x-verify-tenant: {"l1":"<company>","l2":"<workspace>"} ← when the request names one
|
|
512
526
|
```
|
|
513
527
|
|
|
528
|
+
**And whether the user belongs to the company and workspace the request names.** The gate sends them as `x-verify-tenant`, by level (`l1`–`l4`, as memberships are kept — auth needs no app's header names). A user without an active membership for each is refused here, `403 NOT_A_MEMBER`, before the app sees the request; Super Admin belongs to every one. This is the same check as `mtMembershipMiddleware` (`refusedTenant`, one function), so an app on `createApp` never adds it route by route. The answer carries `tenant: 'checked'` whenever it checked, so a gate can refuse an older auth that would have ignored the header.
|
|
529
|
+
|
|
514
530
|
| answer | when |
|
|
515
531
|
|---|---|
|
|
516
|
-
| `200 { user, access, state: 'enabled', api }` | token good, API allowed. `api` is the catalog row it matched, or `null` (not registered, so open) |
|
|
532
|
+
| `200 { user, access, state: 'enabled', api, tenant? }` | token good, API allowed (and, with `x-verify-tenant`, a member of each: `tenant: 'checked'`). `api` is the catalog row it matched, or `null` (not registered, so open) |
|
|
517
533
|
| `403 { code: 'DISABLED' }` · `403 { code: 'HIDDEN' }` | token good, API not allowed |
|
|
518
534
|
| `403 { code: 'UNLICENSED' }` | token good, but the API belongs to a module the user's licence does not include |
|
|
519
535
|
| `401` | bad or expired token (the same tolerance and `X-New-Token` sliding as every route) |
|
|
520
536
|
| `400 { code: 'NO_REQUEST' }` | no method or path named: nothing to check, so refused |
|
|
537
|
+
| `403 { code: 'NOT_A_MEMBER' }` | token good, but no membership for a company or workspace in `x-verify-tenant` |
|
|
538
|
+
| `400 { code: 'BAD_TENANT' }` | `x-verify-tenant` is not `{ "l1": "<id>", … }` of known levels: refused, never read past |
|
|
521
539
|
|
|
522
540
|
**Which row a request is.** A catalog name is `METHOD path` or a bare path (every method), and a path may hold `:params`: `GET /widget-templates/:id` covers `GET /widget-templates/abc`. When several rows fit, more literal segments win, then a row with a method over one without (`lib/apiMatch.js`). The catalog names are cached under `access:api:catalog`, cleared with the other rules.
|
|
523
541
|
|
|
@@ -616,6 +634,10 @@ Hooks run in the process that did the work — register them in the same script
|
|
|
616
634
|
npm test # node --test test/*.test.js
|
|
617
635
|
```
|
|
618
636
|
|
|
637
|
+
`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
|
+
|
|
639
|
+
`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
|
+
|
|
619
641
|
`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.
|
|
620
642
|
|
|
621
643
|
## License
|
package/index.js
CHANGED
|
@@ -111,8 +111,8 @@ async function start(config = {}) {
|
|
|
111
111
|
//
|
|
112
112
|
// Not a hole. createAuthRouter gates its own protected routes per-route
|
|
113
113
|
// with authMiddleware (/me, /profile, /change-password, /sse-ticket, and
|
|
114
|
-
// all of /admin). What is left open — login, register,
|
|
115
|
-
// forgot/reset-password — is open by design, because it is how a caller
|
|
114
|
+
// all of /admin). What is left open — login, register, resend-activation,
|
|
115
|
+
// activate, refresh, forgot/reset-password — is open by design, because it is how a caller
|
|
116
116
|
// obtains a token in the first place.
|
|
117
117
|
auth: false,
|
|
118
118
|
corsOptions: config.corsOptions,
|
|
@@ -217,11 +217,15 @@ async function boot() {
|
|
|
217
217
|
// reset) cannot be sent, and the banner says so rather than the first
|
|
218
218
|
// person to register finding out.
|
|
219
219
|
var email = await emailStatus();
|
|
220
|
+
// Registration and reset refuse up front when mail is known not to work,
|
|
221
|
+
// instead of creating an account whose link never goes out.
|
|
222
|
+
authService.configureEmailStatus(email.unknown ? null : email.ok);
|
|
220
223
|
authService.configureActivation({
|
|
221
224
|
// Fully qualified, one per link — the token is the only thing appended.
|
|
222
225
|
// AUTH_ACTIVATION_BASE_URL still works as an origin; see configureActivation.
|
|
223
226
|
activationUrl: process.env.AUTH_ACTIVATION_URL || null,
|
|
224
227
|
inviteUrl: process.env.AUTH_INVITE_URL || null,
|
|
228
|
+
resetUrl: process.env.AUTH_RESET_URL || null,
|
|
225
229
|
baseUrl: process.env.AUTH_ACTIVATION_BASE_URL || null
|
|
226
230
|
});
|
|
227
231
|
|
|
@@ -251,9 +255,9 @@ async function emailStatus() {
|
|
|
251
255
|
|
|
252
256
|
function warnNoEmail(email) {
|
|
253
257
|
console.warn('[xeplr-auth] EMAIL IS NOT WORKING — ' + String(email.detail).replace(/\.$/, '') + '.');
|
|
254
|
-
console.warn(' Sign-in keeps working. Registration,
|
|
255
|
-
console.warn('
|
|
256
|
-
console.warn(' EMAIL_PROVIDER (smtp, brevo, aws or azure) and its settings.\n');
|
|
258
|
+
console.warn(' Sign-in keeps working. Registration, resending activation links,');
|
|
259
|
+
console.warn(' invites and password resets are refused until this is fixed:');
|
|
260
|
+
console.warn(' set EMAIL_PROVIDER (smtp, brevo, aws or azure) and its settings.\n');
|
|
257
261
|
}
|
|
258
262
|
|
|
259
263
|
function describeEmail(email) {
|
|
@@ -274,6 +278,8 @@ function banner(email) {
|
|
|
274
278
|
[migrationsVar('auth'), migrationsFor('auth') || '(none)'],
|
|
275
279
|
['activation url', process.env.AUTH_ACTIVATION_URL || process.env.AUTH_ACTIVATION_BASE_URL || '(none)'],
|
|
276
280
|
['invite url', process.env.AUTH_INVITE_URL || '(derived)'],
|
|
281
|
+
['reset url', process.env.AUTH_RESET_URL || (process.env.AUTH_ACTIVATION_BASE_URL ? '(derived)' : '✗ NOT SET, password reset refused')],
|
|
282
|
+
['sign-up roles', process.env.AUTH_REGISTER_ROLES || '✗ NOT SET, registration refused'],
|
|
277
283
|
['access token ttl', (process.env.AUTH_ACCESS_TOKEN_TTL_MINUTES || '15') + 'm'],
|
|
278
284
|
['refresh token ttl', (process.env.AUTH_REFRESH_TOKEN_TTL_DAYS || '7') + 'd'],
|
|
279
285
|
['slide tolerance', (process.env.AUTH_ACCESS_TOKEN_TOLERANCE_SECONDS || '0') + 's'],
|
|
@@ -326,6 +332,7 @@ function attach() {
|
|
|
326
332
|
// AUTH_ACTIVATION_BASE_URL still works as an origin; see configureActivation.
|
|
327
333
|
activationUrl: process.env.AUTH_ACTIVATION_URL || null,
|
|
328
334
|
inviteUrl: process.env.AUTH_INVITE_URL || null,
|
|
335
|
+
resetUrl: process.env.AUTH_RESET_URL || null,
|
|
329
336
|
baseUrl: process.env.AUTH_ACTIVATION_BASE_URL || null
|
|
330
337
|
});
|
|
331
338
|
return _conn;
|
|
@@ -348,11 +355,6 @@ function attach() {
|
|
|
348
355
|
var requiredEnv = [
|
|
349
356
|
'ENCRYPTION_KEY',
|
|
350
357
|
'AUTH_JWT_SECRET',
|
|
351
|
-
// NOT listed literally: the activation link can be given either as
|
|
352
|
-
// AUTH_ACTIVATION_URL (fully qualified, preferred) or as the older
|
|
353
|
-
// AUTH_ACTIVATION_BASE_URL (an origin). checkEnv takes a list of names and
|
|
354
|
-
// demands every one, which would refuse to boot an install that configured
|
|
355
|
-
// the new form. The getter below asks for whichever is actually in use.
|
|
356
358
|
'AUTH_PORT',
|
|
357
359
|
'AUTH_DB_NAME', // auth db (api reaches it via attach())
|
|
358
360
|
'XEPLR_AUTH_MIGRATIONS', // migrations run via migrate:up
|
|
@@ -380,11 +382,33 @@ var requiredEnv = [
|
|
|
380
382
|
// forgot it would create every role as '*' — visible to every company —
|
|
381
383
|
// and nothing would look wrong. See lib/tenant.js.
|
|
382
384
|
'AUTH_TENANT_HEADER',
|
|
385
|
+
|
|
386
|
+
// THE SIGN-UP FLOW. Without these the service starts and signs people in,
|
|
387
|
+
// but nobody new can get in: registration, activation and password reset
|
|
388
|
+
// each refuse. That shows up as the first person to register finding out,
|
|
389
|
+
// so it is refused here, before anything starts. See README "Sign-up and
|
|
390
|
+
// activation".
|
|
391
|
+
//
|
|
392
|
+
// The role a new account gets when it is activated — no default, each app
|
|
393
|
+
// names its own (e.g. Viewer).
|
|
394
|
+
'AUTH_REGISTER_ROLES',
|
|
395
|
+
|
|
396
|
+
// The two links that go out by email. Each can be given fully qualified
|
|
397
|
+
// (preferred) or derived from the older AUTH_ACTIVATION_BASE_URL origin, so
|
|
398
|
+
// the name asked for is whichever form this install uses: demanding the new
|
|
399
|
+
// name would refuse an install correctly configured the old way.
|
|
400
|
+
linkVar('AUTH_ACTIVATION_URL'),
|
|
401
|
+
linkVar('AUTH_RESET_URL'),
|
|
383
402
|
];
|
|
384
403
|
|
|
385
|
-
//
|
|
386
|
-
//
|
|
387
|
-
|
|
404
|
+
// Decided when this module loads, which is after the launcher (dotenv -e …)
|
|
405
|
+
// has filled process.env — so the list names the form actually in use.
|
|
406
|
+
function linkVar(name) {
|
|
407
|
+
return process.env.AUTH_ACTIVATION_BASE_URL && !process.env[name] ? 'AUTH_ACTIVATION_BASE_URL' : name;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// Kept for callers that read it; the list above now carries the same name.
|
|
411
|
+
// Read at ACCESS time so it reflects the .env the app has already loaded.
|
|
388
412
|
Object.defineProperty(requiredEnv, 'activationLinkVar', {
|
|
389
413
|
enumerable: false,
|
|
390
414
|
get: function () {
|
package/lib/adminRouter.js
CHANGED
|
@@ -5,6 +5,8 @@ var { accessGate } = require('./accessMiddleware');
|
|
|
5
5
|
var { createMenuService } = require('./menuService');
|
|
6
6
|
var authMiddleware = require('./authMiddleware');
|
|
7
7
|
var hooks = require('./hooks');
|
|
8
|
+
var { grantRoles } = require('./userRoles');
|
|
9
|
+
var { adminActivate } = require('./authService');
|
|
8
10
|
var { isSuperAdmin, systemScopeGuard, SUPER_ADMIN_ROLE } = require('./systemScope');
|
|
9
11
|
var { tenantOf, visibleTenants, GENERIC } = require('./tenant');
|
|
10
12
|
var User = require('../models/User');
|
|
@@ -99,8 +101,10 @@ function createAdminRouter() {
|
|
|
99
101
|
// ─── Users with their roles ───
|
|
100
102
|
router.get('/users', async function(req, res) {
|
|
101
103
|
try {
|
|
104
|
+
// invitePending: invited and has not set a password yet — activated by
|
|
105
|
+
// accepting the invite, never by an admin. Only the fact leaves here.
|
|
102
106
|
var users = await User.query()
|
|
103
|
-
.select('id', 'email', 'name', 'isActive', 'isActivated')
|
|
107
|
+
.select('id', 'email', 'name', 'isActive', 'isActivated', User.raw('("pwd" IS NULL) as "invitePending"'))
|
|
104
108
|
.withGraphFetched('roles');
|
|
105
109
|
res.json(users);
|
|
106
110
|
} catch (err) {
|
|
@@ -108,6 +112,26 @@ function createAdminRouter() {
|
|
|
108
112
|
}
|
|
109
113
|
});
|
|
110
114
|
|
|
115
|
+
// ─── Activate an account by hand ───
|
|
116
|
+
// For someone whose activation mail never arrived, or an app that approves
|
|
117
|
+
// sign-ups itself. Gives the account the same sign-up roles the emailed
|
|
118
|
+
// link would (AUTH_REGISTER_ROLES).
|
|
119
|
+
router.post('/users/:id/activate', async function(req, res) {
|
|
120
|
+
try {
|
|
121
|
+
var user = await adminActivate(req.params.id, req.user ? req.user.id : null);
|
|
122
|
+
res.json({ message: 'Account activated', user: user });
|
|
123
|
+
} catch (err) {
|
|
124
|
+
if (err.code === 'USER_NOT_FOUND') return res.status(404).json({ error: err.message, code: err.code });
|
|
125
|
+
if (err.code === 'ALREADY_ACTIVATED' || err.code === 'INVITE_PENDING') {
|
|
126
|
+
return res.status(409).json({ error: err.message, code: err.code });
|
|
127
|
+
}
|
|
128
|
+
if (err.code && err.code.indexOf('REGISTER_ROLES_') === 0) {
|
|
129
|
+
return res.status(503).json({ error: err.message, code: err.code });
|
|
130
|
+
}
|
|
131
|
+
res.status(500).json({ error: 'Something went wrong' });
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
|
|
111
135
|
// ─── Roles ───
|
|
112
136
|
router.get('/roles', async function(req, res) {
|
|
113
137
|
try {
|
|
@@ -145,23 +169,14 @@ function createAdminRouter() {
|
|
|
145
169
|
if (await refuseSystemRole(req, res, roleId)) return;
|
|
146
170
|
|
|
147
171
|
if (assign) {
|
|
148
|
-
|
|
149
|
-
.findOne({ userId: userId, roleId: roleId });
|
|
150
|
-
if (!existing) {
|
|
151
|
-
await UserRolesMapping.query().insert({
|
|
152
|
-
id: generateId(),
|
|
153
|
-
userId: userId,
|
|
154
|
-
roleId: roleId,
|
|
155
|
-
recordCreatedBy: req.user ? req.user.id : null
|
|
156
|
-
});
|
|
157
|
-
}
|
|
172
|
+
await grantRoles(userId, [roleId], { by: req.user ? req.user.id : null });
|
|
158
173
|
} else {
|
|
159
174
|
await UserRolesMapping.query()
|
|
160
175
|
.delete()
|
|
161
176
|
.where({ userId: userId, roleId: roleId });
|
|
177
|
+
await clearUserAccess(userId);
|
|
162
178
|
}
|
|
163
179
|
|
|
164
|
-
await clearUserAccess(userId);
|
|
165
180
|
await hooks.fire('userRolesMapping', assign ? 'create' : 'delete', userId);
|
|
166
181
|
res.json({ ok: true });
|
|
167
182
|
} catch (err) {
|
package/lib/authRouter.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
const express = require('express');
|
|
2
2
|
const FileUploader = require('@xeplr/utils/lib/fileUploader');
|
|
3
|
-
const { register, activate, previewInvite, acceptInvite, login, forgotPassword, resetPassword, requestPhoneOtp, verifyPhoneOtp, getProfile, updateProfile, setProfilePic, changePassword } = require('./authService');
|
|
3
|
+
const { register, resendActivation, activate, previewInvite, acceptInvite, login, forgotPassword, resetPassword, requestPhoneOtp, verifyPhoneOtp, getProfile, updateProfile, setProfilePic, changePassword } = require('./authService');
|
|
4
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 { refusedTenant, SLOT_KEYS } = require('./mtMembershipMiddleware');
|
|
8
9
|
const { accessGate } = require('./accessMiddleware');
|
|
9
10
|
|
|
10
11
|
// Signed in AND allowed this route by the catalog: the same two checks every
|
|
@@ -18,12 +19,42 @@ const User = require('../models/User');
|
|
|
18
19
|
// path on the user; serving it back over HTTP is the consuming app's concern
|
|
19
20
|
// (same as any other uploaded asset), so wire a static route to the same
|
|
20
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
|
+
|
|
21
40
|
const avatarUploader = new FileUploader({ allowedTypes: ['image/*'], maxSize: 2 * 1024 * 1024 });
|
|
22
41
|
|
|
23
42
|
function logError(req, err) {
|
|
24
43
|
if (req.log) req.log.error(err.message, { stack: err.stack });
|
|
25
44
|
}
|
|
26
45
|
|
|
46
|
+
// A refusal the person cannot fix by retrying: the server is missing a
|
|
47
|
+
// setting or cannot send mail. 503 with the reason, so whoever runs the app
|
|
48
|
+
// sees which setting to fix instead of a bare "Something went wrong".
|
|
49
|
+
var SERVER_NOT_READY = ['EMAIL_NOT_SET_UP', 'EMAIL_SEND_FAILED', 'ACTIVATION_URL_NOT_SET', 'RESET_URL_NOT_SET',
|
|
50
|
+
'REGISTER_ROLES_NOT_SET', 'REGISTER_ROLES_UNKNOWN', 'REGISTER_ROLES_SYSTEM'];
|
|
51
|
+
|
|
52
|
+
function sendNotReady(res, err) {
|
|
53
|
+
if (SERVER_NOT_READY.indexOf(err.code) === -1) return false;
|
|
54
|
+
res.status(503).json({ error: err.message, code: err.code });
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
|
|
27
58
|
function createAuthRouter(options = {}) {
|
|
28
59
|
const router = express.Router();
|
|
29
60
|
const resetBaseUrl = options.resetBaseUrl || null;
|
|
@@ -43,6 +74,21 @@ function createAuthRouter(options = {}) {
|
|
|
43
74
|
if (err.message === 'Email already registered') {
|
|
44
75
|
return res.status(409).json({ error: err.message });
|
|
45
76
|
}
|
|
77
|
+
if (sendNotReady(res, err)) return;
|
|
78
|
+
res.status(500).json({ error: 'Something went wrong' });
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// Same answer whether or not the address has an account.
|
|
83
|
+
router.post('/resend-activation', async function(req, res) {
|
|
84
|
+
try {
|
|
85
|
+
var email = req.body && req.body.email;
|
|
86
|
+
if (!email) return res.status(400).json({ error: 'Email is required' });
|
|
87
|
+
await resendActivation({ email: email });
|
|
88
|
+
res.json({ message: 'If that account is waiting for activation, a new link has been sent.' });
|
|
89
|
+
} catch (err) {
|
|
90
|
+
logError(req, err);
|
|
91
|
+
if (sendNotReady(res, err)) return;
|
|
46
92
|
res.status(500).json({ error: 'Something went wrong' });
|
|
47
93
|
}
|
|
48
94
|
});
|
|
@@ -61,6 +107,7 @@ function createAuthRouter(options = {}) {
|
|
|
61
107
|
res.json({ message: 'Account activated successfully', user: result });
|
|
62
108
|
} catch (err) {
|
|
63
109
|
logError(req, err);
|
|
110
|
+
if (sendNotReady(res, err)) return;
|
|
64
111
|
res.status(400).json({ error: err.message });
|
|
65
112
|
}
|
|
66
113
|
});
|
|
@@ -104,7 +151,10 @@ function createAuthRouter(options = {}) {
|
|
|
104
151
|
} catch (err) {
|
|
105
152
|
logError(req, err);
|
|
106
153
|
if (err.message === 'NOT_ACTIVATED') {
|
|
107
|
-
return res.status(403).json({
|
|
154
|
+
return res.status(403).json({
|
|
155
|
+
error: 'Your account is not activated yet. Open the activation link we emailed you.',
|
|
156
|
+
code: 'NOT_ACTIVATED'
|
|
157
|
+
});
|
|
108
158
|
}
|
|
109
159
|
if (err.message === 'Invalid email or password' || err.message === 'Account is deactivated') {
|
|
110
160
|
return res.status(401).json({ error: err.message });
|
|
@@ -121,11 +171,11 @@ function createAuthRouter(options = {}) {
|
|
|
121
171
|
return res.status(400).json({ error: 'Email is required' });
|
|
122
172
|
}
|
|
123
173
|
|
|
124
|
-
|
|
125
|
-
await forgotPassword({ email }, baseUrl);
|
|
174
|
+
await forgotPassword({ email }, resetBaseUrl);
|
|
126
175
|
res.json({ message: 'If that email exists, a reset link has been sent.' });
|
|
127
176
|
} catch (err) {
|
|
128
177
|
logError(req, err);
|
|
178
|
+
if (sendNotReady(res, err)) return;
|
|
129
179
|
res.status(500).json({ error: 'Something went wrong' });
|
|
130
180
|
}
|
|
131
181
|
});
|
|
@@ -228,17 +278,37 @@ function createAuthRouter(options = {}) {
|
|
|
228
278
|
// (the token, with the same tolerance and sliding refresh as any route) AND
|
|
229
279
|
// may they call this API. Both, always; there is no way to ask one without
|
|
230
280
|
// the other. The app names the request it is serving in two headers.
|
|
281
|
+
//
|
|
282
|
+
// AND, when the request names a company or workspace, whether this user
|
|
283
|
+
// belongs to it: x-verify-tenant, { "l1": "<company>", "l2": "<workspace>" }
|
|
284
|
+
// (the levels as memberships are kept, so auth needs no app's header names).
|
|
285
|
+
// Not a member → 403 NOT_A_MEMBER, before the app sees the request. The
|
|
286
|
+
// answer says `tenant: 'checked'`, so a gate can tell this from an older
|
|
287
|
+
// auth that ignored the header. Super Admin belongs to every one.
|
|
231
288
|
router.get('/verify', authMiddleware, async function(req, res) {
|
|
232
289
|
var method = req.headers['x-verify-method'];
|
|
233
290
|
var path = req.headers['x-verify-path'];
|
|
234
291
|
if (!method || !path) {
|
|
235
292
|
return res.status(400).json({ error: 'x-verify-method and x-verify-path are required', code: 'NO_REQUEST' });
|
|
236
293
|
}
|
|
294
|
+
var tenants = null;
|
|
295
|
+
if (req.headers['x-verify-tenant']) {
|
|
296
|
+
tenants = readTenants(req.headers['x-verify-tenant']);
|
|
297
|
+
if (!tenants) return res.status(400).json({ error: 'x-verify-tenant must be { "l1": "<id>", … }', code: 'BAD_TENANT' });
|
|
298
|
+
}
|
|
237
299
|
try {
|
|
300
|
+
if (tenants) {
|
|
301
|
+
var refused = await refusedTenant(req.user, tenants);
|
|
302
|
+
if (refused) {
|
|
303
|
+
return res.status(403).json({ error: 'Not a member of ' + refused.level + ' "' + refused.value + '"', code: 'NOT_A_MEMBER' });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
238
306
|
var answer = await requestApiState(req.user.id, method, path);
|
|
239
307
|
if (answer.state === 'enabled') {
|
|
240
308
|
var access = await getUserAccess(req.user.id);
|
|
241
|
-
|
|
309
|
+
var ok = { user: req.user, access: access, state: 'enabled', api: answer.api };
|
|
310
|
+
if (tenants) ok.tenant = 'checked';
|
|
311
|
+
return res.json(ok);
|
|
242
312
|
}
|
|
243
313
|
if (answer.state === 'unlicensed') {
|
|
244
314
|
return res.status(403).json({ error: 'This is not part of your licence', code: 'UNLICENSED', api: answer.api });
|
package/lib/authService.js
CHANGED
|
@@ -6,6 +6,7 @@ const User = require('../models/User');
|
|
|
6
6
|
const { getUserAccess, clearUserAccess } = require('./accessService');
|
|
7
7
|
const { createSession, destroyAllUserSessions } = require('./sessionService');
|
|
8
8
|
const hooks = require('./hooks');
|
|
9
|
+
const { grantRoles, registerRoleIds, refusal } = require('./userRoles');
|
|
9
10
|
|
|
10
11
|
// WHERE THE LINKS IN OUR EMAILS POINT.
|
|
11
12
|
//
|
|
@@ -19,9 +20,39 @@ const hooks = require('./hooks');
|
|
|
19
20
|
// path for each link is appended, exactly as before. It served both the
|
|
20
21
|
// activation and the invite page, which is precisely why one fully-qualified
|
|
21
22
|
// value could not replace it.
|
|
22
|
-
var _links = { activationUrl: null, inviteUrl: null, baseUrl: null };
|
|
23
|
+
var _links = { activationUrl: null, inviteUrl: null, resetUrl: null, baseUrl: null };
|
|
23
24
|
|
|
24
|
-
var DEFAULT_PATHS = { activation: '/auth/activate', invite: '/auth/accept-invite' };
|
|
25
|
+
var DEFAULT_PATHS = { activation: '/auth/activate', invite: '/auth/accept-invite', reset: '/auth/reset-password' };
|
|
26
|
+
|
|
27
|
+
var LINK_VARS = { activation: 'AUTH_ACTIVATION_URL', invite: 'AUTH_INVITE_URL', reset: 'AUTH_RESET_URL' };
|
|
28
|
+
|
|
29
|
+
// CAN MAIL GO OUT? Set by boot() from its startup check: true, false, or null
|
|
30
|
+
// when nobody checked (an app that calls init()/start() itself). Known-false
|
|
31
|
+
// refuses registration before an account exists; null lets it try, and a
|
|
32
|
+
// failed send rolls the account back — either way no account is left behind
|
|
33
|
+
// that was never sent its link.
|
|
34
|
+
var _emailReady = null;
|
|
35
|
+
|
|
36
|
+
function configureEmailStatus(ready) {
|
|
37
|
+
_emailReady = ready === true || ready === false ? ready : null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function requireEmail(what) {
|
|
41
|
+
if (_emailReady === false) {
|
|
42
|
+
throw refusal('EMAIL_NOT_SET_UP', 'Email is not set up on this server, so ' + what +
|
|
43
|
+
' cannot be sent. Set EMAIL_PROVIDER and its settings.');
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function sendOrRefuse(to, subject, html, what) {
|
|
48
|
+
try {
|
|
49
|
+
await sendEmail(to, subject, html);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
var wrapped = refusal('EMAIL_SEND_FAILED', 'Could not send ' + what + ': ' + err.message);
|
|
52
|
+
wrapped.cause = err;
|
|
53
|
+
throw wrapped;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
25
56
|
|
|
26
57
|
// RESUMING A WORKFLOW ON ACTIVATION.
|
|
27
58
|
//
|
|
@@ -71,13 +102,12 @@ function configureActivation(config) {
|
|
|
71
102
|
if (!config) return;
|
|
72
103
|
if (config.activationUrl !== undefined) _links.activationUrl = config.activationUrl;
|
|
73
104
|
if (config.inviteUrl !== undefined) _links.inviteUrl = config.inviteUrl;
|
|
105
|
+
if (config.resetUrl !== undefined) _links.resetUrl = config.resetUrl;
|
|
74
106
|
if (config.baseUrl !== undefined) _links.baseUrl = config.baseUrl;
|
|
75
107
|
}
|
|
76
108
|
|
|
77
109
|
function linkFor(kind) {
|
|
78
|
-
var explicit = kind
|
|
79
|
-
? (_links.activationUrl || process.env.AUTH_ACTIVATION_URL)
|
|
80
|
-
: (_links.inviteUrl || process.env.AUTH_INVITE_URL);
|
|
110
|
+
var explicit = _links[kind + 'Url'] || process.env[LINK_VARS[kind]];
|
|
81
111
|
if (explicit) return explicit;
|
|
82
112
|
|
|
83
113
|
var base = _links.baseUrl || process.env.AUTH_ACTIVATION_BASE_URL;
|
|
@@ -92,7 +122,39 @@ function withToken(url, token) {
|
|
|
92
122
|
return url + (url.indexOf('?') === -1 ? '?' : '&') + 'token=' + token;
|
|
93
123
|
}
|
|
94
124
|
|
|
125
|
+
function activationEmail(name, link) {
|
|
126
|
+
return '<h2>Activate your account</h2>'
|
|
127
|
+
+ '<p>Hi ' + (name || 'there') + ',</p>'
|
|
128
|
+
+ '<p>Click below to activate your account:</p>'
|
|
129
|
+
+ '<p><a href="' + link + '">' + link + '</a></p>';
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// The key rides along in the link so it comes back to us when the user
|
|
133
|
+
// clicks — there is nowhere else to keep it: activation happens in a
|
|
134
|
+
// different browser, days later, with no session.
|
|
135
|
+
function activationLinkFor(activationUrl, token, workflowKey) {
|
|
136
|
+
var link = withToken(activationUrl, token);
|
|
137
|
+
if (workflowKey) link += '&workflowKey=' + encodeURIComponent(workflowKey);
|
|
138
|
+
return link;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function requireActivationUrl() {
|
|
142
|
+
var activationUrl = linkFor('activation');
|
|
143
|
+
if (!activationUrl) {
|
|
144
|
+
throw refusal('ACTIVATION_URL_NOT_SET', 'AUTH_ACTIVATION_URL is required (the full address of your activation page, ' +
|
|
145
|
+
'e.g. http://localhost:19100/auth/activate). Cannot register without email activation.');
|
|
146
|
+
}
|
|
147
|
+
return activationUrl;
|
|
148
|
+
}
|
|
149
|
+
|
|
95
150
|
async function register({ email, phoneNumber, name, password, workflowKey, knex }) {
|
|
151
|
+
// EVERYTHING THAT CAN REFUSE, BEFORE THE ACCOUNT EXISTS. An account created
|
|
152
|
+
// and then refused is stuck: its address is taken (a retry says "already
|
|
153
|
+
// registered") and it can never be activated, because the link never went.
|
|
154
|
+
var activationUrl = requireActivationUrl();
|
|
155
|
+
requireEmail('the activation link');
|
|
156
|
+
await registerRoleIds(knex); // the roles it gets on activation must exist now
|
|
157
|
+
|
|
96
158
|
const UserM = knex ? User.bindKnex(knex) : User;
|
|
97
159
|
const normalized = normalizeEmail(email);
|
|
98
160
|
|
|
@@ -106,44 +168,32 @@ async function register({ email, phoneNumber, name, password, workflowKey, knex
|
|
|
106
168
|
const now = formatDbDateTime();
|
|
107
169
|
const activationToken = crypto.randomBytes(32).toString('hex');
|
|
108
170
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
171
|
+
// The send is inside the transaction: if the mail cannot go out, the
|
|
172
|
+
// account is rolled back and the person can simply try again.
|
|
173
|
+
var user = await (knex || User.knex()).transaction(async function(trx) {
|
|
174
|
+
var created = await User.bindKnex(trx).query().insert({
|
|
175
|
+
id,
|
|
176
|
+
email: email.trim().toLowerCase(),
|
|
177
|
+
normalizedEmail: normalized,
|
|
178
|
+
phoneNumber: phoneNumber || null,
|
|
179
|
+
name: name || null,
|
|
180
|
+
pwd: hash,
|
|
181
|
+
pwdSalt: salt,
|
|
182
|
+
isActive: true,
|
|
183
|
+
isActivated: false,
|
|
184
|
+
activationToken,
|
|
185
|
+
activatedOn: null,
|
|
186
|
+
activatedBy: null,
|
|
187
|
+
recordCreatedDate: now,
|
|
188
|
+
recordModifiedDate: now,
|
|
189
|
+
recordCreatedBy: id,
|
|
190
|
+
recordModifiedBy: id
|
|
191
|
+
});
|
|
192
|
+
var link = activationLinkFor(activationUrl, activationToken, workflowKey);
|
|
193
|
+
await sendOrRefuse(email, 'Activate your account', activationEmail(name, link), 'the activation link');
|
|
194
|
+
return created;
|
|
126
195
|
});
|
|
127
196
|
|
|
128
|
-
// Send activation email
|
|
129
|
-
const activationUrl = linkFor('activation');
|
|
130
|
-
if (!activationUrl) {
|
|
131
|
-
throw new Error('AUTH_ACTIVATION_URL is required (the full address of your activation page, ' +
|
|
132
|
-
'e.g. http://localhost:19100/auth/activate). Cannot register without email activation.');
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// The key rides along in the link so it comes back to us when the user
|
|
136
|
-
// clicks — there is nowhere else to keep it: activation happens in a
|
|
137
|
-
// different browser, days later, with no session.
|
|
138
|
-
var activationLink = withToken(activationUrl, activationToken);
|
|
139
|
-
if (workflowKey) activationLink += '&workflowKey=' + encodeURIComponent(workflowKey);
|
|
140
|
-
const html = '<h2>Activate your account</h2>'
|
|
141
|
-
+ '<p>Hi ' + (name || 'there') + ',</p>'
|
|
142
|
-
+ '<p>Click below to activate your account:</p>'
|
|
143
|
-
+ '<p><a href="' + activationLink + '">' + activationLink + '</a></p>';
|
|
144
|
-
|
|
145
|
-
await sendEmail(email, 'Activate your account', html);
|
|
146
|
-
|
|
147
197
|
await hooks.fire('user', 'create', user.id);
|
|
148
198
|
|
|
149
199
|
return {
|
|
@@ -156,6 +206,48 @@ async function register({ email, phoneNumber, name, password, workflowKey, knex
|
|
|
156
206
|
};
|
|
157
207
|
}
|
|
158
208
|
|
|
209
|
+
/**
|
|
210
|
+
* Send a fresh activation link to an account that has not been activated.
|
|
211
|
+
* Answers the same way whether or not the address has an account, so it
|
|
212
|
+
* cannot be used to find out who is registered.
|
|
213
|
+
*/
|
|
214
|
+
async function resendActivation({ email }) {
|
|
215
|
+
var activationUrl = requireActivationUrl();
|
|
216
|
+
requireEmail('the activation link');
|
|
217
|
+
|
|
218
|
+
var user = await User.query().findOne({ normalizedEmail: normalizeEmail(email) });
|
|
219
|
+
// Invited accounts (no password yet) activate through their invite link.
|
|
220
|
+
if (!user || user.isActivated || !user.pwd) return;
|
|
221
|
+
|
|
222
|
+
var activationToken = crypto.randomBytes(32).toString('hex');
|
|
223
|
+
await User.query().findById(user.id).patch({
|
|
224
|
+
activationToken: activationToken,
|
|
225
|
+
recordModifiedDate: formatDbDateTime()
|
|
226
|
+
});
|
|
227
|
+
await sendOrRefuse(user.email, 'Activate your account',
|
|
228
|
+
activationEmail(user.name, activationLinkFor(activationUrl, activationToken)), 'the activation link');
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Mark the account activated and give it the app's sign-up roles, together.
|
|
233
|
+
* Both activation paths — the emailed link and an admin — come through here,
|
|
234
|
+
* so an activated account always has the roles it needs to use the app.
|
|
235
|
+
*/
|
|
236
|
+
async function markActivated(user, activatedBy) {
|
|
237
|
+
var roleIds = await registerRoleIds();
|
|
238
|
+
var now = formatDbDateTime();
|
|
239
|
+
await User.knex().transaction(async function(trx) {
|
|
240
|
+
await User.bindKnex(trx).query().findById(user.id).patch({
|
|
241
|
+
isActivated: true,
|
|
242
|
+
activatedOn: now,
|
|
243
|
+
activatedBy: activatedBy || null,
|
|
244
|
+
activationToken: null,
|
|
245
|
+
recordModifiedDate: now
|
|
246
|
+
});
|
|
247
|
+
await grantRoles(user.id, roleIds, { by: activatedBy || user.id, knex: trx });
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
159
251
|
async function activate(token, options) {
|
|
160
252
|
var workflowKey = options && options.workflowKey;
|
|
161
253
|
var log = require('@xeplr/logs').createLogger('auth');
|
|
@@ -168,7 +260,7 @@ async function activate(token, options) {
|
|
|
168
260
|
|
|
169
261
|
const user = await User.query().findOne({ activationToken: token });
|
|
170
262
|
if (!user) {
|
|
171
|
-
log.
|
|
263
|
+
log.important('activation: no user holds that token — expired, already used, or wrong link');
|
|
172
264
|
throw new Error('Invalid activation token');
|
|
173
265
|
}
|
|
174
266
|
|
|
@@ -177,15 +269,17 @@ async function activate(token, options) {
|
|
|
177
269
|
throw new Error('Account already activated');
|
|
178
270
|
}
|
|
179
271
|
|
|
272
|
+
// An INVITE token opened as an activation link. Activating here would leave
|
|
273
|
+
// an account with no password that nobody can sign in to, and use up the
|
|
274
|
+
// token the invite page needs.
|
|
275
|
+
if (!user.pwd) {
|
|
276
|
+
log.important('activation: ' + user.email + ' was invited and has no password — refused');
|
|
277
|
+
throw new Error('This link is an invitation. Open it from the invite email to set your password.');
|
|
278
|
+
}
|
|
279
|
+
|
|
180
280
|
log.info('activation: activating ' + user.email);
|
|
181
281
|
|
|
182
|
-
|
|
183
|
-
await User.query().findById(user.id).patch({
|
|
184
|
-
isActivated: true,
|
|
185
|
-
activatedOn: now,
|
|
186
|
-
activationToken: null,
|
|
187
|
-
recordModifiedDate: now
|
|
188
|
-
});
|
|
282
|
+
await markActivated(user, null);
|
|
189
283
|
|
|
190
284
|
log.important('activation: ' + user.email + ' activated');
|
|
191
285
|
await hooks.fire('user', 'update', user.id);
|
|
@@ -207,6 +301,23 @@ async function activate(token, options) {
|
|
|
207
301
|
return { id: user.id, email: user.email, name: user.name };
|
|
208
302
|
}
|
|
209
303
|
|
|
304
|
+
/**
|
|
305
|
+
* An admin activates an account without its emailed link — for someone whose
|
|
306
|
+
* mail never arrived, or an app that approves sign-ups by hand.
|
|
307
|
+
*/
|
|
308
|
+
async function adminActivate(userId, adminId) {
|
|
309
|
+
var user = await User.query().findById(userId);
|
|
310
|
+
if (!user) throw refusal('USER_NOT_FOUND', 'User not found');
|
|
311
|
+
if (user.isActivated) throw refusal('ALREADY_ACTIVATED', 'This account is already activated');
|
|
312
|
+
if (!user.pwd) {
|
|
313
|
+
throw refusal('INVITE_PENDING', 'This person was invited and has not set a password yet. ' +
|
|
314
|
+
'They activate by accepting the invite.');
|
|
315
|
+
}
|
|
316
|
+
await markActivated(user, adminId);
|
|
317
|
+
await hooks.fire('user', 'update', user.id);
|
|
318
|
+
return { id: user.id, email: user.email, name: user.name, isActivated: true };
|
|
319
|
+
}
|
|
320
|
+
|
|
210
321
|
async function login({ email, password }) {
|
|
211
322
|
const normalized = normalizeEmail(email);
|
|
212
323
|
const user = await User.query()
|
|
@@ -220,6 +331,11 @@ async function login({ email, password }) {
|
|
|
220
331
|
throw new Error('Account is deactivated');
|
|
221
332
|
}
|
|
222
333
|
|
|
334
|
+
// An invited account has no password until the invite is accepted.
|
|
335
|
+
if (!user.pwd) {
|
|
336
|
+
throw new Error('Invalid email or password');
|
|
337
|
+
}
|
|
338
|
+
|
|
223
339
|
const isMatch = await comparePassword(password, user.pwd);
|
|
224
340
|
if (!isMatch) {
|
|
225
341
|
throw new Error('Invalid email or password');
|
|
@@ -377,7 +493,26 @@ async function acceptInvite({ token, name, password, knex }) {
|
|
|
377
493
|
return { id: user.id, email: user.email, name: name || user.name };
|
|
378
494
|
}
|
|
379
495
|
|
|
496
|
+
// WHERE THE RESET LINK POINTS — the app's own setting, never the request's
|
|
497
|
+
// Host header: anyone can send a forgot-password request with Host set to
|
|
498
|
+
// their own site and have us mail the real user a link to it, token included.
|
|
499
|
+
// resetBaseUrl (an origin) is the older way for a host app to say the same.
|
|
500
|
+
function resetUrlFor(resetBaseUrl) {
|
|
501
|
+
if (resetBaseUrl) return String(resetBaseUrl).replace(/\/+$/, '') + DEFAULT_PATHS.reset;
|
|
502
|
+
var url = linkFor('reset');
|
|
503
|
+
if (!url) {
|
|
504
|
+
throw refusal('RESET_URL_NOT_SET', 'AUTH_RESET_URL is required (the full address of your reset-password ' +
|
|
505
|
+
'page, e.g. http://localhost:19100/auth/reset-password). Password reset links cannot be sent without it.');
|
|
506
|
+
}
|
|
507
|
+
return url;
|
|
508
|
+
}
|
|
509
|
+
|
|
380
510
|
async function forgotPassword({ email }, resetBaseUrl) {
|
|
511
|
+
// Refused for every address alike, before the lookup, so the answer says
|
|
512
|
+
// nothing about whether this one has an account.
|
|
513
|
+
var resetUrl = resetUrlFor(resetBaseUrl);
|
|
514
|
+
requireEmail('the password reset link');
|
|
515
|
+
|
|
381
516
|
const normalized = normalizeEmail(email);
|
|
382
517
|
const user = await User.query().findOne({ normalizedEmail: normalized });
|
|
383
518
|
if (!user) {
|
|
@@ -394,7 +529,7 @@ async function forgotPassword({ email }, resetBaseUrl) {
|
|
|
394
529
|
recordModifiedDate: formatDbDateTime()
|
|
395
530
|
});
|
|
396
531
|
|
|
397
|
-
const resetLink =
|
|
532
|
+
const resetLink = withToken(resetUrl, resetToken);
|
|
398
533
|
|
|
399
534
|
const html = `
|
|
400
535
|
<h2>Password Reset</h2>
|
|
@@ -405,22 +540,26 @@ async function forgotPassword({ email }, resetBaseUrl) {
|
|
|
405
540
|
<p>If you didn't request this, ignore this email.</p>
|
|
406
541
|
`;
|
|
407
542
|
|
|
408
|
-
await
|
|
543
|
+
await sendOrRefuse(user.email, 'Password Reset', html, 'the password reset link');
|
|
409
544
|
|
|
410
545
|
await hooks.fire('user', 'update', user.id);
|
|
411
546
|
}
|
|
412
547
|
|
|
413
548
|
async function resetPassword({ token, newPassword }) {
|
|
414
|
-
|
|
549
|
+
// EXPIRY IS CHECKED IN THE QUERY, against a value written the same way.
|
|
550
|
+
// forgotPassword stores formatDbDateTime() — UTC — in a column with no time
|
|
551
|
+
// zone. Read back, the driver takes that as LOCAL time, so a comparison in
|
|
552
|
+
// JavaScript is off by the server's UTC offset: east of UTC every fresh link
|
|
553
|
+
// looked expired, and the older `Date < string` check let expired ones
|
|
554
|
+
// through. Postgres compares the two UTC values as written.
|
|
555
|
+
const user = await User.query()
|
|
556
|
+
.findOne({ resetToken: token })
|
|
557
|
+
.where('resetTokenExpiry', '>', formatDbDateTime());
|
|
415
558
|
|
|
416
559
|
if (!user) {
|
|
417
560
|
throw new Error('Invalid or expired reset token');
|
|
418
561
|
}
|
|
419
562
|
|
|
420
|
-
if (user.resetTokenExpiry < formatDbDateTime()) {
|
|
421
|
-
throw new Error('Invalid or expired reset token');
|
|
422
|
-
}
|
|
423
|
-
|
|
424
563
|
const { hash, salt } = await hashPassword(newPassword);
|
|
425
564
|
|
|
426
565
|
await User.query().findById(user.id).patch({
|
|
@@ -609,8 +748,12 @@ module.exports = {
|
|
|
609
748
|
configureActivation,
|
|
610
749
|
configureWorkflowResume,
|
|
611
750
|
configureEmail,
|
|
751
|
+
configureEmailStatus,
|
|
752
|
+
linkFor,
|
|
612
753
|
register,
|
|
754
|
+
resendActivation,
|
|
613
755
|
activate,
|
|
756
|
+
adminActivate,
|
|
614
757
|
invite,
|
|
615
758
|
previewInvite,
|
|
616
759
|
acceptInvite,
|
|
@@ -28,6 +28,32 @@ var SLOT_KEYS = ['l1', 'l2', 'l3', 'l4'];
|
|
|
28
28
|
* app.use(mtMiddleware()); // @xeplr/db — sets mtId context
|
|
29
29
|
* app.use(mtMembershipMiddleware()); // this — rejects forged values
|
|
30
30
|
*/
|
|
31
|
+
/**
|
|
32
|
+
* THE ONE MEMBERSHIP CHECK — this middleware's, and GET /verify's (which
|
|
33
|
+
* every app's gate asks on every request, @xeplr/base-apis remoteAuth).
|
|
34
|
+
*
|
|
35
|
+
* @param user the signed-in user ({ id, roles })
|
|
36
|
+
* @param tenants { l1: 'c1', l2: 'w1' } — a level absent or empty is not asked
|
|
37
|
+
* @param Model a bound UserTenantsMapping (default: this package's)
|
|
38
|
+
* @returns null when the user may use every value; else { level, value }, the
|
|
39
|
+
* first one refused. Super Admin may use any: running the whole
|
|
40
|
+
* install is the role. Everyone else needs a membership row per value.
|
|
41
|
+
*/
|
|
42
|
+
async function refusedTenant(user, tenants, Model) {
|
|
43
|
+
Model = Model || UserTenantsMapping;
|
|
44
|
+
if (isSuperAdmin(user)) return null;
|
|
45
|
+
for (var i = 0; i < SLOT_KEYS.length; i++) {
|
|
46
|
+
var key = SLOT_KEYS[i];
|
|
47
|
+
var value = tenants && tenants[key];
|
|
48
|
+
if (value === undefined || value === null || value === '') continue;
|
|
49
|
+
var grant = await Model.query()
|
|
50
|
+
.where({ userId: user.id, level: key, value: String(value), isActive: true })
|
|
51
|
+
.first();
|
|
52
|
+
if (!grant) return { level: key, value: String(value) };
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
|
|
31
57
|
function mtMembershipMiddleware(options) {
|
|
32
58
|
options = options || {};
|
|
33
59
|
var Model = options.userTenantsMapping || UserTenantsMapping;
|
|
@@ -36,27 +62,16 @@ function mtMembershipMiddleware(options) {
|
|
|
36
62
|
try {
|
|
37
63
|
var mtConfig = getMtConfig();
|
|
38
64
|
if (!mtConfig.enabled || !req.user || !req.user.id) return next();
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
if (isSuperAdmin(req.user)) return next();
|
|
42
|
-
|
|
43
|
-
for (var i = 0; i < SLOT_KEYS.length; i++) {
|
|
44
|
-
var key = SLOT_KEYS[i];
|
|
65
|
+
var tenants = {};
|
|
66
|
+
SLOT_KEYS.forEach(function(key) {
|
|
45
67
|
var slot = mtConfig.slots[key];
|
|
46
|
-
if (
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
.where({ userId: req.user.id, level: key, value: value, isActive: true })
|
|
53
|
-
.first();
|
|
54
|
-
|
|
55
|
-
if (!grant) {
|
|
56
|
-
return res.status(403).json({ error: 'Not authorized for ' + (slot.name || key) + ' "' + value + '"' });
|
|
57
|
-
}
|
|
68
|
+
if (slot) tenants[key] = req.headers[slot.header];
|
|
69
|
+
});
|
|
70
|
+
var refused = await refusedTenant(req.user, tenants, Model);
|
|
71
|
+
if (refused) {
|
|
72
|
+
var slot = mtConfig.slots[refused.level];
|
|
73
|
+
return res.status(403).json({ error: 'Not authorized for ' + ((slot && slot.name) || refused.level) + ' "' + refused.value + '"' });
|
|
58
74
|
}
|
|
59
|
-
|
|
60
75
|
next();
|
|
61
76
|
} catch (err) {
|
|
62
77
|
if (req.log) req.log.error(err.message, { stack: err.stack });
|
|
@@ -66,3 +81,5 @@ function mtMembershipMiddleware(options) {
|
|
|
66
81
|
}
|
|
67
82
|
|
|
68
83
|
module.exports = mtMembershipMiddleware;
|
|
84
|
+
module.exports.refusedTenant = refusedTenant;
|
|
85
|
+
module.exports.SLOT_KEYS = SLOT_KEYS;
|
package/lib/userRoles.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
var { generateId } = require('./authHelper');
|
|
2
|
+
var Role = require('../models/Role');
|
|
3
|
+
var UserRolesMapping = require('../models/UserRolesMapping');
|
|
4
|
+
var { clearUserAccess } = require('./accessService');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Give a user roles. Skips any they already hold, then drops their cached
|
|
8
|
+
* access so the next request sees the new roles. The one insert behind both
|
|
9
|
+
* the admin's role toggle and the roles a new account gets on activation.
|
|
10
|
+
*
|
|
11
|
+
* @param {string} userId
|
|
12
|
+
* @param {string[]} roleIds
|
|
13
|
+
* @param {object} [options] - { by: userId doing it, knex: transaction }
|
|
14
|
+
*/
|
|
15
|
+
async function grantRoles(userId, roleIds, options) {
|
|
16
|
+
var by = options && options.by;
|
|
17
|
+
var knex = options && options.knex;
|
|
18
|
+
var Mapping = knex ? UserRolesMapping.bindKnex(knex) : UserRolesMapping;
|
|
19
|
+
for (var i = 0; i < roleIds.length; i++) {
|
|
20
|
+
var existing = await Mapping.query().findOne({ userId: userId, roleId: roleIds[i] });
|
|
21
|
+
if (existing) continue;
|
|
22
|
+
await Mapping.query().insert({
|
|
23
|
+
id: generateId(),
|
|
24
|
+
userId: userId,
|
|
25
|
+
roleId: roleIds[i],
|
|
26
|
+
recordCreatedBy: by || null
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
await clearUserAccess(userId);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// THE ROLES A SELF-REGISTERED ACCOUNT GETS — named by each app, never assumed.
|
|
33
|
+
//
|
|
34
|
+
// Without a role every API mapped to roles is hidden from the person, their
|
|
35
|
+
// own profile included, so an account with none can sign in and do nothing.
|
|
36
|
+
// Which role fits is the app's call (BI: Viewer), so there is no default:
|
|
37
|
+
// registration refuses until AUTH_REGISTER_ROLES names one, rather than
|
|
38
|
+
// quietly creating accounts that cannot use the app.
|
|
39
|
+
//
|
|
40
|
+
// Read at call time, like AUTH_ACTIVATION_URL, so the .env the app has
|
|
41
|
+
// loaded is the one used. System roles (Super Admin) are refused: a sign-up
|
|
42
|
+
// form must never be a way to become one.
|
|
43
|
+
var REGISTER_ROLES_VAR = 'AUTH_REGISTER_ROLES';
|
|
44
|
+
|
|
45
|
+
function refusal(code, message) {
|
|
46
|
+
var err = new Error(message);
|
|
47
|
+
err.code = code;
|
|
48
|
+
return err;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function registerRoleIds(knex) {
|
|
52
|
+
var raw = process.env[REGISTER_ROLES_VAR];
|
|
53
|
+
var names = String(raw || '').split(',')
|
|
54
|
+
.map(function(n) { return n.trim(); })
|
|
55
|
+
.filter(Boolean);
|
|
56
|
+
if (!names.length) {
|
|
57
|
+
throw refusal('REGISTER_ROLES_NOT_SET', REGISTER_ROLES_VAR + ' is not set: name the role(s) a new ' +
|
|
58
|
+
'account gets, comma-separated (for example Viewer). Registration is refused until it is.');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
var RoleM = knex ? Role.bindKnex(knex) : Role;
|
|
62
|
+
var roles = await RoleM.query().select('id', 'name', 'scope').where('mtId1', '*').whereIn('name', names);
|
|
63
|
+
var missing = names.filter(function(n) { return !roles.some(function(r) { return r.name === n; }); });
|
|
64
|
+
if (missing.length) {
|
|
65
|
+
throw refusal('REGISTER_ROLES_UNKNOWN', REGISTER_ROLES_VAR + ' names ' +
|
|
66
|
+
(missing.length > 1 ? 'roles that do' : 'a role that does') + ' not exist: ' + missing.join(', ') + '.');
|
|
67
|
+
}
|
|
68
|
+
var system = roles.filter(function(r) { return r.scope === 'system'; });
|
|
69
|
+
if (system.length) {
|
|
70
|
+
throw refusal('REGISTER_ROLES_SYSTEM', REGISTER_ROLES_VAR + ' names a system role (' +
|
|
71
|
+
system.map(function(r) { return r.name; }).join(', ') + '); new accounts can never be given one.');
|
|
72
|
+
}
|
|
73
|
+
return roles.map(function(r) { return r.id; });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
module.exports = { grantRoles, registerRoleIds, refusal, REGISTER_ROLES_VAR };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
-- 0014_activation_routes.sql
|
|
2
|
+
-- Routes added for the sign-up flow, plus three that shipped without a row.
|
|
3
|
+
--
|
|
4
|
+
-- POST /auth/api/resend-activation public: a new activation link
|
|
5
|
+
-- POST /auth/api/admin/users/:id/activate users:edit: activate by hand
|
|
6
|
+
-- /auth/api/invite-preview, invite-accept public: the accept-invite page
|
|
7
|
+
-- /auth/api/sse-ticket account:view: any signed-in role
|
|
8
|
+
--
|
|
9
|
+
-- invite-preview, invite-accept and sse-ticket existed with no row, and an
|
|
10
|
+
-- unregistered API is open to everyone — sse-ticket is meant for signed-in
|
|
11
|
+
-- users only.
|
|
12
|
+
--
|
|
13
|
+
-- Mapped the same way as 0012: users:* to Super Admin and Admin, account:* to
|
|
14
|
+
-- every base role. An app's own roles (CompanyAdmin, Creator) are mapped in
|
|
15
|
+
-- the app's migrations-auth/.
|
|
16
|
+
|
|
17
|
+
INSERT INTO "apis" (id, name, "apiGroup", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
|
|
18
|
+
SELECT encode(gen_random_bytes(12), 'hex'), v.name, v.grp, v.pub, true, '*', now(), now()
|
|
19
|
+
FROM (VALUES
|
|
20
|
+
('POST /auth/api/resend-activation', '', true),
|
|
21
|
+
('POST /auth/api/admin/users/:id/activate', 'users:edit', false),
|
|
22
|
+
('GET /auth/api/invite-preview', '', true),
|
|
23
|
+
('POST /auth/api/invite-accept', '', true),
|
|
24
|
+
('POST /auth/api/sse-ticket', 'account:view', false)
|
|
25
|
+
) AS v(name, grp, pub)
|
|
26
|
+
WHERE NOT EXISTS (SELECT 1 FROM "apis" a WHERE a.name = v.name AND a."apiGroup" = v.grp);
|
|
27
|
+
|
|
28
|
+
INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
|
|
29
|
+
SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
|
|
30
|
+
FROM "roles" r CROSS JOIN "apis" a
|
|
31
|
+
WHERE r.name IN ('Super Admin', 'Admin')
|
|
32
|
+
AND a.name = 'POST /auth/api/admin/users/:id/activate' AND a."apiGroup" = 'users:edit'
|
|
33
|
+
AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
|
|
34
|
+
|
|
35
|
+
INSERT INTO "apisRolesMapping" (id, "roleId", "apiId", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
|
|
36
|
+
SELECT encode(gen_random_bytes(12), 'hex'), r.id, a.id, true, '*', now(), now()
|
|
37
|
+
FROM "roles" r CROSS JOIN "apis" a
|
|
38
|
+
WHERE r.name IN ('Super Admin', 'Admin', 'Editor', 'Viewer')
|
|
39
|
+
AND a.name = 'POST /auth/api/sse-ticket' AND a."apiGroup" = 'account:view'
|
|
40
|
+
AND NOT EXISTS (SELECT 1 FROM "apisRolesMapping" m WHERE m."roleId" = r.id AND m."apiId" = a.id);
|
|
41
|
+
|
|
42
|
+
-- The two public pages that go with them (the UI's /auth/resend-activation
|
|
43
|
+
-- and /auth/accept-invite), next to Login, Register and the rest from 0006.
|
|
44
|
+
INSERT INTO "uiPages" (id, name, "uiPagesGroup", "isPublic", "isActive", "mtId1", "recordCreatedDate", "recordModifiedDate")
|
|
45
|
+
SELECT encode(gen_random_bytes(12), 'hex'), v.name, '', true, true, '*', now(), now()
|
|
46
|
+
FROM (VALUES ('Resend Activation'), ('Accept Invite')) AS v(name)
|
|
47
|
+
WHERE NOT EXISTS (SELECT 1 FROM "uiPages" p WHERE p.name = v.name AND p."uiPagesGroup" = '');
|