@frigear-nu/users 3.1.4 → 3.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/module.d.mts +117 -1
  2. package/dist/module.json +1 -1
  3. package/dist/module.mjs +144 -27
  4. package/dist/runtime/access.js +3 -3
  5. package/dist/runtime/app/components/UserCreateSlideover.vue +8 -6
  6. package/dist/runtime/app/components/UserPicker.d.vue.ts +2 -2
  7. package/dist/runtime/app/components/UserPicker.vue.d.ts +2 -2
  8. package/dist/runtime/app/components/UsersAdminTerms.d.vue.ts +7 -0
  9. package/dist/runtime/app/components/UsersAdminTerms.vue +55 -0
  10. package/dist/runtime/app/components/UsersAdminTerms.vue.d.ts +7 -0
  11. package/dist/runtime/app/components/UsersTermsGate.d.vue.ts +11 -0
  12. package/dist/runtime/app/components/UsersTermsGate.vue +82 -0
  13. package/dist/runtime/app/components/UsersTermsGate.vue.d.ts +11 -0
  14. package/dist/runtime/app/components/UsersTermsText.d.vue.ts +7 -0
  15. package/dist/runtime/app/components/UsersTermsText.vue +34 -0
  16. package/dist/runtime/app/components/UsersTermsText.vue.d.ts +7 -0
  17. package/dist/runtime/app/composables/useUserActions.d.ts +6 -2
  18. package/dist/runtime/app/composables/useUserActions.js +32 -3
  19. package/dist/runtime/app/pages/admin-user.vue +3 -0
  20. package/dist/runtime/app/pages/admin.vue +23 -5
  21. package/dist/runtime/app/pages/revert-email-change.vue +2 -1
  22. package/dist/runtime/app/plugins/offer-locale.client.js +22 -3
  23. package/dist/runtime/app/plugins/terms-gate.client.d.ts +2 -0
  24. package/dist/runtime/app/plugins/terms-gate.client.js +55 -0
  25. package/dist/runtime/app/tabs/Overview.vue +88 -14
  26. package/dist/runtime/app/utils/admin-user.d.ts +4 -2
  27. package/dist/runtime/app/utils/terms.d.ts +10 -0
  28. package/dist/runtime/app/utils/terms.js +7 -0
  29. package/dist/runtime/app/widgets/NewUsers.d.vue.ts +4 -1
  30. package/dist/runtime/app/widgets/NewUsers.vue +7 -4
  31. package/dist/runtime/app/widgets/NewUsers.vue.d.ts +4 -1
  32. package/dist/runtime/app/widgets/NewUsersStat.d.vue.ts +4 -1
  33. package/dist/runtime/app/widgets/NewUsersStat.vue +4 -1
  34. package/dist/runtime/app/widgets/NewUsersStat.vue.d.ts +4 -1
  35. package/dist/runtime/app/widgets/UsersAccountTerms.d.vue.ts +6 -0
  36. package/dist/runtime/app/widgets/UsersAccountTerms.vue +63 -0
  37. package/dist/runtime/app/widgets/UsersAccountTerms.vue.d.ts +6 -0
  38. package/dist/runtime/app/widgets/UsersRegisterTerms.d.vue.ts +9 -0
  39. package/dist/runtime/app/widgets/UsersRegisterTerms.vue +37 -0
  40. package/dist/runtime/app/widgets/UsersRegisterTerms.vue.d.ts +9 -0
  41. package/dist/runtime/db/schema.postgresql.d.ts +68 -0
  42. package/dist/runtime/db/schema.postgresql.js +15 -4
  43. package/dist/runtime/db/schema.sqlite.d.ts +72 -0
  44. package/dist/runtime/db/schema.sqlite.js +15 -4
  45. package/dist/runtime/db/terms-users.postgresql.d.ts +24 -0
  46. package/dist/runtime/db/terms-users.postgresql.js +4 -0
  47. package/dist/runtime/db/terms-users.sqlite.d.ts +26 -0
  48. package/dist/runtime/db/terms-users.sqlite.js +4 -0
  49. package/dist/runtime/db/terms.postgresql.d.ts +162 -0
  50. package/dist/runtime/db/terms.postgresql.js +21 -0
  51. package/dist/runtime/db/terms.sqlite.d.ts +173 -0
  52. package/dist/runtime/db/terms.sqlite.js +21 -0
  53. package/dist/runtime/i18n/lang/da.json +85 -6
  54. package/dist/runtime/i18n/lang/en.json +85 -6
  55. package/dist/runtime/server/plugins/terms-claims.d.ts +13 -0
  56. package/dist/runtime/server/plugins/terms-claims.js +19 -0
  57. package/dist/runtime/server/plugins/terms.d.ts +15 -0
  58. package/dist/runtime/server/plugins/terms.js +43 -0
  59. package/dist/runtime/server/routes/admin/user-avatar.delete.d.ts +2 -0
  60. package/dist/runtime/server/routes/admin/user-avatar.delete.js +11 -0
  61. package/dist/runtime/server/routes/admin/user-terms.get.d.ts +2 -0
  62. package/dist/runtime/server/routes/admin/user-terms.get.js +12 -0
  63. package/dist/runtime/server/routes/admin/user.delete.js +2 -0
  64. package/dist/runtime/server/routes/admin/user.patch.js +14 -3
  65. package/dist/runtime/server/routes/admin/users.get.js +11 -3
  66. package/dist/runtime/server/routes/admin/users.post.js +1 -0
  67. package/dist/runtime/server/routes/avatar.get.d.ts +2 -0
  68. package/dist/runtime/server/routes/avatar.get.js +12 -0
  69. package/dist/runtime/server/routes/me/avatar.delete.d.ts +2 -0
  70. package/dist/runtime/server/routes/me/avatar.delete.js +13 -0
  71. package/dist/runtime/server/routes/me/avatar.put.d.ts +2 -0
  72. package/dist/runtime/server/routes/me/avatar.put.js +20 -0
  73. package/dist/runtime/server/routes/me/profile.patch.js +23 -4
  74. package/dist/runtime/server/routes/me/terms.get.d.ts +2 -0
  75. package/dist/runtime/server/routes/me/terms.get.js +4 -0
  76. package/dist/runtime/server/routes/me/terms.post.d.ts +2 -0
  77. package/dist/runtime/server/routes/me/terms.post.js +18 -0
  78. package/dist/runtime/server/schemas.d.ts +12 -1
  79. package/dist/runtime/server/schemas.js +6 -1
  80. package/dist/runtime/server/search-index.js +2 -2
  81. package/dist/runtime/server/user-store.js +2 -1
  82. package/dist/runtime/server/utils/dto.d.ts +5 -1
  83. package/dist/runtime/server/utils/dto.js +8 -0
  84. package/dist/runtime/server/utils/user-refs.d.ts +2 -1
  85. package/dist/runtime/server/utils/user-refs.js +8 -2
  86. package/dist/runtime/server/utils/user-search.d.ts +13 -5
  87. package/dist/runtime/server/utils/user-search.js +13 -1
  88. package/dist/runtime/server/utils/users-avatar.d.ts +29 -0
  89. package/dist/runtime/server/utils/users-avatar.js +69 -0
  90. package/dist/runtime/server/utils/users-terms.d.ts +35 -0
  91. package/dist/runtime/server/utils/users-terms.js +90 -0
  92. package/dist/runtime/utils/api.d.ts +25 -4
  93. package/dist/runtime/utils/api.js +23 -3
  94. package/dist/runtime/utils/avatar.d.ts +25 -0
  95. package/dist/runtime/utils/avatar.js +23 -0
  96. package/dist/runtime/utils/profile.d.ts +14 -0
  97. package/dist/runtime/utils/profile.js +8 -0
  98. package/dist/runtime/utils/terms-claim.d.ts +27 -0
  99. package/dist/runtime/utils/terms-claim.js +15 -0
  100. package/dist/types.d.mts +1 -1
  101. package/package.json +18 -13
@@ -0,0 +1,19 @@
1
+ import { db, schema } from "@nuxthub/db";
2
+ import { desc, eq } from "drizzle-orm";
3
+ import { toUsersTermsClaim } from "../../utils/terms-claim.js";
4
+ export async function addUserTermsClaim(ctx) {
5
+ if (ctx.tokenType === "access_token" || !ctx.scope.includes("profile") || "terms" in ctx.claims) return;
6
+ const table = schema.userTermsAcceptances;
7
+ const [row] = await db.select().from(table).where(eq(table.userId, Number(ctx.user.id))).orderBy(desc(table.acceptedAt), desc(table.id)).limit(1);
8
+ if (row) ctx.claims.terms = toUsersTermsClaim(row);
9
+ }
10
+ export default defineNitroPlugin((nitro) => {
11
+ const hooks = nitro.hooks;
12
+ hooks.hook("oauth:claims", async (ctx) => {
13
+ try {
14
+ await addUserTermsClaim(ctx);
15
+ } catch (error) {
16
+ console.error(`[users] Could not add the terms claim for user ${ctx.user.id}.`, error);
17
+ }
18
+ });
19
+ });
@@ -0,0 +1,15 @@
1
+ /** What the frigear.nu login hands this plugin (auth's `auth:frigear:login` context, `FrigearLoginContext`). */
2
+ export interface UsersTermsLoginContext {
3
+ user: {
4
+ id: number;
5
+ } & Record<string, unknown>;
6
+ claims: Record<string, unknown>;
7
+ }
8
+ /**
9
+ * At a frigear.nu login: the `terms` claim (profile scope) is recorded as an acceptance
10
+ * here (`source: 'oauth'`, at the time it was given there) when it is for the same terms, the current version and the
11
+ * same text, and the user has not accepted this version here yet. Anything else is left to the prompt.
12
+ */
13
+ export declare function storeFrigearTermsClaim(ctx: UsersTermsLoginContext): Promise<void>;
14
+ declare const _default: any;
15
+ export default _default;
@@ -0,0 +1,43 @@
1
+ import { matchUsersTermsClaim } from "../../utils/terms-claim.js";
2
+ export async function storeFrigearTermsClaim(ctx) {
3
+ const config = usersTermsConfig();
4
+ if (!config) return;
5
+ const match = matchUsersTermsClaim(ctx.claims.terms, config);
6
+ if (!match) return;
7
+ const userId = Number(ctx.user.id);
8
+ const status = await usersTermsStatus(void 0, userId);
9
+ if (status.upToDate) return;
10
+ await usersRecordTermsAcceptance(void 0, userId, { locale: match.locale, source: "oauth", acceptedAt: match.acceptedAt });
11
+ }
12
+ export default defineNitroPlugin((nitro) => {
13
+ nitro.hooks.hook("auth:user:created", async (ctx) => {
14
+ const extra = ctx.extras?.users;
15
+ if (!extra || typeof extra !== "object") return;
16
+ const { termsVersion, locale } = extra;
17
+ const config = usersTermsConfig(ctx.event);
18
+ if (!config || typeof termsVersion !== "string" || termsVersion !== config.version) return;
19
+ try {
20
+ await usersRecordTermsAcceptance(ctx.event, Number(ctx.user.id), {
21
+ locale: typeof locale === "string" ? locale.slice(0, 35) : null,
22
+ source: "sign-up"
23
+ });
24
+ } catch (error) {
25
+ console.error(`[users] Could not record the terms acceptance of the new account ${ctx.user.id}.`, error);
26
+ }
27
+ });
28
+ const hooks = nitro.hooks;
29
+ hooks.hook("auth:frigear:login", async (ctx) => {
30
+ try {
31
+ await storeFrigearTermsClaim(ctx);
32
+ } catch (error) {
33
+ console.error(`[users] Could not record the terms claim of user ${ctx.user.id}.`, error);
34
+ }
35
+ });
36
+ nitro.hooks.hook("users:deleted", async (ctx) => {
37
+ try {
38
+ await usersDeleteTermsHistory(ctx.userId);
39
+ } catch (error) {
40
+ console.error(`[users] Could not remove the terms history of the deleted user ${ctx.userId}.`, error);
41
+ }
42
+ });
43
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,11 @@
1
+ import { db, schema } from "@nuxthub/db";
2
+ import { eq } from "drizzle-orm";
3
+ import { noContent } from "@frigear-nu/module-kit/server";
4
+ export default defineEventHandler(async (event) => {
5
+ const { target } = await loadUsersAdminTarget(event, "update");
6
+ if (target.avatar !== null) {
7
+ await db.update(schema.users).set({ avatar: null, updatedAt: /* @__PURE__ */ new Date() }).where(eq(schema.users.id, target.id));
8
+ await deleteUserAvatar(target.avatar, target.id);
9
+ }
10
+ return noContent(event);
11
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,12 @@
1
+ import { db, schema } from "@nuxthub/db";
2
+ import { eq } from "drizzle-orm";
3
+ import { intIdParams, notFound } from "@frigear-nu/module-kit/server";
4
+ import { usersAccess } from "../../../access.js";
5
+ export default defineEventHandler(async (event) => {
6
+ await authorize(event, usersAccess.permissions.pii);
7
+ const { id } = await getValidatedRouterParams(event, intIdParams().parse);
8
+ const [target] = await db.select().from(schema.users).where(eq(schema.users.id, id)).limit(1);
9
+ if (!target) throw notFound("User not found.");
10
+ await authorize(event, usersAccess.permissions.pii, target);
11
+ return usersTermsHistory(id);
12
+ });
@@ -8,5 +8,7 @@ export default defineEventHandler(async (event) => {
8
8
  }
9
9
  await deleteUserAuthData(target.id);
10
10
  await db.delete(schema.users).where(eq(schema.users.id, target.id));
11
+ await deleteUserAvatarFiles(target.id);
12
+ await useNitroApp().hooks.callHook("users:deleted", { event, userId: target.id });
11
13
  return noContent(event);
12
14
  });
@@ -2,13 +2,18 @@ import { db, schema } from "@nuxthub/db";
2
2
  import { eq } from "drizzle-orm";
3
3
  import { z } from "zod";
4
4
  import { usersAccess } from "../../../access.js";
5
- import { emailField, nameField, phoneField } from "../../schemas.js";
5
+ import { emailField, nameField, nicknameField, peopleNumberField, phoneField } from "../../schemas.js";
6
6
  const bodySchema = z.object({
7
7
  name: nameField().optional(),
8
+ // `null` or an empty string clears it.
9
+ nickname: nicknameField().optional(),
8
10
  email: emailField().optional(),
9
11
  emailVerified: z.boolean().optional(),
10
12
  // `null` or an empty string clears it; changing it needs `users:pii` as well.
11
- phone: phoneField().optional()
13
+ phone: phoneField().optional(),
14
+ // The person's id in an external system: personal data like the phone number, so `users:pii` as well. The media
15
+ // opt-outs are not here: they are the user's own choice.
16
+ peopleNumber: peopleNumberField().optional()
12
17
  });
13
18
  export default defineEventHandler(async (event) => {
14
19
  const { target } = await loadUsersAdminTarget(event, "update");
@@ -18,10 +23,16 @@ export default defineEventHandler(async (event) => {
18
23
  if (emailChanged) await assertEmailAvailable(input.email, { exceptUserId: target.id });
19
24
  if (input.phone !== void 0) await authorize(event, usersAccess.permissions.pii, target);
20
25
  const phoneChanged = input.phone !== void 0 && input.phone !== (target.phone ?? null);
26
+ const peopleNumberChanged = input.peopleNumber !== void 0 && input.peopleNumber !== (target.peopleNumber ?? null);
21
27
  const pii = input.phone !== void 0 || await allows(event, usersAccess.permissions.pii, target);
28
+ const nicknameChanged = input.nickname !== void 0 && input.nickname !== (target.nickname ?? null);
22
29
  const changes = {
23
- ...input.name ? withUserSearchText({ name: input.name }) : {},
30
+ ...input.name || nicknameChanged ? withUserSearchText({
31
+ ...input.name ? { name: input.name } : {},
32
+ ...nicknameChanged ? { nickname: input.nickname } : {}
33
+ }, target) : {},
24
34
  ...phoneChanged ? { phone: input.phone } : {},
35
+ ...peopleNumberChanged ? { peopleNumber: input.peopleNumber } : {},
25
36
  // A changed address was typed in by staff, so it is unverified until its owner confirms it (unless staff
26
37
  // explicitly marks it verified in the same request).
27
38
  ...emailChanged ? { email: input.email, emailVerifiedAt: input.emailVerified ? /* @__PURE__ */ new Date() : null } : {},
@@ -1,13 +1,16 @@
1
1
  import { db, schema } from "@nuxthub/db";
2
- import { and, asc, count, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
2
+ import { and, asc, count, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
3
3
  import { z } from "zod";
4
4
  import { likeContains, orderByQuery, pageQuery, pageRange, paginate, searchContains } from "@frigear-nu/module-kit/server";
5
+ import { USER_MEDIA_OPT_OUTS, normalizeUserPeopleNumber } from "../../../utils/profile.js";
5
6
  const querySchema = pageQuery({
6
7
  sort: ["id", "name", "email", "role", "createdAt", "lastLoginAt"],
7
8
  defaultSort: "createdAt",
8
9
  filters: {
9
10
  role: z.string().trim().min(1).max(60).optional(),
10
- verified: z.enum(["true", "false"]).optional()
11
+ verified: z.enum(["true", "false"]).optional(),
12
+ // Users who opted out of photos (`photo`) or of tagging (`tag`).
13
+ mediaOptOut: z.enum(USER_MEDIA_OPT_OUTS).optional()
11
14
  }
12
15
  });
13
16
  export default defineEventHandler(async (event) => {
@@ -15,7 +18,12 @@ export default defineEventHandler(async (event) => {
15
18
  const query = await getValidatedQuery(event, querySchema.parse);
16
19
  const userRoles = usersRoleAssignments();
17
20
  const conditions = [];
18
- if (query.q) conditions.push(or(searchContains(schema.users.searchText, query.q), likeContains(schema.users.email, query.q)));
21
+ if (query.q) {
22
+ const peopleNumber = normalizeUserPeopleNumber(query.q);
23
+ const byPeopleNumber = peopleNumber ? eq(schema.users.peopleNumber, peopleNumber) : void 0;
24
+ conditions.push(or(searchContains(schema.users.searchText, query.q), likeContains(schema.users.email, query.q), byPeopleNumber));
25
+ }
26
+ if (query.mediaOptOut) conditions.push(eq(query.mediaOptOut === "photo" ? schema.users.photoOptOut : schema.users.tagOptOut, true));
19
27
  if (query.role && userRoles) {
20
28
  conditions.push(sql`exists (select 1 from ${userRoles} where ${userRoles.userId} = ${schema.users.id} and ${userRoles.role} = ${query.role})`);
21
29
  }
@@ -34,6 +34,7 @@ export default defineEventHandler(async (event) => {
34
34
  if (!user) {
35
35
  throw apiError(500, "internal_error", "Failed to create the user.");
36
36
  }
37
+ await notifyAuthUserCreated({ event, user, source: "admin" });
37
38
  if (input.sendWelcomeEmail && useRuntimeConfig(event).public.authentication?.mode !== "resource") {
38
39
  await sendVerificationLink(event, user, { invite: true });
39
40
  }
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,12 @@
1
+ import { z } from "zod";
2
+ import { notFound } from "@frigear-nu/module-kit/server";
3
+ import { USERS_AVATAR_FILE_PATTERN } from "../../utils/avatar.js";
4
+ const paramsSchema = z.object({
5
+ userId: z.string().regex(/^\d{1,15}$/).transform(Number),
6
+ file: z.string().regex(USERS_AVATAR_FILE_PATTERN)
7
+ });
8
+ export default defineEventHandler(async (event) => {
9
+ const params = await getValidatedRouterParams(event, (value) => paramsSchema.safeParse(value));
10
+ if (!params.success) throw notFound("There is no image.");
11
+ return serveUserAvatar(event, params.data.userId, params.data.file);
12
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,13 @@
1
+ import { db, schema } from "@nuxthub/db";
2
+ import { eq } from "drizzle-orm";
3
+ import { noContent, notFound } from "@frigear-nu/module-kit/server";
4
+ import { usersAccess } from "../../../access.js";
5
+ export default defineEventHandler(async (event) => {
6
+ const { user, kind } = await authorize(event, usersAccess.permissions["profile:write"]);
7
+ const [current] = await db.select({ avatar: schema.users.avatar }).from(schema.users).where(eq(schema.users.id, user.id));
8
+ if (!current) throw notFound("User not found.");
9
+ const [updated] = await db.update(schema.users).set({ avatar: null, updatedAt: /* @__PURE__ */ new Date() }).where(eq(schema.users.id, user.id)).returning();
10
+ await deleteUserAvatar(current.avatar, user.id);
11
+ if (kind === "session" && updated) await setUserSession(event, { user: mapUserToSession(updated) });
12
+ return noContent(event);
13
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,20 @@
1
+ import { db, schema } from "@nuxthub/db";
2
+ import { eq } from "drizzle-orm";
3
+ import { notFound } from "@frigear-nu/module-kit/server";
4
+ import { usersAccess } from "../../../access.js";
5
+ export default defineEventHandler(async (event) => {
6
+ const { user, kind } = await authorize(event, usersAccess.permissions["profile:write"]);
7
+ const avatar = await storeUserAvatar(event, user.id);
8
+ const [current] = await db.select({ avatar: schema.users.avatar }).from(schema.users).where(eq(schema.users.id, user.id));
9
+ const [updated] = await db.update(schema.users).set({ avatar, updatedAt: /* @__PURE__ */ new Date() }).where(eq(schema.users.id, user.id)).returning().catch(async (error) => {
10
+ await deleteUserAvatar(avatar, user.id);
11
+ throw error;
12
+ });
13
+ if (!updated) {
14
+ await deleteUserAvatar(avatar, user.id);
15
+ throw notFound("User not found.");
16
+ }
17
+ if (current?.avatar !== avatar) await deleteUserAvatar(current?.avatar, user.id);
18
+ if (kind === "session") await setUserSession(event, { user: mapUserToSession(updated) });
19
+ return toProfileDto(updated);
20
+ });
@@ -1,28 +1,47 @@
1
1
  import { db, schema } from "@nuxthub/db";
2
2
  import { eq } from "drizzle-orm";
3
3
  import { z } from "zod";
4
- import { notFound } from "@frigear-nu/module-kit/server";
5
- import { avatarField, localeField, nameField, phoneField } from "../../schemas.js";
4
+ import { notFound, validationError } from "@frigear-nu/module-kit/server";
5
+ import { isUploadedUserAvatar } from "../../../utils/avatar.js";
6
+ import { avatarField, localeField, nameField, nicknameField, peopleNumberField, phoneField } from "../../schemas.js";
6
7
  const bodySchema = (locales) => z.object({
7
8
  name: nameField().optional(),
9
+ // `null` or an empty string clears the nickname; leaving it out keeps it.
10
+ nickname: nicknameField().optional(),
8
11
  // `null` clears the avatar; leaving it out keeps it.
9
12
  avatar: avatarField().optional(),
10
13
  // `null` or an empty string clears the phone number; leaving it out keeps it.
11
14
  phone: phoneField().optional(),
15
+ // The caller's id in an external system; `null` or an empty string clears it.
16
+ peopleNumber: peopleNumberField().optional(),
17
+ // The caller's own media choices: no photos of them as the main subject, no tagging online.
18
+ photoOptOut: z.boolean().optional(),
19
+ tagOptOut: z.boolean().optional(),
12
20
  // The user's language: one of the app's i18n locales (else a short BCP-47 tag); `null` or `''` clears it.
13
21
  locale: localeField(locales).optional()
14
22
  });
15
23
  export default defineEventHandler(async (event) => {
16
24
  const { user, kind } = await authorize(event, "profile:write");
17
- const { name, avatar, phone, locale } = await readValidatedBody(event, bodySchema(usersLocales()).parse);
25
+ const { name, nickname, avatar, phone, peopleNumber, photoOptOut, tagOptOut, locale } = await readValidatedBody(event, bodySchema(usersLocales()).parse);
26
+ const current = name !== void 0 || nickname !== void 0 || avatar !== void 0 ? (await db.select({ name: schema.users.name, nickname: schema.users.nickname, avatar: schema.users.avatar }).from(schema.users).where(eq(schema.users.id, user.id)))[0] : void 0;
27
+ if (isUploadedUserAvatar(avatar) && avatar !== current?.avatar) {
28
+ throw validationError([{ path: ["avatar"], message: "Upload a new avatar instead." }]);
29
+ }
18
30
  const [updated] = await db.update(schema.users).set({
19
- ...name !== void 0 ? withUserSearchText({ name }) : {},
31
+ ...withUserSearchText({
32
+ ...name !== void 0 ? { name } : {},
33
+ ...nickname !== void 0 ? { nickname } : {}
34
+ }, current),
20
35
  ...avatar !== void 0 ? { avatar } : {},
21
36
  ...phone !== void 0 ? { phone } : {},
37
+ ...peopleNumber !== void 0 ? { peopleNumber } : {},
38
+ ...photoOptOut !== void 0 ? { photoOptOut } : {},
39
+ ...tagOptOut !== void 0 ? { tagOptOut } : {},
22
40
  ...locale !== void 0 ? { locale } : {},
23
41
  updatedAt: /* @__PURE__ */ new Date()
24
42
  }).where(eq(schema.users.id, user.id)).returning();
25
43
  if (!updated) throw notFound("User not found.");
44
+ if (avatar !== void 0 && current?.avatar !== avatar) await deleteUserAvatar(current?.avatar, user.id);
26
45
  if (kind === "session") await setUserSession(event, { user: mapUserToSession(updated) });
27
46
  return toProfileDto(updated);
28
47
  });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,4 @@
1
+ export default defineEventHandler(async (event) => {
2
+ const user = await requireUser(event, { sessionOnly: true });
3
+ return usersTermsStatus(event, Number(user.id));
4
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: any;
2
+ export default _default;
@@ -0,0 +1,18 @@
1
+ import { z } from "zod";
2
+ import { apiError } from "@frigear-nu/module-kit/server";
3
+ const bodySchema = z.object({
4
+ // The version the person was shown: accepting an older one (the terms changed in the meantime) is refused.
5
+ version: z.string().trim().min(1).max(100),
6
+ // The language of the text they read; one without a terms file counts as the first file's.
7
+ locale: z.string().trim().max(35).optional()
8
+ });
9
+ export default defineEventHandler(async (event) => {
10
+ const user = await requireUser(event, { sessionOnly: true });
11
+ const body = await readValidatedBody(event, bodySchema.parse);
12
+ const config = usersTermsConfig(event);
13
+ if (body.version !== config.version) {
14
+ throw apiError(409, "outdated_version", "These terms are not the current ones: reload the page.", { version: config.version });
15
+ }
16
+ await usersRecordTermsAcceptance(event, Number(user.id), { locale: body.locale, source: "prompt" });
17
+ return usersTermsStatus(event, Number(user.id));
18
+ });
@@ -3,7 +3,18 @@ import { z } from 'zod';
3
3
  export declare const emailField: () => z.ZodString;
4
4
  /** A display name. */
5
5
  export declare const nameField: () => z.ZodString;
6
- /** An avatar: an absolute http(s) URL, or `null` to clear it. */
6
+ /** A nickname: trimmed, at most 50 characters, or `null` to clear it. An empty string clears it too. */
7
+ export declare const nicknameField: () => z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<string | null, string>>>;
8
+ /**
9
+ * A people number (the person's id in an external system): trimmed, at most 64 characters, or `null` to clear it. An
10
+ * empty string clears it too. Not unique: two users may type the same number.
11
+ */
12
+ export declare const peopleNumberField: () => z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<string | null, string>>>;
13
+ /**
14
+ * An avatar: an absolute http(s) URL, or `null` to clear it. An uploaded avatar's bare path (`/api/users/avatars/...`)
15
+ * passes too. The route accepts an uploaded avatar only as it is stored, so a form can send it back unchanged (an
16
+ * avatar is uploaded through `PUT /api/users/me/avatar`).
17
+ */
7
18
  export declare const avatarField: () => z.ZodNullable<z.ZodString>;
8
19
  /**
9
20
  * A phone number as it is stored: trimmed, at most 40 characters of digits, spaces and `+-().`, or `null` to clear it.
@@ -1,9 +1,14 @@
1
1
  import { z } from "zod";
2
2
  import { USER_PHONE_MAX_LENGTH, USER_PHONE_PATTERN } from "../utils/phone.js";
3
3
  import { USER_LOCALE_MAX_LENGTH, normalizeUserLocale } from "../utils/locale.js";
4
+ import { USER_NICKNAME_MAX_LENGTH, USER_PEOPLE_NUMBER_MAX_LENGTH } from "../utils/profile.js";
5
+ import { isUploadedUserAvatar } from "../utils/avatar.js";
4
6
  export const emailField = () => z.string().trim().toLowerCase().email().max(254);
5
7
  export const nameField = () => z.string().trim().min(1).max(120);
6
- export const avatarField = () => z.string().trim().max(2048).url().refine((value) => /^https?:$/.test(new URL(value).protocol), { message: "The avatar must be an http(s) URL." }).nullable();
8
+ const singleLine = /^[^\p{Cc}\p{Cf}]*$/u;
9
+ export const nicknameField = () => z.string().trim().max(USER_NICKNAME_MAX_LENGTH).regex(singleLine, { message: "Enter the nickname on one line." }).transform((value) => value || null).nullable();
10
+ export const peopleNumberField = () => z.string().trim().max(USER_PEOPLE_NUMBER_MAX_LENGTH).regex(singleLine, { message: "Enter the number on one line." }).transform((value) => value || null).nullable();
11
+ export const avatarField = () => z.string().trim().max(2048).refine((value) => isUploadedUserAvatar(value) || URL.canParse(value) && /^https?:$/.test(new URL(value).protocol), { message: "The avatar must be an http(s) URL." }).nullable();
7
12
  export const phoneField = () => z.string().trim().max(USER_PHONE_MAX_LENGTH).regex(USER_PHONE_PATTERN, { message: "Enter a phone number of digits, spaces and + - ( )." }).transform((value) => value || null).nullable();
8
13
  export const localeField = (known = []) => z.string().trim().max(USER_LOCALE_MAX_LENGTH).refine((value) => !value || normalizeUserLocale(value, known) !== null, {
9
14
  message: known.length ? `Choose one of: ${known.join(", ")}.` : 'Enter a language tag such as "da" or "en-GB".'
@@ -1,7 +1,7 @@
1
1
  import { schema } from "@nuxthub/db";
2
2
  import { defineSearchIndex } from "@frigear-nu/module-kit/server";
3
- import { withUserSearchText } from "./utils/user-search.js";
3
+ import { userSearchTextOf } from "./utils/user-search.js";
4
4
  export default defineSearchIndex({
5
5
  table: schema.users,
6
- columns: (user) => ({ searchText: withUserSearchText({ name: user.name ?? "" }).searchText ?? "" })
6
+ columns: (user) => ({ searchText: userSearchTextOf({ name: user.name ?? "", nickname: user.nickname ?? null }) })
7
7
  });
@@ -55,7 +55,8 @@ const store = {
55
55
  return user;
56
56
  },
57
57
  async update(id, values) {
58
- const [user] = await db.update(schema.users).set(withUserSearchText(withNormalizedEmail(values))).where(eq(schema.users.id, id)).returning();
58
+ const current = typeof values.name === "string" ? (await db.select({ nickname: schema.users.nickname }).from(schema.users).where(eq(schema.users.id, id)))[0] : void 0;
59
+ const [user] = await db.update(schema.users).set(withUserSearchText(withNormalizedEmail(values), current)).where(eq(schema.users.id, id)).returning();
59
60
  return user ?? null;
60
61
  },
61
62
  async remove(id) {
@@ -3,9 +3,13 @@ import type { AdminUserDto, ProfileDto } from '../../../types.js';
3
3
  type UserRowLike = {
4
4
  id: number;
5
5
  name: string;
6
+ nickname?: string | null;
6
7
  email: string;
7
8
  avatar?: string | null;
8
9
  phone?: string | null;
10
+ peopleNumber?: string | null;
11
+ photoOptOut?: boolean | number | null;
12
+ tagOptOut?: boolean | number | null;
9
13
  locale?: string | null;
10
14
  emailVerifiedAt?: Date | number | string | null;
11
15
  lastLoginAt?: Date | number | string | null;
@@ -19,7 +23,7 @@ export declare function toAdminUserDto(user: UserRowLike, options?: {
19
23
  pii?: boolean;
20
24
  }): AdminUserDto;
21
25
  /** The signed-in user's own profile, as the self-service routes return it. */
22
- export declare function toProfileDto(user: Pick<UserRowLike, 'name' | 'email' | 'avatar' | 'phone' | 'locale' | 'emailVerifiedAt'> & {
26
+ export declare function toProfileDto(user: Pick<UserRowLike, 'name' | 'nickname' | 'email' | 'avatar' | 'phone' | 'peopleNumber' | 'photoOptOut' | 'tagOptOut' | 'locale' | 'emailVerifiedAt'> & {
23
27
  id: number | string;
24
28
  }): ProfileDto;
25
29
  export {};
@@ -3,9 +3,13 @@ export function toAdminUserDto(user, options = {}) {
3
3
  return {
4
4
  id: user.id,
5
5
  name: user.name,
6
+ nickname: user.nickname ?? null,
6
7
  email: user.email,
7
8
  avatar: user.avatar ?? null,
9
+ peopleNumber: user.peopleNumber ?? null,
8
10
  ...options.pii ? { phone: user.phone ?? null } : {},
11
+ photoOptOut: !!user.photoOptOut,
12
+ tagOptOut: !!user.tagOptOut,
9
13
  emailVerifiedAt: isoDate(user.emailVerifiedAt),
10
14
  lastLoginAt: isoDate(user.lastLoginAt),
11
15
  createdAt: isoDate(user.createdAt)
@@ -15,9 +19,13 @@ export function toProfileDto(user) {
15
19
  return {
16
20
  id: Number(user.id),
17
21
  name: user.name,
22
+ nickname: user.nickname ?? null,
18
23
  email: user.email,
19
24
  avatar: user.avatar ?? null,
20
25
  phone: user.phone ?? null,
26
+ peopleNumber: user.peopleNumber ?? null,
27
+ photoOptOut: !!user.photoOptOut,
28
+ tagOptOut: !!user.tagOptOut,
21
29
  locale: user.locale ?? null,
22
30
  emailVerifiedAt: isoDate(user.emailVerifiedAt)
23
31
  };
@@ -1,6 +1,7 @@
1
1
  import type { UserRef } from '../../../types.js';
2
2
  /**
3
- * Users by id: `id`, `name`, `email`, `avatar`, `phone` and `locale` (the language to write to them in). Ids that are not whole numbers are skipped, and an unknown id
3
+ * Users by id: `id`, `name`, `email`, `avatar`, `phone`, `locale` (the language to write to them in), `nickname` and the
4
+ * media opt-outs (`photoOptOut`, `tagOptOut`). Ids that are not whole numbers are skipped, and an unknown id
4
5
  * is missing from the map. Any number of ids works: they are looked up in D1-sized chunks.
5
6
  */
6
7
  export declare function loadUserRefs(ids: Iterable<number | string | null | undefined>): Promise<Map<number, UserRef>>;
@@ -7,7 +7,10 @@ const userRefColumns = () => ({
7
7
  email: schema.users.email,
8
8
  avatar: schema.users.avatar,
9
9
  phone: schema.users.phone,
10
- locale: schema.users.locale
10
+ locale: schema.users.locale,
11
+ nickname: schema.users.nickname,
12
+ photoOptOut: schema.users.photoOptOut,
13
+ tagOptOut: schema.users.tagOptOut
11
14
  });
12
15
  const toUserRef = (row) => ({
13
16
  id: Number(row.id),
@@ -15,7 +18,10 @@ const toUserRef = (row) => ({
15
18
  email: row.email ?? null,
16
19
  avatar: row.avatar ?? null,
17
20
  phone: row.phone || null,
18
- locale: row.locale || null
21
+ locale: row.locale || null,
22
+ nickname: row.nickname || null,
23
+ photoOptOut: !!row.photoOptOut,
24
+ tagOptOut: !!row.tagOptOut
19
25
  });
20
26
  function userIdsOf(ids) {
21
27
  const unique = /* @__PURE__ */ new Set();
@@ -1,9 +1,17 @@
1
+ /** The columns `users.searchText` is built from. */
2
+ type UserSearchSource = {
3
+ name?: string | null;
4
+ nickname?: string | null;
5
+ };
6
+ /** `users.searchText` of a user: the name and the nickname, folded for search. */
7
+ export declare const userSearchTextOf: (user: UserSearchSource) => string;
1
8
  /**
2
- * `values` with the user's search column (`users.searchText`, the name folded for search) set whenever `name` is
3
- * written. Every write of a user's name goes through it, so `searchUserRefs` finds `Øyvind` for `øyvind` on sqlite.
9
+ * `values` with the user's search column (`users.searchText`: the name and nickname folded for search) set whenever
10
+ * `name` or `nickname` is written. Every write of either goes through it, so `searchUserRefs` finds `Øyvind` for
11
+ * `øyvind` on sqlite. `current` is the stored user: the column it leaves out of `values` comes from there, so renaming
12
+ * someone keeps their nickname searchable.
4
13
  */
5
- export declare const withUserSearchText: <T extends {
6
- name?: string | null;
7
- }>(values: T) => T & {
14
+ export declare const withUserSearchText: <T extends UserSearchSource>(values: T, current?: UserSearchSource | null) => T & {
8
15
  searchText?: string;
9
16
  };
17
+ export {};
@@ -1,2 +1,14 @@
1
1
  import { searchText } from "@frigear-nu/module-kit/server";
2
- export const withUserSearchText = (values) => typeof values.name === "string" ? { ...values, searchText: searchText(values.name) } : values;
2
+ export const userSearchTextOf = (user) => searchText(user.name, user.nickname);
3
+ export const withUserSearchText = (values, current) => {
4
+ const nameWritten = typeof values.name === "string";
5
+ const nicknameWritten = values.nickname !== void 0;
6
+ if (!nameWritten && !nicknameWritten) return values;
7
+ return {
8
+ ...values,
9
+ searchText: userSearchTextOf({
10
+ name: nameWritten ? values.name : current?.name,
11
+ nickname: nicknameWritten ? values.nickname : current?.nickname
12
+ })
13
+ };
14
+ };
@@ -0,0 +1,29 @@
1
+ import type { H3Event } from 'h3';
2
+ /** The largest avatar upload in bytes (`users.maxAvatarBytes`, 2 MB by default). */
3
+ export declare function usersMaxAvatarBytes(event: H3Event): number;
4
+ /** The origin uploaded avatars are served from: the configured site URL (`NUXT_PUBLIC_SITE_URL`), else the request's. */
5
+ export declare function usersAvatarOrigin(event: H3Event): string;
6
+ /**
7
+ * Reads an avatar from a multipart request (field `file`) and stores it for `userId`. Answers the absolute URL to store
8
+ * in `users.avatar` (`usersAvatarOrigin`). The image must be a PNG, JPEG or WebP by its bytes (415 `unsupported_media_type`), at most
9
+ * `users.maxAvatarBytes` (413 `file_too_large`) and at most `USERS_MAX_AVATAR_DIMENSION` pixels each way (400
10
+ * `image_too_large`). Authorize the caller before calling it.
11
+ */
12
+ export declare function storeUserAvatar(event: H3Event, userId: number): Promise<string>;
13
+ /**
14
+ * Sends a stored avatar (`GET /api/users/avatars/:userId/:file`): only an image type, `nosniff`, inline, cached for a
15
+ * year (the name never changes). 404 when there is none. Validate `file` (`USERS_AVATAR_FILE_PATTERN`) first.
16
+ */
17
+ export declare function serveUserAvatar(event: H3Event, userId: number, file: string): Promise<any>;
18
+ /**
19
+ * Deletes the file of an avatar uploaded here for `ownerId`; any other avatar (a URL from a sign-in provider, another
20
+ * user's upload, `null`) is left alone. A failure is logged, never thrown: the user's row already moved on.
21
+ */
22
+ export declare function deleteUserAvatar(avatar: string | null | undefined, ownerId: number): Promise<void>;
23
+ /** Deletes every avatar file stored for `userId` (the user was deleted). Logged, never thrown. */
24
+ export declare function deleteUserAvatarFiles(userId: number): Promise<void>;
25
+ /**
26
+ * The avatar as an absolute URL, for what leaves the app (an export, another app's API). Uploads are stored absolute;
27
+ * this only resolves one stored as a bare path. Any other avatar is returned as it is.
28
+ */
29
+ export declare function usersAvatarAbsoluteUrl(event: H3Event, avatar: string | null | undefined): string | null;