@xeplr/auth 1.5.0 → 1.5.2
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 +5 -4
- package/lib/authService.js +58 -18
- package/lib/userRoles.js +7 -3
- 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
|
|
@@ -116,7 +116,7 @@ Everything in `requiredEnv`, plus a connection. `requiredEnv` includes the sign-
|
|
|
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
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
|
|
119
|
+
| `AUTH_REGISTER_ROLES` | — (refused) | the role(s) a self-registered account gets when it is activated, comma-separated, e.g. `Viewer` — **any case** (`viewer` is Viewer; two roles differing only in case cannot be created). **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
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
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 |
|
|
122
122
|
|
|
@@ -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,13 +301,13 @@ 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
|
+
| `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) |
|
|
310
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` |
|
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
|
|
package/lib/userRoles.js
CHANGED
|
@@ -38,7 +38,7 @@ async function grantRoles(userId, roleIds, options) {
|
|
|
38
38
|
// quietly creating accounts that cannot use the app.
|
|
39
39
|
//
|
|
40
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
|
|
41
|
+
// loaded is the one used. Names match in any case (viewer = Viewer). System roles (Super Admin) are refused: a sign-up
|
|
42
42
|
// form must never be a way to become one.
|
|
43
43
|
var REGISTER_ROLES_VAR = 'AUTH_REGISTER_ROLES';
|
|
44
44
|
|
|
@@ -58,9 +58,13 @@ async function registerRoleIds(knex) {
|
|
|
58
58
|
'account gets, comma-separated (for example Viewer). Registration is refused until it is.');
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
// Any case: "viewer" is the Viewer role. Two roles that differ only in case
|
|
62
|
+
// cannot exist — creating or renaming one is refused (adminRouter nameTaken).
|
|
61
63
|
var RoleM = knex ? Role.bindKnex(knex) : Role;
|
|
62
|
-
var
|
|
63
|
-
var
|
|
64
|
+
var lower = names.map(function(n) { return n.toLowerCase(); });
|
|
65
|
+
var roles = await RoleM.query().select('id', 'name', 'scope').where('mtId1', '*')
|
|
66
|
+
.whereRaw('lower(name) in (' + lower.map(function() { return '?'; }).join(', ') + ')', lower);
|
|
67
|
+
var missing = names.filter(function(n) { return !roles.some(function(r) { return r.name.toLowerCase() === n.toLowerCase(); }); });
|
|
64
68
|
if (missing.length) {
|
|
65
69
|
throw refusal('REGISTER_ROLES_UNKNOWN', REGISTER_ROLES_VAR + ' names ' +
|
|
66
70
|
(missing.length > 1 ? 'roles that do' : 'a role that does') + ' not exist: ' + missing.join(', ') + '.');
|