@frigear-nu/users 3.1.5 → 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.
- package/dist/module.d.mts +103 -3
- package/dist/module.json +1 -1
- package/dist/module.mjs +132 -16
- package/dist/runtime/access.js +3 -3
- package/dist/runtime/app/components/UserCreateSlideover.vue +8 -6
- package/dist/runtime/app/components/UserPicker.d.vue.ts +2 -2
- package/dist/runtime/app/components/UserPicker.vue.d.ts +2 -2
- package/dist/runtime/app/components/UsersAdminTerms.d.vue.ts +7 -0
- package/dist/runtime/app/components/UsersAdminTerms.vue +55 -0
- package/dist/runtime/app/components/UsersAdminTerms.vue.d.ts +7 -0
- package/dist/runtime/app/components/UsersTermsGate.d.vue.ts +11 -0
- package/dist/runtime/app/components/UsersTermsGate.vue +82 -0
- package/dist/runtime/app/components/UsersTermsGate.vue.d.ts +11 -0
- package/dist/runtime/app/components/UsersTermsText.d.vue.ts +7 -0
- package/dist/runtime/app/components/UsersTermsText.vue +34 -0
- package/dist/runtime/app/components/UsersTermsText.vue.d.ts +7 -0
- package/dist/runtime/app/composables/useUserActions.d.ts +6 -2
- package/dist/runtime/app/composables/useUserActions.js +32 -3
- package/dist/runtime/app/pages/admin-user.vue +3 -0
- package/dist/runtime/app/pages/admin.vue +2 -1
- package/dist/runtime/app/pages/revert-email-change.vue +2 -1
- package/dist/runtime/app/plugins/terms-gate.client.d.ts +2 -0
- package/dist/runtime/app/plugins/terms-gate.client.js +55 -0
- package/dist/runtime/app/tabs/Overview.vue +22 -12
- package/dist/runtime/app/utils/admin-user.d.ts +4 -2
- package/dist/runtime/app/utils/terms.d.ts +10 -0
- package/dist/runtime/app/utils/terms.js +7 -0
- package/dist/runtime/app/widgets/NewUsers.d.vue.ts +4 -1
- package/dist/runtime/app/widgets/NewUsers.vue +7 -4
- package/dist/runtime/app/widgets/NewUsers.vue.d.ts +4 -1
- package/dist/runtime/app/widgets/NewUsersStat.d.vue.ts +4 -1
- package/dist/runtime/app/widgets/NewUsersStat.vue +4 -1
- package/dist/runtime/app/widgets/NewUsersStat.vue.d.ts +4 -1
- package/dist/runtime/app/widgets/UsersAccountTerms.d.vue.ts +6 -0
- package/dist/runtime/app/widgets/UsersAccountTerms.vue +63 -0
- package/dist/runtime/app/widgets/UsersAccountTerms.vue.d.ts +6 -0
- package/dist/runtime/app/widgets/UsersRegisterTerms.d.vue.ts +9 -0
- package/dist/runtime/app/widgets/UsersRegisterTerms.vue +37 -0
- package/dist/runtime/app/widgets/UsersRegisterTerms.vue.d.ts +9 -0
- package/dist/runtime/db/terms-users.postgresql.d.ts +24 -0
- package/dist/runtime/db/terms-users.postgresql.js +4 -0
- package/dist/runtime/db/terms-users.sqlite.d.ts +26 -0
- package/dist/runtime/db/terms-users.sqlite.js +4 -0
- package/dist/runtime/db/terms.postgresql.d.ts +162 -0
- package/dist/runtime/db/terms.postgresql.js +21 -0
- package/dist/runtime/db/terms.sqlite.d.ts +173 -0
- package/dist/runtime/db/terms.sqlite.js +21 -0
- package/dist/runtime/i18n/lang/da.json +62 -3
- package/dist/runtime/i18n/lang/en.json +62 -3
- package/dist/runtime/server/plugins/terms-claims.d.ts +13 -0
- package/dist/runtime/server/plugins/terms-claims.js +19 -0
- package/dist/runtime/server/plugins/terms.d.ts +15 -0
- package/dist/runtime/server/plugins/terms.js +43 -0
- package/dist/runtime/server/routes/admin/user-avatar.delete.d.ts +2 -0
- package/dist/runtime/server/routes/admin/user-avatar.delete.js +11 -0
- package/dist/runtime/server/routes/admin/user-terms.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/user-terms.get.js +12 -0
- package/dist/runtime/server/routes/admin/user.delete.js +2 -0
- package/dist/runtime/server/routes/admin/user.patch.js +2 -2
- package/dist/runtime/server/routes/admin/users.get.js +1 -2
- package/dist/runtime/server/routes/avatar.get.d.ts +2 -0
- package/dist/runtime/server/routes/avatar.get.js +12 -0
- package/dist/runtime/server/routes/me/avatar.delete.d.ts +2 -0
- package/dist/runtime/server/routes/me/avatar.delete.js +13 -0
- package/dist/runtime/server/routes/me/avatar.put.d.ts +2 -0
- package/dist/runtime/server/routes/me/avatar.put.js +20 -0
- package/dist/runtime/server/routes/me/profile.patch.js +7 -2
- package/dist/runtime/server/routes/me/terms.get.d.ts +2 -0
- package/dist/runtime/server/routes/me/terms.get.js +4 -0
- package/dist/runtime/server/routes/me/terms.post.d.ts +2 -0
- package/dist/runtime/server/routes/me/terms.post.js +18 -0
- package/dist/runtime/server/schemas.d.ts +5 -1
- package/dist/runtime/server/schemas.js +2 -1
- package/dist/runtime/server/utils/dto.d.ts +1 -1
- package/dist/runtime/server/utils/dto.js +2 -1
- package/dist/runtime/server/utils/users-avatar.d.ts +29 -0
- package/dist/runtime/server/utils/users-avatar.js +69 -0
- package/dist/runtime/server/utils/users-terms.d.ts +35 -0
- package/dist/runtime/server/utils/users-terms.js +90 -0
- package/dist/runtime/utils/api.d.ts +21 -2
- package/dist/runtime/utils/api.js +20 -1
- package/dist/runtime/utils/avatar.d.ts +25 -0
- package/dist/runtime/utils/avatar.js +23 -0
- package/dist/runtime/utils/terms-claim.d.ts +27 -0
- package/dist/runtime/utils/terms-claim.js +15 -0
- package/dist/types.d.mts +1 -1
- package/package.json +18 -13
|
@@ -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,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,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
|
});
|
|
@@ -21,10 +21,10 @@ export default defineEventHandler(async (event) => {
|
|
|
21
21
|
const emailChanged = !!input.email && !sameUserEmail(input.email, target.email);
|
|
22
22
|
if (emailChanged || input.emailVerified !== void 0) await authorize(event, USERS_MANAGE_PERMISSION, target);
|
|
23
23
|
if (emailChanged) await assertEmailAvailable(input.email, { exceptUserId: target.id });
|
|
24
|
-
if (input.phone !== void 0
|
|
24
|
+
if (input.phone !== void 0) await authorize(event, usersAccess.permissions.pii, target);
|
|
25
25
|
const phoneChanged = input.phone !== void 0 && input.phone !== (target.phone ?? null);
|
|
26
26
|
const peopleNumberChanged = input.peopleNumber !== void 0 && input.peopleNumber !== (target.peopleNumber ?? null);
|
|
27
|
-
const pii = input.phone !== void 0 ||
|
|
27
|
+
const pii = input.phone !== void 0 || await allows(event, usersAccess.permissions.pii, target);
|
|
28
28
|
const nicknameChanged = input.nickname !== void 0 && input.nickname !== (target.nickname ?? null);
|
|
29
29
|
const changes = {
|
|
30
30
|
...input.name || nicknameChanged ? withUserSearchText({
|
|
@@ -2,7 +2,6 @@ import { db, schema } from "@nuxthub/db";
|
|
|
2
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 { usersAccess } from "../../../access.js";
|
|
6
5
|
import { USER_MEDIA_OPT_OUTS, normalizeUserPeopleNumber } from "../../../utils/profile.js";
|
|
7
6
|
const querySchema = pageQuery({
|
|
8
7
|
sort: ["id", "name", "email", "role", "createdAt", "lastLoginAt"],
|
|
@@ -21,7 +20,7 @@ export default defineEventHandler(async (event) => {
|
|
|
21
20
|
const conditions = [];
|
|
22
21
|
if (query.q) {
|
|
23
22
|
const peopleNumber = normalizeUserPeopleNumber(query.q);
|
|
24
|
-
const byPeopleNumber = peopleNumber
|
|
23
|
+
const byPeopleNumber = peopleNumber ? eq(schema.users.peopleNumber, peopleNumber) : void 0;
|
|
25
24
|
conditions.push(or(searchContains(schema.users.searchText, query.q), likeContains(schema.users.email, query.q), byPeopleNumber));
|
|
26
25
|
}
|
|
27
26
|
if (query.mediaOptOut) conditions.push(eq(query.mediaOptOut === "photo" ? schema.users.photoOptOut : schema.users.tagOptOut, true));
|
|
@@ -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,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,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,7 +1,8 @@
|
|
|
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";
|
|
4
|
+
import { notFound, validationError } from "@frigear-nu/module-kit/server";
|
|
5
|
+
import { isUploadedUserAvatar } from "../../../utils/avatar.js";
|
|
5
6
|
import { avatarField, localeField, nameField, nicknameField, peopleNumberField, phoneField } from "../../schemas.js";
|
|
6
7
|
const bodySchema = (locales) => z.object({
|
|
7
8
|
name: nameField().optional(),
|
|
@@ -22,7 +23,10 @@ const bodySchema = (locales) => z.object({
|
|
|
22
23
|
export default defineEventHandler(async (event) => {
|
|
23
24
|
const { user, kind } = await authorize(event, "profile:write");
|
|
24
25
|
const { name, nickname, avatar, phone, peopleNumber, photoOptOut, tagOptOut, locale } = await readValidatedBody(event, bodySchema(usersLocales()).parse);
|
|
25
|
-
const current = name !== void 0 || nickname !== void 0 ? (await db.select({ name: schema.users.name, nickname: schema.users.nickname }).from(schema.users).where(eq(schema.users.id, user.id)))[0] : void 0;
|
|
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
|
+
}
|
|
26
30
|
const [updated] = await db.update(schema.users).set({
|
|
27
31
|
...withUserSearchText({
|
|
28
32
|
...name !== void 0 ? { name } : {},
|
|
@@ -37,6 +41,7 @@ export default defineEventHandler(async (event) => {
|
|
|
37
41
|
updatedAt: /* @__PURE__ */ new Date()
|
|
38
42
|
}).where(eq(schema.users.id, user.id)).returning();
|
|
39
43
|
if (!updated) throw notFound("User not found.");
|
|
44
|
+
if (avatar !== void 0 && current?.avatar !== avatar) await deleteUserAvatar(current?.avatar, user.id);
|
|
40
45
|
if (kind === "session") await setUserSession(event, { user: mapUserToSession(updated) });
|
|
41
46
|
return toProfileDto(updated);
|
|
42
47
|
});
|
|
@@ -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
|
+
});
|
|
@@ -10,7 +10,11 @@ export declare const nicknameField: () => z.ZodNullable<z.ZodPipe<z.ZodString, z
|
|
|
10
10
|
* empty string clears it too. Not unique: two users may type the same number.
|
|
11
11
|
*/
|
|
12
12
|
export declare const peopleNumberField: () => z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<string | null, string>>>;
|
|
13
|
-
/**
|
|
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
|
+
*/
|
|
14
18
|
export declare const avatarField: () => z.ZodNullable<z.ZodString>;
|
|
15
19
|
/**
|
|
16
20
|
* A phone number as it is stored: trimmed, at most 40 characters of digits, spaces and `+-().`, or `null` to clear it.
|
|
@@ -2,12 +2,13 @@ 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
4
|
import { USER_NICKNAME_MAX_LENGTH, USER_PEOPLE_NUMBER_MAX_LENGTH } from "../utils/profile.js";
|
|
5
|
+
import { isUploadedUserAvatar } from "../utils/avatar.js";
|
|
5
6
|
export const emailField = () => z.string().trim().toLowerCase().email().max(254);
|
|
6
7
|
export const nameField = () => z.string().trim().min(1).max(120);
|
|
7
8
|
const singleLine = /^[^\p{Cc}\p{Cf}]*$/u;
|
|
8
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();
|
|
9
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();
|
|
10
|
-
export const avatarField = () => z.string().trim().max(2048).
|
|
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();
|
|
11
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();
|
|
12
13
|
export const localeField = (known = []) => z.string().trim().max(USER_LOCALE_MAX_LENGTH).refine((value) => !value || normalizeUserLocale(value, known) !== null, {
|
|
13
14
|
message: known.length ? `Choose one of: ${known.join(", ")}.` : 'Enter a language tag such as "da" or "en-GB".'
|
|
@@ -17,7 +17,7 @@ type UserRowLike = {
|
|
|
17
17
|
};
|
|
18
18
|
/**
|
|
19
19
|
* A stored user as the users admin returns it: an allowlist (never the password hash or other modules' columns). `pii`
|
|
20
|
-
* (the caller holds `users:pii`) adds the phone number
|
|
20
|
+
* (the caller holds `users:pii`) adds the phone number.
|
|
21
21
|
*/
|
|
22
22
|
export declare function toAdminUserDto(user: UserRowLike, options?: {
|
|
23
23
|
pii?: boolean;
|
|
@@ -6,7 +6,8 @@ export function toAdminUserDto(user, options = {}) {
|
|
|
6
6
|
nickname: user.nickname ?? null,
|
|
7
7
|
email: user.email,
|
|
8
8
|
avatar: user.avatar ?? null,
|
|
9
|
-
|
|
9
|
+
peopleNumber: user.peopleNumber ?? null,
|
|
10
|
+
...options.pii ? { phone: user.phone ?? null } : {},
|
|
10
11
|
photoOptOut: !!user.photoOptOut,
|
|
11
12
|
tagOptOut: !!user.tagOptOut,
|
|
12
13
|
emailVerifiedAt: isoDate(user.emailVerifiedAt),
|
|
@@ -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;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { blob } from "#users/avatar-blob";
|
|
2
|
+
import { apiError, badRequest, notConfigured, notFound, validationError } from "@frigear-nu/module-kit/server";
|
|
3
|
+
import { IMAGE_EXTENSIONS, IMAGE_TYPES, imageSize, sniffImageType } from "@frigear-nu/module-kit/image";
|
|
4
|
+
import { USERS_MAX_AVATAR_BYTES, USERS_MAX_AVATAR_DIMENSION, absoluteUserAvatarUrl, parseUploadedUserAvatar } from "../../utils/avatar.js";
|
|
5
|
+
import { usersApi } from "../../utils/api.js";
|
|
6
|
+
const MULTIPART_ALLOWANCE = 16 * 1024;
|
|
7
|
+
const blobPathname = (userId, file) => `avatars/${userId}/${file}`;
|
|
8
|
+
const contentTypeOf = (file) => IMAGE_TYPES.find((type) => file.endsWith(`.${IMAGE_EXTENSIONS[type]}`));
|
|
9
|
+
export function usersMaxAvatarBytes(event) {
|
|
10
|
+
return Number(useRuntimeConfig(event).public.users?.maxAvatarBytes) || USERS_MAX_AVATAR_BYTES;
|
|
11
|
+
}
|
|
12
|
+
export function usersAvatarOrigin(event) {
|
|
13
|
+
return configuredAuthSiteOrigin(event) ?? getRequestURL(event).origin;
|
|
14
|
+
}
|
|
15
|
+
export async function storeUserAvatar(event, userId) {
|
|
16
|
+
if (!blob) throw notConfigured("Avatar uploads are not enabled.");
|
|
17
|
+
if (!(getRequestHeader(event, "content-type") ?? "").includes("multipart/form-data")) throw badRequest("Send the image as multipart/form-data.");
|
|
18
|
+
const maxBytes = usersMaxAvatarBytes(event);
|
|
19
|
+
const tooLarge = () => apiError(413, "file_too_large", `The image is larger than ${Math.round(maxBytes / 1024 / 1024 * 10) / 10} MB.`, { maxBytes });
|
|
20
|
+
const length = Number(getRequestHeader(event, "content-length"));
|
|
21
|
+
if (!Number.isFinite(length) || length <= 0 || length > maxBytes + MULTIPART_ALLOWANCE) throw tooLarge();
|
|
22
|
+
const parts = await readMultipartFormData(event) ?? [];
|
|
23
|
+
const file = parts.find((part) => part.name === "file" && part.filename);
|
|
24
|
+
if (!file) throw validationError([{ path: ["file"], message: "Choose an image." }], "Missing file");
|
|
25
|
+
if (file.data.byteLength > maxBytes) throw tooLarge();
|
|
26
|
+
const bytes = new Uint8Array(file.data.buffer, file.data.byteOffset, file.data.byteLength);
|
|
27
|
+
const type = sniffImageType(bytes);
|
|
28
|
+
if (!type) throw apiError(415, "unsupported_media_type", "The image must be a PNG, JPEG or WebP.");
|
|
29
|
+
const size = imageSize(bytes);
|
|
30
|
+
if (!size || !size.width || !size.height) throw apiError(400, "unreadable_image", "The size of the image could not be read.");
|
|
31
|
+
if (size.width > USERS_MAX_AVATAR_DIMENSION || size.height > USERS_MAX_AVATAR_DIMENSION) {
|
|
32
|
+
throw apiError(400, "image_too_large", `The image may be at most ${USERS_MAX_AVATAR_DIMENSION} pixels wide and high.`);
|
|
33
|
+
}
|
|
34
|
+
const saved = await blob.put(`avatar.${IMAGE_EXTENSIONS[type]}`, file.data, { contentType: type, prefix: `avatars/${userId}`, addRandomSuffix: true });
|
|
35
|
+
const name = saved.pathname.split("/").pop();
|
|
36
|
+
return new URL(usersApi.avatar(userId, name), usersAvatarOrigin(event)).href;
|
|
37
|
+
}
|
|
38
|
+
export async function serveUserAvatar(event, userId, file) {
|
|
39
|
+
const contentType = contentTypeOf(file);
|
|
40
|
+
if (!blob || !contentType) throw notFound("There is no image.");
|
|
41
|
+
const stored = await blob.get(blobPathname(userId, file));
|
|
42
|
+
if (!stored) throw notFound("There is no image.");
|
|
43
|
+
setResponseHeader(event, "content-type", contentType);
|
|
44
|
+
setResponseHeader(event, "content-disposition", "inline");
|
|
45
|
+
setResponseHeader(event, "x-content-type-options", "nosniff");
|
|
46
|
+
setResponseHeader(event, "cache-control", "public, max-age=31536000, immutable");
|
|
47
|
+
return stored;
|
|
48
|
+
}
|
|
49
|
+
export async function deleteUserAvatar(avatar, ownerId) {
|
|
50
|
+
const uploaded = parseUploadedUserAvatar(avatar);
|
|
51
|
+
if (!blob || !uploaded || uploaded.userId !== Number(ownerId)) return;
|
|
52
|
+
await blob.del(blobPathname(uploaded.userId, uploaded.file)).catch((error) => console.error("[users] an avatar image could not be deleted", error));
|
|
53
|
+
}
|
|
54
|
+
export async function deleteUserAvatarFiles(userId) {
|
|
55
|
+
if (!blob) return;
|
|
56
|
+
try {
|
|
57
|
+
let cursor;
|
|
58
|
+
do {
|
|
59
|
+
const page = await blob.list({ prefix: `avatars/${userId}/`, cursor });
|
|
60
|
+
if (page.blobs.length) await blob.del(page.blobs.map((stored) => stored.pathname));
|
|
61
|
+
cursor = page.hasMore ? page.cursor : void 0;
|
|
62
|
+
} while (cursor);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
console.error(`[users] the avatar images of user ${userId} could not be deleted`, error);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export function usersAvatarAbsoluteUrl(event, avatar) {
|
|
68
|
+
return absoluteUserAvatarUrl(avatar, usersAvatarOrigin(event));
|
|
69
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { H3Event } from 'h3';
|
|
2
|
+
import type { userTermsAcceptances as TermsTable } from '../../db/terms.sqlite.js';
|
|
3
|
+
import type { UserTermsAcceptanceDto, UserTermsStatusDto, UsersTermsAcceptedContext, UsersTermsRuntimeConfig, UsersTermsSource } from '../../../types.js';
|
|
4
|
+
/** The User-Agent is stored cut to this many characters. */
|
|
5
|
+
export declare const USERS_TERMS_USER_AGENT_MAX_LENGTH = 512;
|
|
6
|
+
/** The terms config (`users.terms`), or `null` when the host does not track terms. */
|
|
7
|
+
export declare function usersTermsConfig(event?: H3Event): UsersTermsRuntimeConfig | null;
|
|
8
|
+
/** A locale of the terms files: `locale` when it has a file, else the first file's (the text the site falls back to). */
|
|
9
|
+
export declare function usersTermsLocale(config: UsersTermsRuntimeConfig, locale: string | null | undefined): string;
|
|
10
|
+
/** A keyed hash (HMAC-SHA-256, hex) of the request's IP address, or `null` without an address or a secret. */
|
|
11
|
+
export declare function usersIpHash(event: H3Event): Promise<string | null>;
|
|
12
|
+
/** The signed-in user's terms: the current version, their latest acceptance and whether it is the current one. */
|
|
13
|
+
export declare function usersTermsStatus(event: H3Event | undefined, userId: number): Promise<UserTermsStatusDto>;
|
|
14
|
+
/**
|
|
15
|
+
* Records that `userId` accepted the current terms in `locale` (one of the files, else the fallback): a history row with
|
|
16
|
+
* the file's hash, the time, a keyed hash of the IP address and the User-Agent (without `event`: none), then the latest
|
|
17
|
+
* on the user. Fires
|
|
18
|
+
* `users:terms:accepted`. The server sets everything but the locale.
|
|
19
|
+
*/
|
|
20
|
+
export declare function usersRecordTermsAcceptance(event: H3Event | undefined, userId: number, input: {
|
|
21
|
+
locale?: string | null;
|
|
22
|
+
source: UsersTermsSource;
|
|
23
|
+
acceptedAt?: number;
|
|
24
|
+
}): Promise<UsersTermsAcceptedContext>;
|
|
25
|
+
/**
|
|
26
|
+
* 403 `terms_outdated` unless `userId` accepted the current terms. For routes that must not go on without them (a
|
|
27
|
+
* purchase). Does nothing when the host does not track terms.
|
|
28
|
+
*/
|
|
29
|
+
export declare function usersRequireAcceptedTerms(event: H3Event, userId: number): Promise<void>;
|
|
30
|
+
/** A user's acceptances, newest first (the admin history). */
|
|
31
|
+
export declare function usersTermsHistory(userId: number): Promise<UserTermsAcceptanceDto[]>;
|
|
32
|
+
/** Removes a deleted user's history (`users:deleted`): the table has no foreign key. */
|
|
33
|
+
export declare function usersDeleteTermsHistory(userId: number): Promise<void>;
|
|
34
|
+
/** One history row as the admin route returns it. */
|
|
35
|
+
export declare function toUserTermsAcceptanceDto(row: typeof TermsTable.$inferSelect): UserTermsAcceptanceDto;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { db, schema } from "@nuxthub/db";
|
|
2
|
+
import { desc, eq } from "drizzle-orm";
|
|
3
|
+
import { apiError, isoDate, notConfigured } from "@frigear-nu/module-kit/server";
|
|
4
|
+
import { resolveSecret } from "@frigear-nu/module-kit/secret";
|
|
5
|
+
import { bytesToHex } from "@frigear-nu/module-kit/crypto";
|
|
6
|
+
const termsSchema = () => schema;
|
|
7
|
+
export const USERS_TERMS_USER_AGENT_MAX_LENGTH = 512;
|
|
8
|
+
export function usersTermsConfig(event) {
|
|
9
|
+
return useRuntimeConfig(event).users?.terms ?? null;
|
|
10
|
+
}
|
|
11
|
+
function publicTerms(config) {
|
|
12
|
+
return { version: config.version, url: config.url, ...config.privacyUrl ? { privacyUrl: config.privacyUrl } : {} };
|
|
13
|
+
}
|
|
14
|
+
export function usersTermsLocale(config, locale) {
|
|
15
|
+
if (locale && Object.hasOwn(config.hashes, locale)) return locale;
|
|
16
|
+
const base = locale?.split("-")[0];
|
|
17
|
+
if (base && Object.hasOwn(config.hashes, base)) return base;
|
|
18
|
+
return Object.keys(config.hashes)[0];
|
|
19
|
+
}
|
|
20
|
+
let ipKey;
|
|
21
|
+
export async function usersIpHash(event) {
|
|
22
|
+
const ip = getRequestIP(event, { xForwardedFor: true });
|
|
23
|
+
if (!ip) return null;
|
|
24
|
+
const secret = await resolveSecret("@frigear-nu/users:terms-ip");
|
|
25
|
+
if (!secret) return null;
|
|
26
|
+
if (ipKey?.secret !== secret) {
|
|
27
|
+
ipKey = { secret, key: crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]) };
|
|
28
|
+
}
|
|
29
|
+
const signature = await crypto.subtle.sign("HMAC", await ipKey.key, new TextEncoder().encode(`users:terms:ip:${ip}`));
|
|
30
|
+
return bytesToHex(signature);
|
|
31
|
+
}
|
|
32
|
+
export async function usersTermsStatus(event, userId) {
|
|
33
|
+
const config = usersTermsConfig(event);
|
|
34
|
+
if (!config) throw notConfigured("Terms are not tracked here (`users.terms`).");
|
|
35
|
+
const { users } = termsSchema();
|
|
36
|
+
const [row] = await db.select({ acceptedAt: users.acceptedTermsAt, version: users.acceptedTermsVersion }).from(users).where(eq(users.id, userId)).limit(1);
|
|
37
|
+
const accepted = row?.version && row.acceptedAt ? { version: row.version, acceptedAt: isoDate(row.acceptedAt) } : null;
|
|
38
|
+
return { current: publicTerms(config), accepted, upToDate: accepted?.version === config.version };
|
|
39
|
+
}
|
|
40
|
+
export async function usersRecordTermsAcceptance(event, userId, input) {
|
|
41
|
+
const config = usersTermsConfig(event);
|
|
42
|
+
if (!config) throw notConfigured("Terms are not tracked here (`users.terms`).");
|
|
43
|
+
const locale = usersTermsLocale(config, input.locale);
|
|
44
|
+
const acceptedAt = input.acceptedAt ?? Date.now();
|
|
45
|
+
const userAgent = event ? getRequestHeader(event, "user-agent")?.slice(0, USERS_TERMS_USER_AGENT_MAX_LENGTH) || null : null;
|
|
46
|
+
const ipHash = event ? await usersIpHash(event) : null;
|
|
47
|
+
const { users, userTermsAcceptances } = termsSchema();
|
|
48
|
+
await db.insert(userTermsAcceptances).values({
|
|
49
|
+
userId,
|
|
50
|
+
version: config.version,
|
|
51
|
+
locale,
|
|
52
|
+
contentHash: config.hashes[locale],
|
|
53
|
+
acceptedAt,
|
|
54
|
+
source: input.source,
|
|
55
|
+
ipHash,
|
|
56
|
+
userAgent
|
|
57
|
+
});
|
|
58
|
+
await db.update(users).set({ acceptedTermsAt: acceptedAt, acceptedTermsVersion: config.version }).where(eq(users.id, userId));
|
|
59
|
+
const context = { userId, version: config.version, acceptedAt, source: input.source };
|
|
60
|
+
await useNitroApp().hooks.callHook("users:terms:accepted", context);
|
|
61
|
+
return context;
|
|
62
|
+
}
|
|
63
|
+
export async function usersRequireAcceptedTerms(event, userId) {
|
|
64
|
+
if (!usersTermsConfig(event)) return;
|
|
65
|
+
const status = await usersTermsStatus(event, userId);
|
|
66
|
+
if (!status.upToDate) {
|
|
67
|
+
throw apiError(403, "terms_outdated", "Accept the current terms first.", { version: status.current.version, url: status.current.url });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export async function usersTermsHistory(userId) {
|
|
71
|
+
const { userTermsAcceptances: table } = termsSchema();
|
|
72
|
+
const rows = await db.select().from(table).where(eq(table.userId, userId)).orderBy(desc(table.acceptedAt), desc(table.id));
|
|
73
|
+
return rows.map(toUserTermsAcceptanceDto);
|
|
74
|
+
}
|
|
75
|
+
export async function usersDeleteTermsHistory(userId) {
|
|
76
|
+
const { userTermsAcceptances: table } = termsSchema();
|
|
77
|
+
await db.delete(table).where(eq(table.userId, userId));
|
|
78
|
+
}
|
|
79
|
+
export function toUserTermsAcceptanceDto(row) {
|
|
80
|
+
return {
|
|
81
|
+
id: row.id,
|
|
82
|
+
version: row.version,
|
|
83
|
+
locale: row.locale,
|
|
84
|
+
contentHash: row.contentHash,
|
|
85
|
+
acceptedAt: isoDate(row.acceptedAt),
|
|
86
|
+
source: row.source,
|
|
87
|
+
ipHash: row.ipHash ?? null,
|
|
88
|
+
userAgent: row.userAgent ?? null
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import type { AdminUserDto, ProfileDto, UserPickerCreateInitial, UserPickerOption } from '../../types.js';
|
|
2
|
-
export type { AdminUserDto, ProfileDto, UserPickerCreateInitial, UserPickerOption };
|
|
1
|
+
import type { AdminUserDto, ProfileDto, UserPickerCreateInitial, UserPickerOption, UserTermsAcceptanceDto, UserTermsStatusDto, UsersPublicTerms } from '../../types.js';
|
|
2
|
+
export type { AdminUserDto, ProfileDto, UserPickerCreateInitial, UserPickerOption, UserTermsAcceptanceDto, UserTermsStatusDto, UsersPublicTerms };
|
|
3
3
|
export { USER_PHONE_MAX_LENGTH, USER_PHONE_PATTERN } from './phone.js';
|
|
4
4
|
export { USER_MEDIA_OPT_OUTS, USER_NICKNAME_MAX_LENGTH, USER_PEOPLE_NUMBER_MAX_LENGTH, normalizeUserPeopleNumber, userDisplayName } from './profile.js';
|
|
5
5
|
export type { UserMediaOptOut } from './profile.js';
|
|
6
|
+
export { USERS_AVATAR_FILE_PATTERN, USERS_AVATAR_TYPES, USERS_MAX_AVATAR_BYTES, USERS_MAX_AVATAR_DIMENSION, absoluteUserAvatarUrl, isUploadedUserAvatar, parseUploadedUserAvatar } from './avatar.js';
|
|
6
7
|
/** The users API: self-service under `/api/users`, staff under `/api/admin/users`. */
|
|
7
8
|
export declare const usersApi: {
|
|
8
9
|
readonly me: {
|
|
@@ -17,7 +18,21 @@ export declare const usersApi: {
|
|
|
17
18
|
readonly email: "/api/users/me/email";
|
|
18
19
|
/** `PUT { currentPassword, newPassword, confirmNewPassword }`: changes the caller's password. Session only. */
|
|
19
20
|
readonly password: "/api/users/me/password";
|
|
21
|
+
/**
|
|
22
|
+
* `GET`: the caller's terms (`UserTermsStatusDto`). `POST { version, locale? }`: accepts the current terms, answers
|
|
23
|
+
* the status (409 `outdated_version` for another version). Session only, with `users.terms`.
|
|
24
|
+
*/
|
|
25
|
+
readonly terms: "/api/users/me/terms";
|
|
26
|
+
/**
|
|
27
|
+
* `PUT` multipart/form-data with the image in field `file` (PNG, JPEG or WebP, at most `users.maxAvatarBytes`):
|
|
28
|
+
* stores it as the caller's avatar and answers the profile DTO, whose `avatar` is the image's absolute URL
|
|
29
|
+
* (`usersApi.avatar`). 413 `file_too_large`, 415 `unsupported_media_type`, 400 without a file. `DELETE` removes the
|
|
30
|
+
* caller's avatar (204). Both `profile:write`; only with `users.avatarUpload`.
|
|
31
|
+
*/
|
|
32
|
+
readonly avatar: "/api/users/me/avatar";
|
|
20
33
|
};
|
|
34
|
+
/** `GET`: an uploaded avatar (public, cached for good: every upload gets a new file name). Only with `users.avatarUpload`. */
|
|
35
|
+
readonly avatar: (userId: number | string, file: string) => string;
|
|
21
36
|
/** `GET ?code=`: read-only preview of an email change link (`verifyEmailChange`). */
|
|
22
37
|
readonly emailChange: "/api/users/email-change";
|
|
23
38
|
/** `POST { code }`: confirms an email change; the signed-in owner only. */
|
|
@@ -31,6 +46,10 @@ export declare const usersApi: {
|
|
|
31
46
|
readonly user: (id: number | string) => string;
|
|
32
47
|
/** `POST`: emails the sign-in link (or the verification email) again. */
|
|
33
48
|
readonly resend: (id: number | string) => string;
|
|
49
|
+
/** `GET`: the user's terms acceptances, newest first (`UserTermsAcceptanceDto[]`, `users:pii`, with `users.terms`). */
|
|
50
|
+
readonly terms: (id: number | string) => string;
|
|
51
|
+
/** `DELETE`: removes the user's avatar, uploaded or from a sign-in provider (204). `users:update`. */
|
|
52
|
+
readonly avatar: (id: number | string) => string;
|
|
34
53
|
/** `GET`: the newest sign-ups of the last 30 days (dashboard). */
|
|
35
54
|
readonly new: "/api/admin/users/new";
|
|
36
55
|
/** `GET`: `{ total, newUsers, days }` (dashboard). */
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { USER_PHONE_MAX_LENGTH, USER_PHONE_PATTERN } from "./phone.js";
|
|
2
2
|
export { USER_MEDIA_OPT_OUTS, USER_NICKNAME_MAX_LENGTH, USER_PEOPLE_NUMBER_MAX_LENGTH, normalizeUserPeopleNumber, userDisplayName } from "./profile.js";
|
|
3
|
+
export { USERS_AVATAR_FILE_PATTERN, USERS_AVATAR_TYPES, USERS_MAX_AVATAR_BYTES, USERS_MAX_AVATAR_DIMENSION, absoluteUserAvatarUrl, isUploadedUserAvatar, parseUploadedUserAvatar } from "./avatar.js";
|
|
3
4
|
const base = "/api/users";
|
|
4
5
|
const adminBase = "/api/admin/users";
|
|
5
6
|
export const usersApi = {
|
|
@@ -14,8 +15,22 @@ export const usersApi = {
|
|
|
14
15
|
/** `PUT { email }`: changes the caller's email (or emails a confirmation link with `verifyEmailChange`). Session only. */
|
|
15
16
|
email: `${base}/me/email`,
|
|
16
17
|
/** `PUT { currentPassword, newPassword, confirmNewPassword }`: changes the caller's password. Session only. */
|
|
17
|
-
password: `${base}/me/password
|
|
18
|
+
password: `${base}/me/password`,
|
|
19
|
+
/**
|
|
20
|
+
* `GET`: the caller's terms (`UserTermsStatusDto`). `POST { version, locale? }`: accepts the current terms, answers
|
|
21
|
+
* the status (409 `outdated_version` for another version). Session only, with `users.terms`.
|
|
22
|
+
*/
|
|
23
|
+
terms: `${base}/me/terms`,
|
|
24
|
+
/**
|
|
25
|
+
* `PUT` multipart/form-data with the image in field `file` (PNG, JPEG or WebP, at most `users.maxAvatarBytes`):
|
|
26
|
+
* stores it as the caller's avatar and answers the profile DTO, whose `avatar` is the image's absolute URL
|
|
27
|
+
* (`usersApi.avatar`). 413 `file_too_large`, 415 `unsupported_media_type`, 400 without a file. `DELETE` removes the
|
|
28
|
+
* caller's avatar (204). Both `profile:write`; only with `users.avatarUpload`.
|
|
29
|
+
*/
|
|
30
|
+
avatar: `${base}/me/avatar`
|
|
18
31
|
},
|
|
32
|
+
/** `GET`: an uploaded avatar (public, cached for good: every upload gets a new file name). Only with `users.avatarUpload`. */
|
|
33
|
+
avatar: (userId, file) => `${base}/avatars/${encodeURIComponent(String(userId))}/${encodeURIComponent(file)}`,
|
|
19
34
|
/** `GET ?code=`: read-only preview of an email change link (`verifyEmailChange`). */
|
|
20
35
|
emailChange: `${base}/email-change`,
|
|
21
36
|
/** `POST { code }`: confirms an email change; the signed-in owner only. */
|
|
@@ -29,6 +44,10 @@ export const usersApi = {
|
|
|
29
44
|
user: (id) => `${adminBase}/${encodeURIComponent(String(id))}`,
|
|
30
45
|
/** `POST`: emails the sign-in link (or the verification email) again. */
|
|
31
46
|
resend: (id) => `${adminBase}/${encodeURIComponent(String(id))}/resend`,
|
|
47
|
+
/** `GET`: the user's terms acceptances, newest first (`UserTermsAcceptanceDto[]`, `users:pii`, with `users.terms`). */
|
|
48
|
+
terms: (id) => `${adminBase}/${encodeURIComponent(String(id))}/terms`,
|
|
49
|
+
/** `DELETE`: removes the user's avatar, uploaded or from a sign-in provider (204). `users:update`. */
|
|
50
|
+
avatar: (id) => `${adminBase}/${encodeURIComponent(String(id))}/avatar`,
|
|
32
51
|
/** `GET`: the newest sign-ups of the last 30 days (dashboard). */
|
|
33
52
|
new: `${adminBase}/new`,
|
|
34
53
|
/** `GET`: `{ total, newUsers, days }` (dashboard). */
|