@frigear-nu/users 1.1.2 → 1.1.4
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 +26 -4
- package/dist/module.json +1 -1
- package/dist/module.mjs +35 -29
- package/dist/runtime/app/components/UserCreateSlideover.vue +2 -1
- package/dist/runtime/app/composables/useUserActions.d.ts +1 -1
- package/dist/runtime/app/composables/useUserActions.js +6 -3
- package/dist/runtime/app/pages/admin-user.vue +14 -5
- package/dist/runtime/app/pages/admin.vue +85 -75
- package/dist/runtime/app/pages/revert-email-change.d.vue.ts +3 -0
- package/dist/runtime/app/pages/revert-email-change.vue +104 -0
- package/dist/runtime/app/pages/revert-email-change.vue.d.ts +3 -0
- package/dist/runtime/app/pages/verify-email-change.d.vue.ts +3 -0
- package/dist/runtime/app/pages/verify-email-change.vue +156 -0
- package/dist/runtime/app/pages/verify-email-change.vue.d.ts +3 -0
- package/dist/runtime/app/tabs/Overview.vue +51 -53
- package/dist/runtime/app/utils/admin-user.d.ts +4 -17
- package/dist/runtime/app/widgets/NewUsers.vue +2 -1
- package/dist/runtime/app/widgets/NewUsersStat.vue +2 -1
- package/dist/runtime/i18n/lang/da.json +46 -3
- package/dist/runtime/i18n/lang/en.json +46 -3
- package/dist/runtime/server/email-change.d.ts +6 -0
- package/dist/runtime/server/email-change.js +10 -0
- package/dist/runtime/server/routes/admin/new.get.js +2 -8
- package/dist/runtime/server/routes/admin/user-resend.post.js +3 -13
- package/dist/runtime/server/routes/admin/user.delete.js +6 -15
- package/dist/runtime/server/routes/admin/user.get.js +6 -16
- package/dist/runtime/server/routes/admin/user.patch.js +13 -23
- package/dist/runtime/server/routes/admin/users.get.js +24 -28
- package/dist/runtime/server/routes/admin/users.post.js +12 -13
- package/dist/runtime/server/routes/me/email-change-confirm.post.js +44 -0
- package/dist/runtime/server/routes/me/email-change-revert.get.js +13 -0
- package/dist/runtime/server/routes/me/email-change-revert.post.js +28 -0
- package/dist/runtime/server/routes/me/email-change.get.js +22 -0
- package/dist/runtime/server/routes/me/{change-email.post.js → email.put.js} +9 -10
- package/dist/runtime/server/routes/me/password.put.d.ts +2 -0
- package/dist/runtime/server/routes/me/{change-password.post.js → password.put.js} +4 -5
- package/dist/runtime/server/routes/me/profile.patch.d.ts +2 -0
- package/dist/runtime/server/routes/me/profile.patch.js +22 -0
- package/dist/runtime/server/schemas.d.ts +7 -0
- package/dist/runtime/server/schemas.js +4 -0
- package/dist/runtime/server/user-store.js +5 -3
- package/dist/runtime/server/utils/admin.d.ts +15 -3
- package/dist/runtime/server/utils/admin.js +16 -15
- package/dist/runtime/server/utils/dto.d.ts +19 -0
- package/dist/runtime/server/utils/dto.js +22 -0
- package/dist/runtime/server/utils/email.d.ts +18 -0
- package/dist/runtime/server/utils/email.js +18 -0
- package/dist/runtime/utils/api.d.ts +33 -0
- package/dist/runtime/utils/api.js +32 -0
- package/dist/runtime/utils/index.d.ts +3 -1
- package/dist/runtime/utils/index.js +1 -0
- package/dist/types.d.mts +1 -1
- package/package.json +18 -13
- package/dist/runtime/server/routes/me/profile.post.js +0 -17
- package/dist/runtime/server/routes/me/revert-email-change.get.js +0 -24
- package/dist/runtime/server/routes/me/verify-email-change.get.js +0 -37
- /package/dist/runtime/server/routes/me/{change-email.post.d.ts → email-change-confirm.post.d.ts} +0 -0
- /package/dist/runtime/server/routes/me/{change-password.post.d.ts → email-change-revert.get.d.ts} +0 -0
- /package/dist/runtime/server/routes/me/{profile.post.d.ts → email-change-revert.post.d.ts} +0 -0
- /package/dist/runtime/server/routes/me/{revert-email-change.get.d.ts → email-change.get.d.ts} +0 -0
- /package/dist/runtime/server/routes/me/{verify-email-change.get.d.ts → email.put.d.ts} +0 -0
|
@@ -1,28 +1,18 @@
|
|
|
1
1
|
import { db, schema } from "@nuxthub/db";
|
|
2
2
|
import { count, eq } from "drizzle-orm";
|
|
3
3
|
export default defineEventHandler(async (event) => {
|
|
4
|
-
const
|
|
5
|
-
if (!Number.isInteger(id)) {
|
|
6
|
-
throw createError({ statusCode: 400, statusMessage: "Invalid user id." });
|
|
7
|
-
}
|
|
8
|
-
const actor = await authorizeUsersAdmin(event, "view");
|
|
9
|
-
const target = await db.query.users.findFirst({ where: (t, { eq: eq2 }) => eq2(t.id, id) });
|
|
10
|
-
if (!target) {
|
|
11
|
-
throw createError({ statusCode: 404, statusMessage: "User not found." });
|
|
12
|
-
}
|
|
4
|
+
const { actor, target } = await loadUsersAdminTarget(event, "view");
|
|
13
5
|
const withRole = usersHaveRoles();
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
const subscription = (await latestSubscriptions([id])).get(id) ?? null;
|
|
6
|
+
const targetInfo = usersAdminTargetInfo(target);
|
|
7
|
+
const passkeys = schema.userCredentials ? (await db.select({ total: count() }).from(schema.userCredentials).where(eq(schema.userCredentials.userId, target.id)))[0]?.total ?? 0 : 0;
|
|
8
|
+
const subscription = (await latestSubscriptions([target.id])).get(target.id) ?? null;
|
|
18
9
|
const [canUpdate, canDelete] = await Promise.all([
|
|
19
10
|
isUsersAdminAllowed(event, "update", { target: targetInfo, input: {} }),
|
|
20
11
|
isUsersAdminAllowed(event, "delete", { target: targetInfo })
|
|
21
12
|
]);
|
|
22
|
-
const { password, ...safe } = target;
|
|
23
13
|
return {
|
|
24
|
-
...
|
|
25
|
-
hasPassword: !!password,
|
|
14
|
+
...toAdminUserDto(target),
|
|
15
|
+
hasPassword: !!target.password,
|
|
26
16
|
passkeys,
|
|
27
17
|
subscription,
|
|
28
18
|
hasRoles: withRole,
|
|
@@ -1,45 +1,35 @@
|
|
|
1
1
|
import { db, schema } from "@nuxthub/db";
|
|
2
2
|
import { eq } from "drizzle-orm";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
+
import { emailField, nameField } from "../../schemas.js";
|
|
4
5
|
const bodySchema = z.object({
|
|
5
|
-
name:
|
|
6
|
-
email:
|
|
7
|
-
role: z.string().min(1).optional(),
|
|
6
|
+
name: nameField().optional(),
|
|
7
|
+
email: emailField().optional(),
|
|
8
|
+
role: z.string().trim().min(1).max(60).optional(),
|
|
8
9
|
emailVerified: z.boolean().optional()
|
|
9
10
|
});
|
|
10
11
|
export default defineEventHandler(async (event) => {
|
|
11
|
-
const
|
|
12
|
-
if (!Number.isInteger(id)) {
|
|
13
|
-
throw createError({ statusCode: 400, statusMessage: "Invalid user id." });
|
|
14
|
-
}
|
|
12
|
+
const { target } = await loadUsersAdminTarget(event, "update");
|
|
15
13
|
const input = await readValidatedBody(event, bodySchema.parse);
|
|
16
14
|
const withRole = usersHaveRoles();
|
|
17
|
-
const target = await db.query.users.findFirst({ where: (t, { eq: eq2 }) => eq2(t.id, id) });
|
|
18
|
-
if (!target) {
|
|
19
|
-
throw createError({ statusCode: 404, statusMessage: "User not found." });
|
|
20
|
-
}
|
|
21
15
|
await authorizeUsersAdmin(event, "update", {
|
|
22
16
|
input: { role: withRole ? input.role : void 0, email: input.email, name: input.name },
|
|
23
|
-
target:
|
|
17
|
+
target: usersAdminTargetInfo(target)
|
|
24
18
|
});
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
throw createError({ statusCode: 409, statusMessage: "A user with this email already exists." });
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
const emailChanged = !!input.email && input.email !== target.email;
|
|
32
|
-
const [updated] = await db.update(schema.users).set({
|
|
19
|
+
const emailChanged = !!input.email && !sameUserEmail(input.email, target.email);
|
|
20
|
+
if (emailChanged) await assertEmailAvailable(input.email, { exceptUserId: target.id });
|
|
21
|
+
const changes = {
|
|
33
22
|
...input.name ? { name: input.name } : {},
|
|
34
23
|
// A changed address was typed in by staff, so it is unverified until its owner confirms it (unless staff
|
|
35
24
|
// explicitly marks it verified in the same request).
|
|
36
25
|
...emailChanged ? { email: input.email, emailVerifiedAt: input.emailVerified ? /* @__PURE__ */ new Date() : null } : {},
|
|
37
26
|
...!emailChanged && input.emailVerified !== void 0 ? { emailVerifiedAt: input.emailVerified ? target.emailVerifiedAt ?? /* @__PURE__ */ new Date() : null } : {},
|
|
38
27
|
...withRole && input.role ? { role: input.role } : {}
|
|
39
|
-
}
|
|
28
|
+
};
|
|
29
|
+
if (!Object.keys(changes).length) return toAdminUserDto(target);
|
|
30
|
+
const [updated] = await db.update(schema.users).set(changes).where(eq(schema.users.id, target.id)).returning();
|
|
40
31
|
if (emailChanged && !input.emailVerified) {
|
|
41
32
|
await sendVerificationLink(event, updated);
|
|
42
33
|
}
|
|
43
|
-
|
|
44
|
-
return safe;
|
|
34
|
+
return toAdminUserDto(updated);
|
|
45
35
|
});
|
|
@@ -1,17 +1,15 @@
|
|
|
1
1
|
import { db, schema } from "@nuxthub/db";
|
|
2
|
-
import { and,
|
|
2
|
+
import { and, count, eq, isNotNull, isNull, or } from "drizzle-orm";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
4
|
+
import { escapeLike, likeEscaped as like, orderByQuery, pageQuery, pageRange, paginate } from "@frigear-nu/module-kit/server";
|
|
5
|
+
const querySchema = pageQuery({
|
|
6
|
+
sort: ["id", "name", "email", "role", "createdAt", "lastLoginAt"],
|
|
7
|
+
defaultSort: "createdAt",
|
|
8
|
+
filters: {
|
|
9
|
+
role: z.string().trim().min(1).max(60).optional(),
|
|
10
|
+
verified: z.enum(["true", "false"]).optional()
|
|
11
|
+
}
|
|
12
12
|
});
|
|
13
|
-
const like = (column, pattern) => sql`${column} like ${pattern} escape '\\'`;
|
|
14
|
-
const escapeLike = (value) => value.replace(/[\\%_]/g, (char) => `\\${char}`);
|
|
15
13
|
export default defineEventHandler(async (event) => {
|
|
16
14
|
const actor = await authorizeUsersAdmin(event, "view");
|
|
17
15
|
const query = await getValidatedQuery(event, querySchema.parse);
|
|
@@ -29,29 +27,27 @@ export default defineEventHandler(async (event) => {
|
|
|
29
27
|
conditions.push(query.verified === "true" ? isNotNull(schema.users.emailVerifiedAt) : isNull(schema.users.emailVerifiedAt));
|
|
30
28
|
}
|
|
31
29
|
const where = conditions.length ? and(...conditions) : void 0;
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
30
|
+
const orderBy = orderByQuery({
|
|
31
|
+
id: schema.users.id,
|
|
32
|
+
name: schema.users.name,
|
|
33
|
+
email: schema.users.email,
|
|
34
|
+
role: withRole ? columns.role : void 0,
|
|
35
|
+
createdAt: schema.users.createdAt,
|
|
36
|
+
lastLoginAt: schema.users.lastLoginAt
|
|
37
|
+
}, query, { tiebreaker: schema.users.id });
|
|
38
|
+
const { limit, offset } = pageRange(query);
|
|
35
39
|
const [rows, [totals]] = await Promise.all([
|
|
36
|
-
db.select().from(schema.users).where(where).orderBy(...orderBy).limit(
|
|
40
|
+
db.select().from(schema.users).where(where).orderBy(...orderBy).limit(limit).offset(offset),
|
|
37
41
|
db.select({ total: count() }).from(schema.users).where(where)
|
|
38
42
|
]);
|
|
39
43
|
const subscriptions = await latestSubscriptions(rows.map((user) => user.id));
|
|
40
44
|
const roles = withRole ? await assignableRoles(event, actor.id) : [];
|
|
41
45
|
return {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
...withRole ? { role: user.role } : {},
|
|
48
|
-
emailVerifiedAt: user.emailVerifiedAt,
|
|
49
|
-
lastLoginAt: user.lastLoginAt,
|
|
50
|
-
createdAt: user.createdAt
|
|
51
|
-
})),
|
|
52
|
-
total: totals?.total ?? 0,
|
|
53
|
-
page: query.page,
|
|
54
|
-
pageSize: query.pageSize,
|
|
46
|
+
...paginate({
|
|
47
|
+
total: totals?.total ?? 0,
|
|
48
|
+
query,
|
|
49
|
+
items: rows.map((user) => ({ ...toAdminUserDto(user), subscription: subscriptions.get(user.id) ?? null }))
|
|
50
|
+
}),
|
|
55
51
|
hasRoles: withRole,
|
|
56
52
|
hasSubscriptions: !!schema.subscriptions,
|
|
57
53
|
roles
|
|
@@ -1,33 +1,32 @@
|
|
|
1
1
|
import { db, schema } from "@nuxthub/db";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
+
import { apiError, created } from "@frigear-nu/module-kit/server";
|
|
4
|
+
import { emailField, nameField } from "../../schemas.js";
|
|
3
5
|
const bodySchema = z.object({
|
|
4
|
-
name:
|
|
5
|
-
email:
|
|
6
|
-
role: z.string().min(1).optional(),
|
|
6
|
+
name: nameField(),
|
|
7
|
+
email: emailField(),
|
|
8
|
+
role: z.string().trim().min(1).max(60).optional(),
|
|
7
9
|
// Verified accounts are signed in by the emailed link below; leave unverified to let the user verify themselves.
|
|
8
10
|
emailVerified: z.boolean().default(false),
|
|
9
11
|
sendWelcomeEmail: z.boolean().default(true)
|
|
10
12
|
});
|
|
11
13
|
export default defineEventHandler(async (event) => {
|
|
14
|
+
await authorizeUsersAdmin(event, "create");
|
|
12
15
|
const input = await readValidatedBody(event, bodySchema.parse);
|
|
13
16
|
const withRole = usersHaveRoles();
|
|
14
17
|
await authorizeUsersAdmin(event, "create", { input: { role: withRole ? input.role : void 0, email: input.email, name: input.name } });
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
throw createError({ statusCode: 409, statusMessage: "A user with this email already exists." });
|
|
18
|
-
}
|
|
19
|
-
const [created] = await db.insert(schema.users).values({
|
|
18
|
+
await assertEmailAvailable(input.email);
|
|
19
|
+
const [user] = await db.insert(schema.users).values({
|
|
20
20
|
name: input.name,
|
|
21
21
|
email: input.email,
|
|
22
22
|
emailVerifiedAt: input.emailVerified ? /* @__PURE__ */ new Date() : null,
|
|
23
23
|
...withRole && input.role ? { role: input.role } : {}
|
|
24
24
|
}).returning();
|
|
25
|
-
if (!
|
|
26
|
-
throw
|
|
25
|
+
if (!user) {
|
|
26
|
+
throw apiError(500, "internal_error", "Failed to create the user.");
|
|
27
27
|
}
|
|
28
28
|
if (input.sendWelcomeEmail) {
|
|
29
|
-
await sendVerificationLink(event,
|
|
29
|
+
await sendVerificationLink(event, user);
|
|
30
30
|
}
|
|
31
|
-
|
|
32
|
-
return safe;
|
|
31
|
+
return created(event, toAdminUserDto(user));
|
|
33
32
|
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { db, schema } from "@nuxthub/db";
|
|
2
|
+
import { and, eq, gt, isNull } from "drizzle-orm";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { badRequest, forbidden, notFound } from "@frigear-nu/module-kit/server";
|
|
5
|
+
import { EMAIL_CHANGE_INVALID, findEmailChangeByCode } from "../../email-change.js";
|
|
6
|
+
const REVERT_TTL_DAYS = 7;
|
|
7
|
+
export default defineEventHandler(async (event) => {
|
|
8
|
+
const user = await requireUser(event, { sessionOnly: true });
|
|
9
|
+
const { code } = await readValidatedBody(event, z.object({ code: z.string().min(1) }).parse);
|
|
10
|
+
const now = /* @__PURE__ */ new Date();
|
|
11
|
+
const change = await findEmailChangeByCode(code);
|
|
12
|
+
if (!change || change.verifiedAt || change.expiresAt <= now) {
|
|
13
|
+
throw badRequest(EMAIL_CHANGE_INVALID);
|
|
14
|
+
}
|
|
15
|
+
if (change.userId !== user.id) {
|
|
16
|
+
throw forbidden("This email change belongs to another account. Sign in as that account to confirm it.");
|
|
17
|
+
}
|
|
18
|
+
await assertEmailAvailable(change.newEmail, { exceptUserId: change.userId });
|
|
19
|
+
const [claimed] = await db.update(schema.accountEmailChanges).set({ verifiedAt: now, revertExpiresAt: new Date(now.getTime() + REVERT_TTL_DAYS * 24 * 60 * 60 * 1e3) }).where(and(
|
|
20
|
+
eq(schema.accountEmailChanges.id, change.id),
|
|
21
|
+
eq(schema.accountEmailChanges.userId, user.id),
|
|
22
|
+
isNull(schema.accountEmailChanges.verifiedAt),
|
|
23
|
+
gt(schema.accountEmailChanges.expiresAt, now)
|
|
24
|
+
)).returning();
|
|
25
|
+
if (!claimed) {
|
|
26
|
+
throw badRequest(EMAIL_CHANGE_INVALID);
|
|
27
|
+
}
|
|
28
|
+
const [updated] = await db.update(schema.users).set({ email: normalizeUserEmail(claimed.newEmail), emailVerifiedAt: now }).where(eq(schema.users.id, claimed.userId)).returning();
|
|
29
|
+
if (!updated) throw notFound("User not found.");
|
|
30
|
+
await setUserSession(event, { user: mapUserToSession(updated) });
|
|
31
|
+
const revertUrl = new URL(`/auth/revert-email-change?code=${claimed.revertCode}`, getRequestURL(event).origin).toString();
|
|
32
|
+
await dispatchEmailNotification(buildEmailChangedNotification({
|
|
33
|
+
to: claimed.oldEmail,
|
|
34
|
+
name: updated.name,
|
|
35
|
+
newEmail: claimed.newEmail,
|
|
36
|
+
revertUrl
|
|
37
|
+
})).catch((error) => console.error("[@frigear-nu/users] Could not send the email changed notice.", error));
|
|
38
|
+
const profilePath = useRuntimeConfig(event).public.users?.profilePath;
|
|
39
|
+
return {
|
|
40
|
+
id: updated.id,
|
|
41
|
+
email: updated.email,
|
|
42
|
+
redirect: profilePath ? `${profilePath}?email-changed=1` : void 0
|
|
43
|
+
};
|
|
44
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { notFound } from "@frigear-nu/module-kit/server";
|
|
3
|
+
import { EMAIL_REVERT_INVALID, findEmailChangeByRevertCode } from "../../email-change.js";
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
const { code } = await getValidatedQuery(event, z.object({ code: z.string().min(1) }).parse);
|
|
6
|
+
setResponseHeader(event, "cache-control", "no-store");
|
|
7
|
+
const change = await findEmailChangeByRevertCode(code);
|
|
8
|
+
if (!change?.verifiedAt) {
|
|
9
|
+
throw notFound(EMAIL_REVERT_INVALID);
|
|
10
|
+
}
|
|
11
|
+
const status = change.revertedAt ? "reverted" : !change.revertExpiresAt || change.revertExpiresAt <= /* @__PURE__ */ new Date() ? "expired" : "pending";
|
|
12
|
+
return { status, oldEmail: change.oldEmail, newEmail: change.newEmail };
|
|
13
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { db, schema } from "@nuxthub/db";
|
|
2
|
+
import { and, eq, gt, isNotNull, isNull } from "drizzle-orm";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { badRequest } from "@frigear-nu/module-kit/server";
|
|
5
|
+
import { EMAIL_REVERT_INVALID, findEmailChangeByRevertCode } from "../../email-change.js";
|
|
6
|
+
export default defineEventHandler(async (event) => {
|
|
7
|
+
const { code } = await readValidatedBody(event, z.object({ code: z.string().min(1) }).parse);
|
|
8
|
+
const now = /* @__PURE__ */ new Date();
|
|
9
|
+
const change = await findEmailChangeByRevertCode(code);
|
|
10
|
+
if (!change?.verifiedAt || change.revertedAt || !change.revertExpiresAt || change.revertExpiresAt <= now) {
|
|
11
|
+
throw badRequest(EMAIL_REVERT_INVALID);
|
|
12
|
+
}
|
|
13
|
+
await assertEmailAvailable(change.oldEmail, { exceptUserId: change.userId, message: "The old address now belongs to another account." });
|
|
14
|
+
const [claimed] = await db.update(schema.accountEmailChanges).set({ revertedAt: now }).where(and(
|
|
15
|
+
eq(schema.accountEmailChanges.id, change.id),
|
|
16
|
+
isNotNull(schema.accountEmailChanges.verifiedAt),
|
|
17
|
+
isNull(schema.accountEmailChanges.revertedAt),
|
|
18
|
+
gt(schema.accountEmailChanges.revertExpiresAt, now)
|
|
19
|
+
)).returning();
|
|
20
|
+
if (!claimed) {
|
|
21
|
+
throw badRequest(EMAIL_REVERT_INVALID);
|
|
22
|
+
}
|
|
23
|
+
await db.update(schema.users).set({ email: normalizeUserEmail(claimed.oldEmail) }).where(eq(schema.users.id, claimed.userId));
|
|
24
|
+
const session = await getUserSession(event);
|
|
25
|
+
const signedOut = session.user?.id === claimed.userId;
|
|
26
|
+
if (signedOut) await clearUserSession(event);
|
|
27
|
+
return { email: claimed.oldEmail, signedOut };
|
|
28
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { notFound } from "@frigear-nu/module-kit/server";
|
|
3
|
+
import { EMAIL_CHANGE_INVALID, findEmailChangeByCode, maskEmail } from "../../email-change.js";
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
const { code } = await getValidatedQuery(event, z.object({ code: z.string().min(1) }).parse);
|
|
6
|
+
setResponseHeader(event, "cache-control", "no-store");
|
|
7
|
+
const change = await findEmailChangeByCode(code);
|
|
8
|
+
if (!change) {
|
|
9
|
+
throw notFound(EMAIL_CHANGE_INVALID);
|
|
10
|
+
}
|
|
11
|
+
const user = await getUser(event);
|
|
12
|
+
const owner = user?.id === change.userId;
|
|
13
|
+
const status = change.verifiedAt ? "confirmed" : change.expiresAt <= /* @__PURE__ */ new Date() ? "expired" : "pending";
|
|
14
|
+
return {
|
|
15
|
+
status,
|
|
16
|
+
signedIn: !!user,
|
|
17
|
+
owner,
|
|
18
|
+
// The code was emailed to the new address, so its holder knows it; the old one is only shown to its owner.
|
|
19
|
+
newEmail: change.newEmail,
|
|
20
|
+
oldEmail: owner ? change.oldEmail : maskEmail(change.oldEmail)
|
|
21
|
+
};
|
|
22
|
+
});
|
|
@@ -1,17 +1,16 @@
|
|
|
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 { emailField } from "../../schemas.js";
|
|
4
6
|
const bodySchema = z.object({
|
|
5
|
-
email:
|
|
7
|
+
email: emailField()
|
|
6
8
|
});
|
|
7
9
|
const VERIFY_TTL_HOURS = 24;
|
|
8
10
|
export default defineEventHandler(async (event) => {
|
|
9
11
|
const user = await requireUser(event, { sessionOnly: true });
|
|
10
12
|
const { email } = await readValidatedBody(event, bodySchema.parse);
|
|
11
|
-
|
|
12
|
-
if (existing && existing.id !== user.id) {
|
|
13
|
-
throw createError({ statusCode: 409, statusMessage: "A user with this email already exists." });
|
|
14
|
-
}
|
|
13
|
+
await assertEmailAvailable(email, { exceptUserId: user.id });
|
|
15
14
|
if (useRuntimeConfig(event).users?.verifyEmailChange) {
|
|
16
15
|
const code = createOneTimeCode();
|
|
17
16
|
await db.insert(schema.accountEmailChanges).values({
|
|
@@ -24,12 +23,12 @@ export default defineEventHandler(async (event) => {
|
|
|
24
23
|
});
|
|
25
24
|
const url = new URL(`/auth/verify-email-change?code=${code}`, getRequestURL(event).origin).toString();
|
|
26
25
|
await dispatchEmailNotification(buildVerifyEmailChangeNotification({ to: email, name: user.name, url }));
|
|
27
|
-
|
|
26
|
+
const current = await db.query.users.findFirst({ where: (t, { eq: eq2 }) => eq2(t.id, user.id) });
|
|
27
|
+
if (!current) throw notFound("User not found.");
|
|
28
|
+
return { ...toProfileDto(current), verificationRequired: true };
|
|
28
29
|
}
|
|
29
30
|
const [updated] = await db.update(schema.users).set({ email }).where(eq(schema.users.id, user.id)).returning();
|
|
30
|
-
if (!updated)
|
|
31
|
-
throw createError({ statusCode: 404, statusMessage: "User not found." });
|
|
32
|
-
}
|
|
31
|
+
if (!updated) throw notFound("User not found.");
|
|
33
32
|
await setUserSession(event, { user: mapUserToSession(updated) });
|
|
34
|
-
return {
|
|
33
|
+
return { ...toProfileDto(updated), verificationRequired: false };
|
|
35
34
|
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { db, schema } from "@nuxthub/db";
|
|
2
2
|
import { eq } from "drizzle-orm";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
+
import { apiError, notFound } from "@frigear-nu/module-kit/server";
|
|
4
5
|
const bodySchema = z.object({
|
|
5
6
|
currentPassword: z.string().min(1),
|
|
6
7
|
newPassword: z.string().min(8),
|
|
@@ -14,14 +15,12 @@ export default defineEventHandler(async (event) => {
|
|
|
14
15
|
const { currentPassword, newPassword } = await readValidatedBody(event, bodySchema.parse);
|
|
15
16
|
const dbUser = await db.query.users.findFirst({ where: (t, { eq: eq2 }) => eq2(t.id, user.id) });
|
|
16
17
|
if (!dbUser?.password || !await verifyPassword(dbUser.password, currentPassword)) {
|
|
17
|
-
throw
|
|
18
|
+
throw apiError(401, "invalid_credentials", "Your current password is incorrect.");
|
|
18
19
|
}
|
|
19
20
|
const hashed = await hashPassword(newPassword);
|
|
20
21
|
const [updated] = await db.update(schema.users).set({ password: hashed }).where(eq(schema.users.id, user.id)).returning();
|
|
21
|
-
if (!updated)
|
|
22
|
-
throw createError({ statusCode: 404, statusMessage: "User not found." });
|
|
23
|
-
}
|
|
22
|
+
if (!updated) throw notFound("User not found.");
|
|
24
23
|
await setUserSession(event, { user: mapUserToSession(updated) });
|
|
25
24
|
await dispatchEmailNotification(buildPasswordChangedNotification({ to: updated.email, name: updated.name })).catch((error) => console.error("[@frigear-nu/users] Could not send the password changed notice.", error));
|
|
26
|
-
return
|
|
25
|
+
return toProfileDto(updated);
|
|
27
26
|
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { db, schema } from "@nuxthub/db";
|
|
2
|
+
import { eq } from "drizzle-orm";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { notFound } from "@frigear-nu/module-kit/server";
|
|
5
|
+
import { avatarField, nameField } from "../../schemas.js";
|
|
6
|
+
const bodySchema = z.object({
|
|
7
|
+
name: nameField().optional(),
|
|
8
|
+
// `null` clears the avatar; leaving it out keeps it.
|
|
9
|
+
avatar: avatarField().optional()
|
|
10
|
+
});
|
|
11
|
+
export default defineEventHandler(async (event) => {
|
|
12
|
+
const user = await requireUser(event, { sessionOnly: true });
|
|
13
|
+
const { name, avatar } = await readValidatedBody(event, bodySchema.parse);
|
|
14
|
+
const [updated] = await db.update(schema.users).set({
|
|
15
|
+
...name !== void 0 ? { name } : {},
|
|
16
|
+
...avatar !== void 0 ? { avatar } : {},
|
|
17
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
18
|
+
}).where(eq(schema.users.id, user.id)).returning();
|
|
19
|
+
if (!updated) throw notFound("User not found.");
|
|
20
|
+
await setUserSession(event, { user: mapUserToSession(updated) });
|
|
21
|
+
return toProfileDto(updated);
|
|
22
|
+
});
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/** An email as it is stored: trimmed and lowercased before it is validated. */
|
|
3
|
+
export declare const emailField: () => z.ZodString;
|
|
4
|
+
/** A display name. */
|
|
5
|
+
export declare const nameField: () => z.ZodString;
|
|
6
|
+
/** An avatar: an absolute http(s) URL, or `null` to clear it. */
|
|
7
|
+
export declare const avatarField: () => z.ZodNullable<z.ZodString>;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export const emailField = () => z.string().trim().toLowerCase().email().max(254);
|
|
3
|
+
export const nameField = () => z.string().trim().min(1).max(120);
|
|
4
|
+
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();
|
|
@@ -6,6 +6,7 @@ const asId = (id) => {
|
|
|
6
6
|
const numeric = Number(id);
|
|
7
7
|
return Number.isSafeInteger(numeric) ? numeric : null;
|
|
8
8
|
};
|
|
9
|
+
const withNormalizedEmail = (values) => typeof values.email === "string" ? { ...values, email: normalizeUserEmail(values.email) } : values;
|
|
9
10
|
const isPostgres = () => is(schema.users, PgTable);
|
|
10
11
|
const getTableConfig = (table) => is(table, PgTable) ? getPgTableConfig(table) : getSQLiteTableConfig(table);
|
|
11
12
|
function userReferences() {
|
|
@@ -38,15 +39,16 @@ const store = {
|
|
|
38
39
|
if (numeric === null) return null;
|
|
39
40
|
return await db.query.users.findFirst({ where: (t, { eq: eq2 }) => eq2(t.id, numeric) }) ?? null;
|
|
40
41
|
},
|
|
42
|
+
// Case-insensitive, index first (see `findUserByEmail`).
|
|
41
43
|
async findByEmail(email) {
|
|
42
|
-
return await
|
|
44
|
+
return await findUserByEmail(email);
|
|
43
45
|
},
|
|
44
46
|
async create(values) {
|
|
45
|
-
const [user] = await db.insert(schema.users).values(values).returning();
|
|
47
|
+
const [user] = await db.insert(schema.users).values(withNormalizedEmail(values)).returning();
|
|
46
48
|
return user;
|
|
47
49
|
},
|
|
48
50
|
async update(id, values) {
|
|
49
|
-
const [user] = await db.update(schema.users).set(values).where(eq(schema.users.id, id)).returning();
|
|
51
|
+
const [user] = await db.update(schema.users).set(withNormalizedEmail(values)).where(eq(schema.users.id, id)).returning();
|
|
50
52
|
return user ?? null;
|
|
51
53
|
},
|
|
52
54
|
async remove(id) {
|
|
@@ -29,9 +29,9 @@ export type UsersAdminRolesContext = {
|
|
|
29
29
|
};
|
|
30
30
|
/** Whether another module added a `role` column to `users` (`@frigear-nu/authorization`). */
|
|
31
31
|
export declare const usersHaveRoles: () => boolean;
|
|
32
|
-
/** Whether the host policy allows the signed-in user to do `action` (never throws on denial). */
|
|
32
|
+
/** Whether the host policy allows the signed-in user to do `action` (never throws on denial; 401/403 without a session). */
|
|
33
33
|
export declare function isUsersAdminAllowed(event: H3Event, action: UsersAdminAction, details?: Pick<UsersAdminContext, 'input' | 'target'>): Promise<{
|
|
34
|
-
allowed:
|
|
34
|
+
allowed: any;
|
|
35
35
|
user: any;
|
|
36
36
|
}>;
|
|
37
37
|
/**
|
|
@@ -49,9 +49,21 @@ export declare function latestSubscriptions(userIds: number[]): Promise<Map<numb
|
|
|
49
49
|
planKey: string | null;
|
|
50
50
|
status: string;
|
|
51
51
|
}>>;
|
|
52
|
+
/** The policy view of a stored user: what the `users:admin:authorize` hook sees as `target`. */
|
|
53
|
+
export declare const usersAdminTargetInfo: (user: {
|
|
54
|
+
id: number;
|
|
55
|
+
email: string;
|
|
56
|
+
}) => {
|
|
57
|
+
id: number;
|
|
58
|
+
email: string;
|
|
59
|
+
role: string | undefined;
|
|
60
|
+
};
|
|
52
61
|
/**
|
|
53
62
|
* Loads the user a staff member is acting on (`/api/admin/users/:id/...`) and runs the users admin policy against
|
|
54
|
-
* them (`view` for reads, `update` for changes).
|
|
63
|
+
* them (`view` for reads, `update` for changes). For routes added with `extendUsersAdmin`.
|
|
64
|
+
*
|
|
65
|
+
* Authorizes before it looks anything up: 401 without a session, 403 when the host denies `action` outright, then
|
|
66
|
+
* 400 for a malformed id, 404 for an unknown user, and 403 again when the host denies `action` on this target.
|
|
55
67
|
*/
|
|
56
68
|
export declare function loadUsersAdminTarget(event: H3Event, action: Exclude<UsersAdminAction, 'create'>): Promise<{
|
|
57
69
|
actor: any;
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import { db, schema } from "@nuxthub/db";
|
|
2
2
|
import { desc, getTableColumns, inArray } from "drizzle-orm";
|
|
3
|
+
import { intIdParams, notFound } from "@frigear-nu/module-kit/server";
|
|
3
4
|
export const usersHaveRoles = () => "role" in getTableColumns(schema.users);
|
|
5
|
+
const usersAdminGate = definePolicyGate("users:admin:authorize");
|
|
6
|
+
const USERS_ADMIN_DENIED = "You are not allowed to manage users.";
|
|
4
7
|
export async function isUsersAdminAllowed(event, action, details = {}) {
|
|
5
8
|
const user = await requireUser(event, { sessionOnly: true });
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
return { allowed: context.allowed, user };
|
|
9
|
+
const allowed = await usersAdminGate.isAllowed(event, user.id, { action, ...details });
|
|
10
|
+
return { allowed, user };
|
|
9
11
|
}
|
|
10
12
|
export async function authorizeUsersAdmin(event, action, details = {}) {
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
throw createError({ statusCode: 403, statusMessage: "You are not allowed to manage users." });
|
|
14
|
-
}
|
|
13
|
+
const user = await requireUser(event, { sessionOnly: true });
|
|
14
|
+
await usersAdminGate.assert(event, user.id, USERS_ADMIN_DENIED, { action, ...details });
|
|
15
15
|
return user;
|
|
16
16
|
}
|
|
17
17
|
export async function assignableRoles(event, userId) {
|
|
@@ -39,15 +39,16 @@ export async function latestSubscriptions(userIds) {
|
|
|
39
39
|
}
|
|
40
40
|
return result;
|
|
41
41
|
}
|
|
42
|
+
export const usersAdminTargetInfo = (user) => ({
|
|
43
|
+
id: user.id,
|
|
44
|
+
email: user.email,
|
|
45
|
+
role: usersHaveRoles() ? user.role : void 0
|
|
46
|
+
});
|
|
42
47
|
export async function loadUsersAdminTarget(event, action) {
|
|
43
|
-
|
|
44
|
-
|
|
48
|
+
await authorizeUsersAdmin(event, action);
|
|
49
|
+
const { id } = await getValidatedRouterParams(event, intIdParams().parse);
|
|
45
50
|
const target = await db.query.users.findFirst({ where: (t, { eq }) => eq(t.id, id) });
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
action,
|
|
49
|
-
target ? { target: { id: target.id, email: target.email, role: target.role }, input: {} } : {}
|
|
50
|
-
);
|
|
51
|
-
if (!target) throw createError({ statusCode: 404, statusMessage: "User not found." });
|
|
51
|
+
if (!target) throw notFound("User not found.");
|
|
52
|
+
const actor = await authorizeUsersAdmin(event, action, { target: usersAdminTargetInfo(target), input: {} });
|
|
52
53
|
return { actor, target };
|
|
53
54
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AdminUserDto, ProfileDto } from '../../../types.js';
|
|
2
|
+
/** The columns the DTOs read; `role`, `emailVerifiedAt` and `lastLoginAt` come from other modules' extensions. */
|
|
3
|
+
type UserRowLike = {
|
|
4
|
+
id: number;
|
|
5
|
+
name: string;
|
|
6
|
+
email: string;
|
|
7
|
+
avatar?: string | null;
|
|
8
|
+
role?: string | null;
|
|
9
|
+
emailVerifiedAt?: Date | number | string | null;
|
|
10
|
+
lastLoginAt?: Date | number | string | null;
|
|
11
|
+
createdAt: Date | number | string;
|
|
12
|
+
};
|
|
13
|
+
/** A stored user as the users admin returns it: an allowlist (never the password hash or other modules' columns). */
|
|
14
|
+
export declare function toAdminUserDto(user: UserRowLike): AdminUserDto;
|
|
15
|
+
/** The signed-in user's own profile, as the self-service routes return it. */
|
|
16
|
+
export declare function toProfileDto(user: Pick<UserRowLike, 'name' | 'email' | 'avatar' | 'emailVerifiedAt'> & {
|
|
17
|
+
id: number | string;
|
|
18
|
+
}): ProfileDto;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { isoDate } from "@frigear-nu/module-kit/server";
|
|
2
|
+
export function toAdminUserDto(user) {
|
|
3
|
+
return {
|
|
4
|
+
id: user.id,
|
|
5
|
+
name: user.name,
|
|
6
|
+
email: user.email,
|
|
7
|
+
...usersHaveRoles() && user.role ? { role: user.role } : {},
|
|
8
|
+
avatar: user.avatar ?? null,
|
|
9
|
+
emailVerifiedAt: isoDate(user.emailVerifiedAt),
|
|
10
|
+
lastLoginAt: isoDate(user.lastLoginAt),
|
|
11
|
+
createdAt: isoDate(user.createdAt)
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export function toProfileDto(user) {
|
|
15
|
+
return {
|
|
16
|
+
id: Number(user.id),
|
|
17
|
+
name: user.name,
|
|
18
|
+
email: user.email,
|
|
19
|
+
avatar: user.avatar ?? null,
|
|
20
|
+
emailVerifiedAt: isoDate(user.emailVerifiedAt)
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** How every email is stored: trimmed and lowercased, so `Ada@Example.com` and `ada@example.com` are one account. */
|
|
2
|
+
export declare const normalizeUserEmail: (email: string) => string;
|
|
3
|
+
/** Whether two addresses are the same account (trimmed, case-insensitive). */
|
|
4
|
+
export declare const sameUserEmail: (a: string, b: string) => boolean;
|
|
5
|
+
/**
|
|
6
|
+
* The user holding `email`, case-insensitively. The exact (normalised) address is looked up first, which the unique
|
|
7
|
+
* index on `users.email` answers; only on a miss does it fall back to `lower(email) = ?` (a scan), for rows stored
|
|
8
|
+
* before emails were normalised. The same SQL on sqlite and postgresql. Used by the auth user store too.
|
|
9
|
+
*/
|
|
10
|
+
export declare function findUserByEmail(email: string): Promise<any>;
|
|
11
|
+
/**
|
|
12
|
+
* Throws 409 `conflict` when another user holds `email` (case-insensitively). `exceptUserId` is the user the address
|
|
13
|
+
* is being written to, who may already hold it.
|
|
14
|
+
*/
|
|
15
|
+
export declare function assertEmailAvailable(email: string, options?: {
|
|
16
|
+
exceptUserId?: number;
|
|
17
|
+
message?: string;
|
|
18
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { db, schema } from "@nuxthub/db";
|
|
2
|
+
import { eq, sql } from "drizzle-orm";
|
|
3
|
+
import { conflict } from "@frigear-nu/module-kit/server";
|
|
4
|
+
export const normalizeUserEmail = (email) => email.trim().toLowerCase();
|
|
5
|
+
export const sameUserEmail = (a, b) => normalizeUserEmail(a) === normalizeUserEmail(b);
|
|
6
|
+
export async function findUserByEmail(email) {
|
|
7
|
+
const address = normalizeUserEmail(email);
|
|
8
|
+
const [exact] = await db.select().from(schema.users).where(eq(schema.users.email, address)).limit(1);
|
|
9
|
+
if (exact) return exact;
|
|
10
|
+
const [legacy] = await db.select().from(schema.users).where(sql`lower(${schema.users.email}) = ${address}`).limit(1);
|
|
11
|
+
return legacy ?? null;
|
|
12
|
+
}
|
|
13
|
+
export async function assertEmailAvailable(email, options = {}) {
|
|
14
|
+
const holder = await findUserByEmail(email);
|
|
15
|
+
if (holder && holder.id !== options.exceptUserId) {
|
|
16
|
+
throw conflict(options.message ?? "A user with this email already exists.", { field: "email" });
|
|
17
|
+
}
|
|
18
|
+
}
|