@frigear-nu/users 1.1.3 → 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 +21 -1
- package/dist/module.json +1 -1
- package/dist/module.mjs +25 -30
- 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.vue +3 -2
- package/dist/runtime/app/pages/verify-email-change.vue +3 -2
- 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 +5 -3
- package/dist/runtime/i18n/lang/en.json +5 -3
- 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 +7 -11
- package/dist/runtime/server/routes/me/email-change-revert.get.js +2 -1
- package/dist/runtime/server/routes/me/email-change-revert.post.js +5 -7
- package/dist/runtime/server/routes/me/email-change.get.js +2 -1
- package/dist/runtime/server/routes/me/{change-email.post.js → email.put.js} +9 -10
- package/dist/runtime/server/routes/me/{change-password.post.js → password.put.js} +4 -5
- 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 +16 -11
- package/dist/runtime/server/routes/me/profile.post.js +0 -17
- /package/dist/runtime/server/routes/me/{change-email.post.d.ts → email.put.d.ts} +0 -0
- /package/dist/runtime/server/routes/me/{change-password.post.d.ts → password.put.d.ts} +0 -0
- /package/dist/runtime/server/routes/me/{profile.post.d.ts → profile.patch.d.ts} +0 -0
|
@@ -1,18 +1,16 @@
|
|
|
1
1
|
import { db, schema } from "@nuxthub/db";
|
|
2
2
|
import { and, eq, gt, isNotNull, isNull } from "drizzle-orm";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
+
import { badRequest } from "@frigear-nu/module-kit/server";
|
|
4
5
|
import { EMAIL_REVERT_INVALID, findEmailChangeByRevertCode } from "../../email-change.js";
|
|
5
6
|
export default defineEventHandler(async (event) => {
|
|
6
7
|
const { code } = await readValidatedBody(event, z.object({ code: z.string().min(1) }).parse);
|
|
7
8
|
const now = /* @__PURE__ */ new Date();
|
|
8
9
|
const change = await findEmailChangeByRevertCode(code);
|
|
9
10
|
if (!change?.verifiedAt || change.revertedAt || !change.revertExpiresAt || change.revertExpiresAt <= now) {
|
|
10
|
-
throw
|
|
11
|
-
}
|
|
12
|
-
const taken = await db.query.users.findFirst({ where: (t, { eq: eq2 }) => eq2(t.email, change.oldEmail) });
|
|
13
|
-
if (taken && taken.id !== change.userId) {
|
|
14
|
-
throw createError({ statusCode: 409, statusMessage: "The old address now belongs to another account." });
|
|
11
|
+
throw badRequest(EMAIL_REVERT_INVALID);
|
|
15
12
|
}
|
|
13
|
+
await assertEmailAvailable(change.oldEmail, { exceptUserId: change.userId, message: "The old address now belongs to another account." });
|
|
16
14
|
const [claimed] = await db.update(schema.accountEmailChanges).set({ revertedAt: now }).where(and(
|
|
17
15
|
eq(schema.accountEmailChanges.id, change.id),
|
|
18
16
|
isNotNull(schema.accountEmailChanges.verifiedAt),
|
|
@@ -20,9 +18,9 @@ export default defineEventHandler(async (event) => {
|
|
|
20
18
|
gt(schema.accountEmailChanges.revertExpiresAt, now)
|
|
21
19
|
)).returning();
|
|
22
20
|
if (!claimed) {
|
|
23
|
-
throw
|
|
21
|
+
throw badRequest(EMAIL_REVERT_INVALID);
|
|
24
22
|
}
|
|
25
|
-
await db.update(schema.users).set({ email: claimed.oldEmail }).where(eq(schema.users.id, claimed.userId));
|
|
23
|
+
await db.update(schema.users).set({ email: normalizeUserEmail(claimed.oldEmail) }).where(eq(schema.users.id, claimed.userId));
|
|
26
24
|
const session = await getUserSession(event);
|
|
27
25
|
const signedOut = session.user?.id === claimed.userId;
|
|
28
26
|
if (signedOut) await clearUserSession(event);
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { notFound } from "@frigear-nu/module-kit/server";
|
|
2
3
|
import { EMAIL_CHANGE_INVALID, findEmailChangeByCode, maskEmail } from "../../email-change.js";
|
|
3
4
|
export default defineEventHandler(async (event) => {
|
|
4
5
|
const { code } = await getValidatedQuery(event, z.object({ code: z.string().min(1) }).parse);
|
|
5
6
|
setResponseHeader(event, "cache-control", "no-store");
|
|
6
7
|
const change = await findEmailChangeByCode(code);
|
|
7
8
|
if (!change) {
|
|
8
|
-
throw
|
|
9
|
+
throw notFound(EMAIL_CHANGE_INVALID);
|
|
9
10
|
}
|
|
10
11
|
const user = await getUser(event);
|
|
11
12
|
const owner = user?.id === change.userId;
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { AdminUserDto, ProfileDto } from '../../types.js';
|
|
2
|
+
export type { AdminUserDto, ProfileDto };
|
|
3
|
+
/** The users API: self-service under `/api/users`, staff under `/api/admin/users`. */
|
|
4
|
+
export declare const usersApi: {
|
|
5
|
+
readonly me: {
|
|
6
|
+
/** `PATCH { name, avatar? }`: updates the caller's profile, answers the profile DTO. Session only. */
|
|
7
|
+
readonly profile: "/api/users/me";
|
|
8
|
+
/** `PUT { email }`: changes the caller's email (or emails a confirmation link with `verifyEmailChange`). Session only. */
|
|
9
|
+
readonly email: "/api/users/me/email";
|
|
10
|
+
/** `PUT { currentPassword, newPassword, confirmNewPassword }`: changes the caller's password. Session only. */
|
|
11
|
+
readonly password: "/api/users/me/password";
|
|
12
|
+
};
|
|
13
|
+
/** `GET ?code=`: read-only preview of an email change link (`verifyEmailChange`). */
|
|
14
|
+
readonly emailChange: "/api/users/email-change";
|
|
15
|
+
/** `POST { code }`: confirms an email change; the signed-in owner only. */
|
|
16
|
+
readonly emailChangeConfirm: "/api/users/email-change/confirm";
|
|
17
|
+
/** `GET ?code=` (preview) and `POST { code }` (restore the old address). The code is the proof, no sign-in needed. */
|
|
18
|
+
readonly emailChangeRevert: "/api/users/email-change/revert";
|
|
19
|
+
readonly admin: {
|
|
20
|
+
/** `GET` (paginated list, `useTableQuery` keys plus `role`, `verified`) and `POST` (create, 201). */
|
|
21
|
+
readonly users: "/api/admin/users";
|
|
22
|
+
/** `GET` (detail), `PATCH` (edit) and `DELETE` (204). */
|
|
23
|
+
readonly user: (id: number | string) => string;
|
|
24
|
+
/** `POST`: emails the sign-in link (or the verification email) again. */
|
|
25
|
+
readonly resend: (id: number | string) => string;
|
|
26
|
+
/** `GET`: the newest sign-ups of the last 30 days (dashboard). */
|
|
27
|
+
readonly new: "/api/admin/users/new";
|
|
28
|
+
/** `GET`: `{ total, newUsers, days }` (dashboard). */
|
|
29
|
+
readonly stats: "/api/admin/users/stats";
|
|
30
|
+
/** `GET`: `{ roles }` the caller may assign. */
|
|
31
|
+
readonly roles: "/api/admin/users/roles";
|
|
32
|
+
};
|
|
33
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const base = "/api/users";
|
|
2
|
+
const adminBase = "/api/admin/users";
|
|
3
|
+
export const usersApi = {
|
|
4
|
+
me: {
|
|
5
|
+
/** `PATCH { name, avatar? }`: updates the caller's profile, answers the profile DTO. Session only. */
|
|
6
|
+
profile: `${base}/me`,
|
|
7
|
+
/** `PUT { email }`: changes the caller's email (or emails a confirmation link with `verifyEmailChange`). Session only. */
|
|
8
|
+
email: `${base}/me/email`,
|
|
9
|
+
/** `PUT { currentPassword, newPassword, confirmNewPassword }`: changes the caller's password. Session only. */
|
|
10
|
+
password: `${base}/me/password`
|
|
11
|
+
},
|
|
12
|
+
/** `GET ?code=`: read-only preview of an email change link (`verifyEmailChange`). */
|
|
13
|
+
emailChange: `${base}/email-change`,
|
|
14
|
+
/** `POST { code }`: confirms an email change; the signed-in owner only. */
|
|
15
|
+
emailChangeConfirm: `${base}/email-change/confirm`,
|
|
16
|
+
/** `GET ?code=` (preview) and `POST { code }` (restore the old address). The code is the proof, no sign-in needed. */
|
|
17
|
+
emailChangeRevert: `${base}/email-change/revert`,
|
|
18
|
+
admin: {
|
|
19
|
+
/** `GET` (paginated list, `useTableQuery` keys plus `role`, `verified`) and `POST` (create, 201). */
|
|
20
|
+
users: adminBase,
|
|
21
|
+
/** `GET` (detail), `PATCH` (edit) and `DELETE` (204). */
|
|
22
|
+
user: (id) => `${adminBase}/${encodeURIComponent(String(id))}`,
|
|
23
|
+
/** `POST`: emails the sign-in link (or the verification email) again. */
|
|
24
|
+
resend: (id) => `${adminBase}/${encodeURIComponent(String(id))}/resend`,
|
|
25
|
+
/** `GET`: the newest sign-ups of the last 30 days (dashboard). */
|
|
26
|
+
new: `${adminBase}/new`,
|
|
27
|
+
/** `GET`: `{ total, newUsers, days }` (dashboard). */
|
|
28
|
+
stats: `${adminBase}/stats`,
|
|
29
|
+
/** `GET`: `{ roles }` the caller may assign. */
|
|
30
|
+
roles: `${adminBase}/roles`
|
|
31
|
+
}
|
|
32
|
+
};
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { Nuxt } from '@nuxt/schema';
|
|
2
2
|
import type { TabDefinition, WidgetDefinition } from '@frigear-nu/widget/utils';
|
|
3
|
+
export { usersApi } from './api.js';
|
|
4
|
+
export type { AdminUserDto, ProfileDto } from '../../types.js';
|
|
3
5
|
export interface UsersAdminExtension {
|
|
4
6
|
/** Staff routes on the user, mounted at `/api/admin/users/:id/<path>`. Handlers are absolute paths. */
|
|
5
7
|
routes?: {
|
|
6
|
-
method: 'get' | 'post' | 'patch' | 'delete';
|
|
8
|
+
method: 'get' | 'post' | 'put' | 'patch' | 'delete';
|
|
7
9
|
path: string;
|
|
8
10
|
handler: string;
|
|
9
11
|
}[];
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { addServerHandler, hasNuxtModule } from "@nuxt/kit";
|
|
2
|
+
export { usersApi } from "./api.js";
|
|
2
3
|
export async function extendUsersAdmin(nuxt, extension) {
|
|
3
4
|
for (const { method, path, handler } of extension.routes ?? []) {
|
|
4
5
|
addServerHandler({ route: `/api/admin/users/:id/${path}`, method, handler });
|
package/dist/types.d.mts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frigear-nu/users",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.4",
|
|
4
4
|
"description": "The user entity for the main frigear app: the users table, admin user management and self-service profile, email and password changes. Sign-in lives in @frigear-nu/auth.",
|
|
5
5
|
"homepage": "https://docs.frigear.dev/modules/users",
|
|
6
6
|
"repository": {
|
|
@@ -20,6 +20,11 @@
|
|
|
20
20
|
"types": "./dist/runtime/utils/index.d.ts",
|
|
21
21
|
"import": "./dist/runtime/utils/index.js",
|
|
22
22
|
"default": "./dist/runtime/utils/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./api": {
|
|
25
|
+
"types": "./dist/runtime/utils/api.d.ts",
|
|
26
|
+
"import": "./dist/runtime/utils/api.js",
|
|
27
|
+
"default": "./dist/runtime/utils/api.js"
|
|
23
28
|
}
|
|
24
29
|
},
|
|
25
30
|
"files": [
|
|
@@ -29,11 +34,11 @@
|
|
|
29
34
|
"playground"
|
|
30
35
|
],
|
|
31
36
|
"dependencies": {
|
|
32
|
-
"@frigear-nu/auth": "0.1.
|
|
33
|
-
"@frigear-nu/mcp": "0.1.
|
|
34
|
-
"@frigear-nu/module-kit": "1.1.
|
|
35
|
-
"@frigear-nu/notify": "0.1.
|
|
36
|
-
"@frigear-nu/ui": "0.1.
|
|
37
|
+
"@frigear-nu/auth": "0.1.4",
|
|
38
|
+
"@frigear-nu/mcp": "0.1.3",
|
|
39
|
+
"@frigear-nu/module-kit": "1.1.3",
|
|
40
|
+
"@frigear-nu/notify": "0.1.3",
|
|
41
|
+
"@frigear-nu/ui": "0.1.3",
|
|
37
42
|
"@libsql/client": "^0.18.0",
|
|
38
43
|
"@nuxt/kit": "^4.6.1",
|
|
39
44
|
"drizzle-kit": "^0.31.11",
|
|
@@ -44,8 +49,8 @@
|
|
|
44
49
|
"peerDependencies": {
|
|
45
50
|
"@frigear-nu/admin": ">=0.0.0",
|
|
46
51
|
"@frigear-nu/email-templates": "0.1.0",
|
|
47
|
-
"@frigear-nu/menu": "0.1.
|
|
48
|
-
"@frigear-nu/widget": "0.1.
|
|
52
|
+
"@frigear-nu/menu": "0.1.3",
|
|
53
|
+
"@frigear-nu/widget": "0.1.3",
|
|
49
54
|
"@nuxt/ui": "^4.12.0",
|
|
50
55
|
"@nuxthub/core": "^0.10.8"
|
|
51
56
|
},
|
|
@@ -68,10 +73,10 @@
|
|
|
68
73
|
},
|
|
69
74
|
"devDependencies": {
|
|
70
75
|
"@electric-sql/pglite": "^0.5.9",
|
|
71
|
-
"@frigear-nu/admin": "0.1.
|
|
76
|
+
"@frigear-nu/admin": "0.1.3",
|
|
72
77
|
"@frigear-nu/email-templates": "0.1.0",
|
|
73
|
-
"@frigear-nu/menu": "0.1.
|
|
74
|
-
"@frigear-nu/widget": "0.1.
|
|
78
|
+
"@frigear-nu/menu": "0.1.3",
|
|
79
|
+
"@frigear-nu/widget": "0.1.3",
|
|
75
80
|
"@nuxt/devtools": "^3.4.2",
|
|
76
81
|
"@nuxt/eslint-config": "^1.17.0",
|
|
77
82
|
"@nuxt/module-builder": "^1.0.3",
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { db, schema } from "@nuxthub/db";
|
|
2
|
-
import { eq } from "drizzle-orm";
|
|
3
|
-
import { z } from "zod";
|
|
4
|
-
const bodySchema = z.object({
|
|
5
|
-
name: z.string().min(1),
|
|
6
|
-
avatar: z.string().optional()
|
|
7
|
-
});
|
|
8
|
-
export default defineEventHandler(async (event) => {
|
|
9
|
-
const user = await requireUser(event, { sessionOnly: true });
|
|
10
|
-
const { name, avatar } = await readValidatedBody(event, bodySchema.parse);
|
|
11
|
-
const [updated] = await db.update(schema.users).set({ name, avatar }).where(eq(schema.users.id, user.id)).returning();
|
|
12
|
-
if (!updated) {
|
|
13
|
-
throw createError({ statusCode: 404, statusMessage: "User not found." });
|
|
14
|
-
}
|
|
15
|
-
await setUserSession(event, { user: mapUserToSession(updated) });
|
|
16
|
-
return { id: updated.id };
|
|
17
|
-
});
|
|
File without changes
|
|
File without changes
|
|
File without changes
|