@jskit-ai/users-core 0.2.14 → 0.2.16
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/CHANGELOG.md +22 -0
- package/package.json +24 -17
- package/patterns/user-administration-server/PATTERN.md +59 -10
- package/patterns/user-administration-server/example/packages/users/package.json +5 -4
- package/patterns/user-administration-server/example/packages/users/src/server/UsersFeature.js +7 -5
- package/patterns/user-administration-server/example/packages/users/src/shared/index.js +1 -1
- package/patterns/user-administration-server/example/packages/users/src/shared/userCrud.js +21 -0
- package/patterns/user-administration-server/example/packages/users-workspace/package.json +11 -5
- package/patterns/user-administration-server/example/packages/users-workspace/src/server/UsersWorkspaceFeature.js +14 -5
- package/patterns/user-administration-server/example/packages/users-workspace/src/server/workspaceMembersOnly.js +52 -0
- package/patterns/user-administration-server/example/packages/users-workspace/src/shared/index.js +1 -1
- package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userCrud.js +21 -0
- package/src/server/UsersFeature.js +10 -6
- package/src/server/UsersIdentityProvider.js +13 -29
- package/src/server/accountNotifications/accountNotificationsActions.js +3 -3
- package/src/server/accountNotifications/accountNotificationsRoutes.js +3 -3
- package/src/server/accountPreferences/accountPreferencesActions.js +3 -3
- package/src/server/accountPreferences/accountPreferencesRoutes.js +3 -3
- package/src/server/accountProfile/accountProfileActions.js +9 -9
- package/src/server/accountProfile/accountProfileRoutes.js +5 -5
- package/src/server/accountSecurity/accountSecurityActions.js +10 -10
- package/src/server/accountSecurity/accountSecurityRoutes.js +9 -9
- package/src/server/common/repositories/userProfilesRepository.js +246 -145
- package/src/server/common/repositories/userSettingsRepository.js +20 -49
- package/src/server/common/services/authProfileSyncService.js +3 -5
- package/src/server/types.js +9 -1
- package/src/server/usersIdentity.js +11 -11
- package/src/server/usersRuntime.js +13 -11
- package/src/shared/resources/userProfileResource.js +43 -13
- package/src/shared/resources/userSettingsResource.js +34 -29
- package/test/accountSecurityService.test.js +2 -2
- package/test/authProfileSyncService.test.js +13 -9
- package/test/exportsContract.test.js +2 -0
- package/test/featureRuntime.test.js +63 -20
- package/test/i18nCodes.test.js +6 -10
- package/test/repositories.mysql.test.js +384 -0
- package/test/resourcesCanonical.test.js +58 -22
- package/test/support/mysqlUsers.js +74 -0
- package/test/userSettingsInternalResource.test.js +3 -3
- package/test/userSettingsResource.test.js +3 -3
- package/test/usersPackageScaffoldContract.test.js +70 -12
- package/test/usersRouteRequestInputValidator.test.js +2 -2
- package/test/usersRouteResources.test.js +73 -29
- package/patterns/user-administration-server/example/packages/users/src/shared/userResource.js +0 -69
- package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userResource.js +0 -56
- package/test/repositoryContracts.test.js +0 -596
|
@@ -1,18 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
findDuplicateEntryError,
|
|
3
3
|
isLostDuplicateInsertRace,
|
|
4
|
-
joinOrOpenTransaction,
|
|
5
4
|
normalizeDbRecordId,
|
|
6
|
-
resolveTransaction,
|
|
7
|
-
retryDeadlocks,
|
|
8
5
|
toIsoString
|
|
9
6
|
} from "@jskit-ai/database-runtime/shared";
|
|
10
7
|
import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
11
|
-
import {
|
|
12
|
-
createJsonRestContext,
|
|
13
|
-
extractJsonRestCollectionRows,
|
|
14
|
-
queryAllJsonRestCollectionRows
|
|
15
|
-
} from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
|
|
8
|
+
import { isSystemContext } from "@jskit-ai/resource-runtime/server";
|
|
16
9
|
import { normalizeIdentity } from "../support/identity.js";
|
|
17
10
|
import { USERNAME_MAX_LENGTH, normalizeNullableString, normalizeNullableVersion, normalizeUsername } from "../../../shared/resources/userProfileValues.js";
|
|
18
11
|
|
|
@@ -110,6 +103,23 @@ function duplicateTargetsUsername(error) {
|
|
|
110
103
|
return message.includes("username");
|
|
111
104
|
}
|
|
112
105
|
|
|
106
|
+
function buildDuplicateUsernameConflictError(cause = undefined) {
|
|
107
|
+
const error = new Error("Username is already taken.", cause ? { cause } : undefined);
|
|
108
|
+
error.transactionOutcome = cause?.transactionOutcome;
|
|
109
|
+
error.code = "USER_PROFILE_USERNAME_CONFLICT";
|
|
110
|
+
return error;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// The fields a new profile needs, normalized; `context` names the call for its errors.
|
|
114
|
+
function requireNewProfile(profileLike, context) {
|
|
115
|
+
const payload = normalizeCreatePayload(profileLike);
|
|
116
|
+
const missing = ["authProvider", "authProviderUserSid", "email", "displayName"].filter((field) => !payload[field]);
|
|
117
|
+
if (missing.length > 0) {
|
|
118
|
+
throw new TypeError(`${context} requires ${missing.join(", ")}.`);
|
|
119
|
+
}
|
|
120
|
+
return payload;
|
|
121
|
+
}
|
|
122
|
+
|
|
113
123
|
function buildDuplicateEmailConflictError(cause) {
|
|
114
124
|
const error = new Error("Email is already linked to a different profile.", { cause });
|
|
115
125
|
error.transactionOutcome = cause.transactionOutcome;
|
|
@@ -118,11 +128,14 @@ function buildDuplicateEmailConflictError(cause) {
|
|
|
118
128
|
}
|
|
119
129
|
|
|
120
130
|
/**
|
|
121
|
-
*
|
|
131
|
+
* The username a profile gets: the base, or the first of base-2 to base-1000
|
|
132
|
+
* no other profile holds.
|
|
133
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} userProfiles
|
|
122
134
|
* @param {string} baseUsername
|
|
123
|
-
* @param {
|
|
135
|
+
* @param {unknown} excludeUserId The profile whose own username stays available to it.
|
|
136
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
|
|
124
137
|
*/
|
|
125
|
-
async function resolveUniqueUsername(
|
|
138
|
+
async function resolveUniqueUsername(userProfiles, baseUsername, excludeUserId, options) {
|
|
126
139
|
const normalizedExcludeUserId = normalizeDbRecordId(excludeUserId, { fallback: null });
|
|
127
140
|
const candidates = Array.from(
|
|
128
141
|
{ length: USERNAME_CANDIDATE_LIMIT },
|
|
@@ -130,18 +143,7 @@ async function resolveUniqueUsername(api, baseUsername, { excludeUserId = null,
|
|
|
130
143
|
);
|
|
131
144
|
|
|
132
145
|
// One read of every profile holding a candidate, however many namesakes came before.
|
|
133
|
-
const existingRows = await
|
|
134
|
-
api.resources.userProfiles,
|
|
135
|
-
{
|
|
136
|
-
queryParams: {
|
|
137
|
-
filters: {
|
|
138
|
-
usernames: candidates
|
|
139
|
-
}
|
|
140
|
-
},
|
|
141
|
-
transaction,
|
|
142
|
-
format: "plain"
|
|
143
|
-
}
|
|
144
|
-
);
|
|
146
|
+
const existingRows = await userProfiles.queryAll({ filters: { usernames: candidates } }, options);
|
|
145
147
|
const holderIdByUsername = new Map(
|
|
146
148
|
existingRows.map((row) => [normalizeLowerText(row.username), normalizeDbRecordId(row.id, { fallback: null })])
|
|
147
149
|
);
|
|
@@ -156,25 +158,25 @@ async function resolveUniqueUsername(api, baseUsername, { excludeUserId = null,
|
|
|
156
158
|
throw new Error("Unable to generate unique username.");
|
|
157
159
|
}
|
|
158
160
|
|
|
159
|
-
/**
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
)
|
|
175
|
-
);
|
|
161
|
+
/**
|
|
162
|
+
* The `users.profiles` capability: the users table's records. Every method
|
|
163
|
+
* takes the caller's options last and joins their transaction. Its reads
|
|
164
|
+
* `query`, `get` and `pageLimits` also serve a CRUD feature that names it as
|
|
165
|
+
* its `ownerRepository`.
|
|
166
|
+
* @param {object} dependencies
|
|
167
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} dependencies.userProfiles The users table's handle.
|
|
168
|
+
* @param {import("../../types.js").UserSettingsRepository} dependencies.userSettings The settings that
|
|
169
|
+
* createWithSettings writes beside a profile.
|
|
170
|
+
*/
|
|
171
|
+
function createRepository({ userProfiles, userSettings }) {
|
|
172
|
+
async function countProfiles(filters, options) {
|
|
173
|
+
const rows = await userProfiles.aggregate({ measures: { count: { count: "*" } }, filters }, options);
|
|
174
|
+
return Number(rows?.[0]?.count || 0);
|
|
175
|
+
}
|
|
176
176
|
|
|
177
|
-
|
|
177
|
+
async function queryFirst(filters, options) {
|
|
178
|
+
const { records } = await userProfiles.query({ filters, page: { size: 1 } }, options);
|
|
179
|
+
return records[0] || null;
|
|
178
180
|
}
|
|
179
181
|
|
|
180
182
|
async function findById(userId, options = {}) {
|
|
@@ -212,77 +214,38 @@ function createRepository({ api }) {
|
|
|
212
214
|
);
|
|
213
215
|
}
|
|
214
216
|
|
|
215
|
-
|
|
217
|
+
// A profile's changed fields, stamped with the update time; null for a missing id or profile.
|
|
218
|
+
async function patchProfile(userId, changes, options) {
|
|
216
219
|
const normalizedUserId = normalizeRecordId(userId, { fallback: null });
|
|
217
220
|
if (!normalizedUserId) {
|
|
218
221
|
return null;
|
|
219
222
|
}
|
|
220
223
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
},
|
|
228
|
-
format: "plain",
|
|
229
|
-
returning: "full",
|
|
230
|
-
transaction: resolveTransaction(options)
|
|
231
|
-
},
|
|
232
|
-
createJsonRestContext(options.context)
|
|
233
|
-
);
|
|
224
|
+
return normalizeProfileRecord(await userProfiles.patch(
|
|
225
|
+
normalizedUserId,
|
|
226
|
+
{ ...changes, updatedAt: new Date().toISOString() },
|
|
227
|
+
{ ...options, missing: "skip" }
|
|
228
|
+
));
|
|
229
|
+
}
|
|
234
230
|
|
|
235
|
-
|
|
231
|
+
async function updateDisplayNameById(userId, displayName, options = {}) {
|
|
232
|
+
return patchProfile(userId, { displayName }, options);
|
|
236
233
|
}
|
|
237
234
|
|
|
238
235
|
async function updateAvatarById(userId, avatar = {}, options = {}) {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
const updated = await api.resources.userProfiles.patch(
|
|
245
|
-
{
|
|
246
|
-
id: normalizedUserId,
|
|
247
|
-
data: {
|
|
248
|
-
avatarStorageKey: avatar.avatarStorageKey ?? null,
|
|
249
|
-
avatarVersion: avatar.avatarVersion ?? null,
|
|
250
|
-
avatarUpdatedAt: toIsoString(avatar.avatarUpdatedAt ?? new Date()),
|
|
251
|
-
updatedAt: new Date().toISOString()
|
|
252
|
-
},
|
|
253
|
-
format: "plain",
|
|
254
|
-
returning: "full",
|
|
255
|
-
transaction: resolveTransaction(options)
|
|
256
|
-
},
|
|
257
|
-
createJsonRestContext(options.context)
|
|
258
|
-
);
|
|
259
|
-
|
|
260
|
-
return normalizeProfileRecord(updated);
|
|
236
|
+
return patchProfile(userId, {
|
|
237
|
+
avatarStorageKey: avatar.avatarStorageKey ?? null,
|
|
238
|
+
avatarVersion: avatar.avatarVersion ?? null,
|
|
239
|
+
avatarUpdatedAt: toIsoString(avatar.avatarUpdatedAt ?? new Date())
|
|
240
|
+
}, options);
|
|
261
241
|
}
|
|
262
242
|
|
|
263
243
|
async function clearAvatarById(userId, options = {}) {
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
const updated = await api.resources.userProfiles.patch(
|
|
270
|
-
{
|
|
271
|
-
id: normalizedUserId,
|
|
272
|
-
data: {
|
|
273
|
-
avatarStorageKey: null,
|
|
274
|
-
avatarVersion: null,
|
|
275
|
-
avatarUpdatedAt: null,
|
|
276
|
-
updatedAt: new Date().toISOString()
|
|
277
|
-
},
|
|
278
|
-
format: "plain",
|
|
279
|
-
returning: "full",
|
|
280
|
-
transaction: resolveTransaction(options)
|
|
281
|
-
},
|
|
282
|
-
createJsonRestContext(options.context)
|
|
283
|
-
);
|
|
284
|
-
|
|
285
|
-
return normalizeProfileRecord(updated);
|
|
244
|
+
return patchProfile(userId, {
|
|
245
|
+
avatarStorageKey: null,
|
|
246
|
+
avatarVersion: null,
|
|
247
|
+
avatarUpdatedAt: null
|
|
248
|
+
}, options);
|
|
286
249
|
}
|
|
287
250
|
|
|
288
251
|
async function upsert(profileLike = {}, options = {}) {
|
|
@@ -302,69 +265,45 @@ function createRepository({ api }) {
|
|
|
302
265
|
throw new TypeError("upsert requires email and displayName.");
|
|
303
266
|
}
|
|
304
267
|
|
|
305
|
-
const executeUpsert = async (
|
|
306
|
-
const existing = await findByIdentity(identity,
|
|
307
|
-
trx,
|
|
308
|
-
context: options.context
|
|
309
|
-
});
|
|
268
|
+
const executeUpsert = async (txOptions) => {
|
|
269
|
+
const existing = await findByIdentity(identity, txOptions);
|
|
310
270
|
|
|
311
271
|
if (existing) {
|
|
312
272
|
const existingUsername = normalizeUsername(existing.username);
|
|
313
273
|
const username = existingUsername || (
|
|
314
274
|
await resolveUniqueUsername(
|
|
315
|
-
|
|
275
|
+
userProfiles,
|
|
316
276
|
requestedUsername || usernameBaseFromEmail(email),
|
|
317
|
-
|
|
277
|
+
existing.id,
|
|
278
|
+
txOptions
|
|
318
279
|
)
|
|
319
280
|
);
|
|
320
281
|
|
|
321
|
-
|
|
322
|
-
{
|
|
323
|
-
id: normalizeDbRecordId(existing.id, { fallback: null }),
|
|
324
|
-
data: {
|
|
325
|
-
email,
|
|
326
|
-
displayName,
|
|
327
|
-
username,
|
|
328
|
-
updatedAt: new Date().toISOString()
|
|
329
|
-
},
|
|
330
|
-
format: "plain",
|
|
331
|
-
returning: "full",
|
|
332
|
-
transaction: trx
|
|
333
|
-
},
|
|
334
|
-
createJsonRestContext(options.context)
|
|
335
|
-
);
|
|
336
|
-
|
|
337
|
-
return normalizeProfileRecord(updated);
|
|
282
|
+
return patchProfile(existing.id, { email, displayName, username }, txOptions);
|
|
338
283
|
}
|
|
339
284
|
|
|
340
285
|
const username = await resolveUniqueUsername(
|
|
341
|
-
|
|
286
|
+
userProfiles,
|
|
342
287
|
requestedUsername || usernameBaseFromEmail(email),
|
|
343
|
-
|
|
288
|
+
null,
|
|
289
|
+
txOptions
|
|
344
290
|
);
|
|
345
291
|
|
|
346
|
-
|
|
292
|
+
return normalizeProfileRecord(await userProfiles.create(
|
|
347
293
|
{
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
createdAt: new Date().toISOString()
|
|
355
|
-
},
|
|
356
|
-
format: "plain",
|
|
357
|
-
returning: "full",
|
|
358
|
-
transaction: trx
|
|
294
|
+
authProvider: identity.provider,
|
|
295
|
+
authProviderUserSid: identity.providerUserId,
|
|
296
|
+
email,
|
|
297
|
+
displayName,
|
|
298
|
+
username,
|
|
299
|
+
createdAt: new Date().toISOString()
|
|
359
300
|
},
|
|
360
|
-
|
|
361
|
-
);
|
|
362
|
-
|
|
363
|
-
return normalizeProfileRecord(created);
|
|
301
|
+
txOptions
|
|
302
|
+
));
|
|
364
303
|
};
|
|
365
304
|
|
|
366
305
|
try {
|
|
367
|
-
return await
|
|
306
|
+
return await userProfiles.withTransaction(options, executeUpsert);
|
|
368
307
|
} catch (error) {
|
|
369
308
|
if (["pending", "rolledBack"].includes(error?.transactionOutcome) && duplicateTargetsEmail(error)) {
|
|
370
309
|
throw buildDuplicateEmailConflictError(error);
|
|
@@ -384,15 +323,177 @@ function createRepository({ api }) {
|
|
|
384
323
|
}
|
|
385
324
|
}
|
|
386
325
|
|
|
326
|
+
/**
|
|
327
|
+
* Creates (or, for an identity that already has one, updates) a profile and
|
|
328
|
+
* gives it its settings, in one transaction: the caller's, or one it opens.
|
|
329
|
+
* Settings start from the defaults; the given fields replace them.
|
|
330
|
+
* @param {{ profile: object, settings?: object }} input
|
|
331
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
|
|
332
|
+
*/
|
|
333
|
+
async function createWithSettings({ profile, settings = {} }, options = {}) {
|
|
334
|
+
return userProfiles.withTransaction(options, async (txOptions) => {
|
|
335
|
+
const created = await upsert(profile, txOptions);
|
|
336
|
+
return {
|
|
337
|
+
profile: created,
|
|
338
|
+
settings: await userSettings.patchUserSettings(created.id, settings, txOptions)
|
|
339
|
+
};
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Creates a profile with the id it is given, as an application that keeps
|
|
345
|
+
* the ids of an earlier users table does, in one transaction: the caller's,
|
|
346
|
+
* or one it opens. Its username is the one given or one made from its email,
|
|
347
|
+
* the first of base, base-2 to base-1000 no other profile holds. A taken id or
|
|
348
|
+
* identity fails. On PostgreSQL the id sequence does not move past a given
|
|
349
|
+
* id, so an import advances it (setval) before the table creates profiles of
|
|
350
|
+
* its own again.
|
|
351
|
+
* @param {{ id: unknown, authProvider: string, authProviderUserSid: string, email: string, displayName: string, username?: string, avatarStorageKey?: string | null, avatarVersion?: string | null, avatarUpdatedAt?: Date | string | null }} profile
|
|
352
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
|
|
353
|
+
*/
|
|
354
|
+
async function createWithId(profile, options = {}) {
|
|
355
|
+
const id = normalizeDbRecordId(profile?.id, { fallback: null });
|
|
356
|
+
if (!id) {
|
|
357
|
+
throw new TypeError("createWithId requires id.");
|
|
358
|
+
}
|
|
359
|
+
const payload = requireNewProfile(profile, "createWithId");
|
|
360
|
+
return userProfiles.withTransaction(options, async (txOptions) => {
|
|
361
|
+
const username = await resolveUniqueUsername(
|
|
362
|
+
userProfiles,
|
|
363
|
+
payload.username || usernameBaseFromEmail(payload.email),
|
|
364
|
+
null,
|
|
365
|
+
txOptions
|
|
366
|
+
);
|
|
367
|
+
const now = new Date().toISOString();
|
|
368
|
+
return normalizeProfileRecord(await userProfiles.create(
|
|
369
|
+
{ ...payload, id, username, createdAt: now, updatedAt: now },
|
|
370
|
+
txOptions
|
|
371
|
+
));
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* The profiles with these emails, compared in lower case, in one read; an
|
|
377
|
+
* email no profile has is left out.
|
|
378
|
+
* @param {readonly string[]} emails
|
|
379
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
|
|
380
|
+
*/
|
|
381
|
+
async function listByEmails(emails, options = {}) {
|
|
382
|
+
if (!Array.isArray(emails)) {
|
|
383
|
+
throw new TypeError("listByEmails takes an array of emails.");
|
|
384
|
+
}
|
|
385
|
+
const normalizedEmails = [...new Set(emails.map((email) => normalizeLowerText(email)).filter(Boolean))];
|
|
386
|
+
if (normalizedEmails.length < 1) {
|
|
387
|
+
return [];
|
|
388
|
+
}
|
|
389
|
+
const rows = await userProfiles.queryAll({ filters: { emails: normalizedEmails } }, options);
|
|
390
|
+
return rows.map(normalizeProfileRecord);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Creates the profiles whose identity (authProvider and authProviderUserSid)
|
|
395
|
+
* has none yet, in one INSERT per chunk, and leaves those that have one as
|
|
396
|
+
* they are: a bulk import that may run again. Only background work may call
|
|
397
|
+
* it, in a system context (`systemContext(reason)`), since it writes users no
|
|
398
|
+
* caller signed in as. Each row names its username; an email or username
|
|
399
|
+
* another identity holds fails the whole call.
|
|
400
|
+
* @param {ReadonlyArray<{ authProvider: string, authProviderUserSid: string, email: string, displayName: string, username: string }>} profiles
|
|
401
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
|
|
402
|
+
* @returns {Promise<string[]>} The ids of the profiles it created; a row whose identity already had one adds none.
|
|
403
|
+
*/
|
|
404
|
+
async function createManyIgnoringExisting(profiles, options = {}) {
|
|
405
|
+
if (!isSystemContext(options.context)) {
|
|
406
|
+
throw new TypeError("createManyIgnoringExisting runs only in a system context: pass { context: systemContext(reason) }.");
|
|
407
|
+
}
|
|
408
|
+
if (!Array.isArray(profiles)) {
|
|
409
|
+
throw new TypeError("createManyIgnoringExisting takes an array of profiles.");
|
|
410
|
+
}
|
|
411
|
+
const now = new Date().toISOString();
|
|
412
|
+
const rows = profiles.map((profile, index) => {
|
|
413
|
+
const payload = requireNewProfile(profile, `createManyIgnoringExisting row ${index}`);
|
|
414
|
+
if (!payload.username) {
|
|
415
|
+
throw new TypeError(`createManyIgnoringExisting row ${index} requires username.`);
|
|
416
|
+
}
|
|
417
|
+
return { ...payload, createdAt: now, updatedAt: now };
|
|
418
|
+
});
|
|
419
|
+
if (rows.length < 1) {
|
|
420
|
+
return [];
|
|
421
|
+
}
|
|
422
|
+
return userProfiles.createMany(rows, {
|
|
423
|
+
...options,
|
|
424
|
+
returning: "ids",
|
|
425
|
+
onConflict: { keys: ["authProvider", "authProviderUserSid"], action: "ignore" }
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Gives a profile a new username, in one transaction: the caller's, or one
|
|
431
|
+
* it opens. A username another profile holds is USER_PROFILE_USERNAME_CONFLICT,
|
|
432
|
+
* found before the write so the caller's transaction stays usable; null for a
|
|
433
|
+
* missing id or profile.
|
|
434
|
+
* @param {unknown} userId
|
|
435
|
+
* @param {string} username
|
|
436
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
|
|
437
|
+
*/
|
|
438
|
+
async function changeUsername(userId, username, options = {}) {
|
|
439
|
+
const normalizedUsername = normalizeUsername(username);
|
|
440
|
+
if (!normalizedUsername) {
|
|
441
|
+
throw new TypeError("changeUsername requires a username.");
|
|
442
|
+
}
|
|
443
|
+
const normalizedUserId = normalizeDbRecordId(userId, { fallback: null });
|
|
444
|
+
try {
|
|
445
|
+
return await userProfiles.withTransaction(options, async (txOptions) => {
|
|
446
|
+
const holders = await userProfiles.queryAll({ filters: { usernames: [normalizedUsername] } }, txOptions);
|
|
447
|
+
if (holders.some((row) => normalizeDbRecordId(row.id, { fallback: null }) !== normalizedUserId)) {
|
|
448
|
+
throw buildDuplicateUsernameConflictError();
|
|
449
|
+
}
|
|
450
|
+
return patchProfile(userId, { username: normalizedUsername }, txOptions);
|
|
451
|
+
});
|
|
452
|
+
} catch (error) {
|
|
453
|
+
// Another request took it between the read and the write.
|
|
454
|
+
if (["pending", "rolledBack"].includes(error?.transactionOutcome) && duplicateTargetsUsername(error)) {
|
|
455
|
+
throw buildDuplicateUsernameConflictError(error);
|
|
456
|
+
}
|
|
457
|
+
throw error;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* The number of users, leaving out `excludeIds` and, with `createdSince`,
|
|
463
|
+
* those created before it; with `authProvider`, only those who sign in with it.
|
|
464
|
+
* @param {{ excludeIds?: readonly unknown[], createdSince?: Date | string | null, authProvider?: string }} [criteria]
|
|
465
|
+
* @param {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} [options]
|
|
466
|
+
*/
|
|
467
|
+
async function countUsers({ excludeIds = [], createdSince = null, authProvider = "" } = {}, options = {}) {
|
|
468
|
+
const filters = {
|
|
469
|
+
...(createdSince == null ? {} : { createdSince: toIsoString(createdSince) }),
|
|
470
|
+
...(normalizeLowerText(authProvider) ? { authProvider: normalizeLowerText(authProvider) } : {})
|
|
471
|
+
};
|
|
472
|
+
const ids = [...new Set(excludeIds.map((id) => normalizeDbRecordId(id, { fallback: null })).filter(Boolean))];
|
|
473
|
+
const total = await countProfiles(filters, options);
|
|
474
|
+
// The id filter has no "not in": the excluded users who match are subtracted.
|
|
475
|
+
return ids.length < 1 ? total : total - await countProfiles({ ...filters, id: ids }, options);
|
|
476
|
+
}
|
|
477
|
+
|
|
387
478
|
return Object.freeze({
|
|
388
|
-
withTransaction,
|
|
479
|
+
withTransaction: userProfiles.withTransaction,
|
|
389
480
|
findById,
|
|
390
481
|
findByEmail,
|
|
391
482
|
findByIdentity,
|
|
392
483
|
updateDisplayNameById,
|
|
393
484
|
updateAvatarById,
|
|
394
485
|
clearAvatarById,
|
|
395
|
-
upsert
|
|
486
|
+
upsert,
|
|
487
|
+
createWithSettings,
|
|
488
|
+
createWithId,
|
|
489
|
+
createManyIgnoringExisting,
|
|
490
|
+
listByEmails,
|
|
491
|
+
changeUsername,
|
|
492
|
+
countUsers,
|
|
493
|
+
// The CRUD surface's reads (a CRUD feature serving the users table names this repository as its ownerRepository).
|
|
494
|
+
query: userProfiles.query,
|
|
495
|
+
get: userProfiles.get,
|
|
496
|
+
pageLimits: userProfiles.pageLimits
|
|
396
497
|
});
|
|
397
498
|
}
|
|
398
499
|
|
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
import { isLostDuplicateInsertRace
|
|
1
|
+
import { isLostDuplicateInsertRace } from "@jskit-ai/database-runtime/shared";
|
|
2
2
|
import { normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
|
-
import {
|
|
4
|
-
createJsonRestContext,
|
|
5
|
-
extractJsonRestCollectionRows
|
|
6
|
-
} from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
|
|
7
3
|
import { DEFAULT_USER_SETTINGS, normalizeLocaleCode } from "../../../shared/settings.js";
|
|
8
4
|
|
|
9
5
|
const USER_SETTINGS_PATCH_FIELDS = Object.freeze([
|
|
@@ -51,36 +47,23 @@ function buildDefaultUserSettingsCreatePayload(userId) {
|
|
|
51
47
|
};
|
|
52
48
|
}
|
|
53
49
|
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
{
|
|
62
|
-
queryParams: {
|
|
63
|
-
filters
|
|
64
|
-
},
|
|
65
|
-
transaction: resolveTransaction(options),
|
|
66
|
-
format: "plain"
|
|
67
|
-
},
|
|
68
|
-
createJsonRestContext(options.context)
|
|
69
|
-
)
|
|
70
|
-
);
|
|
71
|
-
|
|
72
|
-
const row = rows[0] || null;
|
|
73
|
-
// Rows saved before locales were canonical hold lowercased tags ("en-us").
|
|
74
|
-
return typeof row?.locale === "string" ? { ...row, locale: normalizeLocaleCode(row.locale) } : row;
|
|
75
|
-
}
|
|
76
|
-
|
|
50
|
+
/**
|
|
51
|
+
* The `users.settings` capability: the user_settings table's records. Every
|
|
52
|
+
* method takes the caller's options last and joins their transaction.
|
|
53
|
+
* @param {{ userSettings: import("@jskit-ai/resource-runtime/server/types").ResourceHandle }} dependencies
|
|
54
|
+
* The user_settings table's handle.
|
|
55
|
+
*/
|
|
56
|
+
function createRepository({ userSettings }) {
|
|
77
57
|
async function findByUserId(userId, options = {}) {
|
|
78
58
|
const normalizedUserId = normalizeRecordId(userId, { fallback: null });
|
|
79
59
|
if (!normalizedUserId) {
|
|
80
60
|
return null;
|
|
81
61
|
}
|
|
82
62
|
|
|
83
|
-
|
|
63
|
+
const { records } = await userSettings.query({ filters: { id: normalizedUserId }, page: { size: 1 } }, options);
|
|
64
|
+
const row = records[0] || null;
|
|
65
|
+
// Rows saved before locales were canonical hold lowercased tags ("en-us").
|
|
66
|
+
return typeof row?.locale === "string" ? { ...row, locale: normalizeLocaleCode(row.locale) } : row;
|
|
84
67
|
}
|
|
85
68
|
|
|
86
69
|
async function ensureForUserId(userId, options = {}) {
|
|
@@ -95,16 +78,9 @@ function createRepository({ api }) {
|
|
|
95
78
|
}
|
|
96
79
|
|
|
97
80
|
try {
|
|
98
|
-
await
|
|
99
|
-
{
|
|
100
|
-
data: buildDefaultUserSettingsCreatePayload(normalizedUserId),
|
|
101
|
-
format: "plain",
|
|
102
|
-
returning: "full",
|
|
103
|
-
transaction: resolveTransaction(options)
|
|
104
|
-
},
|
|
105
|
-
createJsonRestContext(options.context)
|
|
106
|
-
);
|
|
81
|
+
await userSettings.create(buildDefaultUserSettingsCreatePayload(normalizedUserId), { ...options, returning: "none" });
|
|
107
82
|
} catch (error) {
|
|
83
|
+
// A standalone insert that lost to another one reads the winner; inside the caller's transaction it fails it.
|
|
108
84
|
if (!isLostDuplicateInsertRace(error, options)) {
|
|
109
85
|
throw error;
|
|
110
86
|
}
|
|
@@ -127,18 +103,13 @@ function createRepository({ api }) {
|
|
|
127
103
|
return findByUserId(normalizedUserId, options);
|
|
128
104
|
}
|
|
129
105
|
|
|
130
|
-
await
|
|
106
|
+
await userSettings.patch(
|
|
107
|
+
normalizedUserId,
|
|
131
108
|
{
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
...updatePayload,
|
|
135
|
-
updatedAt: new Date().toISOString()
|
|
136
|
-
},
|
|
137
|
-
format: "plain",
|
|
138
|
-
returning: "full",
|
|
139
|
-
transaction: resolveTransaction(options)
|
|
109
|
+
...updatePayload,
|
|
110
|
+
updatedAt: new Date().toISOString()
|
|
140
111
|
},
|
|
141
|
-
|
|
112
|
+
{ ...options, returning: "none" }
|
|
142
113
|
);
|
|
143
114
|
|
|
144
115
|
return findByUserId(normalizedUserId, options);
|
|
@@ -170,7 +141,7 @@ function createRepository({ api }) {
|
|
|
170
141
|
}
|
|
171
142
|
|
|
172
143
|
return Object.freeze({
|
|
173
|
-
withTransaction,
|
|
144
|
+
withTransaction: userSettings.withTransaction,
|
|
174
145
|
findByUserId,
|
|
175
146
|
ensureForUserId,
|
|
176
147
|
patchUserSettings,
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { joinOrOpenTransaction } from "@jskit-ai/database-runtime/shared";
|
|
2
1
|
import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
2
|
import { normalizeIdentity } from "../support/identity.js";
|
|
4
3
|
|
|
@@ -93,7 +92,7 @@ function createService({ userProfilesRepository, resolveLifecycleContributors, u
|
|
|
93
92
|
* contributors (personal workspace provisioning). With `onlyWhenChanged`, an existing row that already
|
|
94
93
|
* matches the identity is answered after one read, without that work: an ordinary request's check.
|
|
95
94
|
* @param {object} profileLike
|
|
96
|
-
* @param {{ onlyWhenChanged?: boolean, trx?: object }} [options]
|
|
95
|
+
* @param {{ onlyWhenChanged?: boolean, trx?: object, context?: object }} [options]
|
|
97
96
|
*/
|
|
98
97
|
async function syncIdentityProfile(profileLike, { onlyWhenChanged = false, ...options } = {}) {
|
|
99
98
|
const normalized = buildNormalizedIdentityProfile(profileLike);
|
|
@@ -103,8 +102,7 @@ function createService({ userProfilesRepository, resolveLifecycleContributors, u
|
|
|
103
102
|
}
|
|
104
103
|
const lifecycleContributors = resolveLifecycleContributors();
|
|
105
104
|
|
|
106
|
-
const runSync = async (
|
|
107
|
-
const operationOptions = { ...options, trx };
|
|
105
|
+
const runSync = async (operationOptions) => {
|
|
108
106
|
const existing = await findByIdentity(normalized, operationOptions);
|
|
109
107
|
let created = false;
|
|
110
108
|
if (!profileNeedsUpdate(existing, normalized)) {
|
|
@@ -135,7 +133,7 @@ function createService({ userProfilesRepository, resolveLifecycleContributors, u
|
|
|
135
133
|
return synchronizedProfile;
|
|
136
134
|
};
|
|
137
135
|
|
|
138
|
-
return
|
|
136
|
+
return userProfilesRepository.withTransaction(options, runSync);
|
|
139
137
|
}
|
|
140
138
|
|
|
141
139
|
return Object.freeze({
|
package/src/server/types.js
CHANGED
|
@@ -2,7 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
/** @typedef {ReturnType<typeof import("./usersRuntime.js").createUsersRuntime>} UsersCore */
|
|
4
4
|
/** @typedef {ReturnType<typeof import("./usersExtensions.js").createUsersExtensions>} UsersExtensions */
|
|
5
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* The handles of the tables `users.identity` owns: users (`userProfiles`) and user_settings (`userSettings`).
|
|
7
|
+
* @typedef {{
|
|
8
|
+
* userProfiles: import("@jskit-ai/resource-runtime/server/types").ResourceHandle,
|
|
9
|
+
* userSettings: import("@jskit-ai/resource-runtime/server/types").ResourceHandle
|
|
10
|
+
* }} UsersResources
|
|
11
|
+
*/
|
|
12
|
+
/** @typedef {ReturnType<typeof import("./common/repositories/userProfilesRepository.js").createRepository>} UsersProfiles The users table's records: `users.profiles`. */
|
|
13
|
+
/** @typedef {ReturnType<typeof import("./common/repositories/userSettingsRepository.js").createRepository>} UsersSettings The users' settings records: `users.settings`. */
|
|
6
14
|
|
|
7
15
|
/**
|
|
8
16
|
* The users' profile repository, as the account services receive it.
|