@frigear-nu/users 2.0.0 → 3.1.0
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/README.md +6 -3
- package/dist/module.d.mts +3 -13
- package/dist/module.json +1 -1
- package/dist/module.mjs +4 -10
- package/dist/runtime/access.d.ts +3 -0
- package/dist/runtime/access.js +22 -0
- package/dist/runtime/admin-menus.js +3 -1
- package/dist/runtime/app/components/UserCreateSlideover.d.vue.ts +3 -6
- package/dist/runtime/app/components/UserCreateSlideover.vue +3 -21
- package/dist/runtime/app/components/UserCreateSlideover.vue.d.ts +3 -6
- package/dist/runtime/app/composables/useUserActions.d.ts +1 -3
- package/dist/runtime/app/composables/useUserActions.js +2 -2
- package/dist/runtime/app/pages/admin.vue +8 -8
- package/dist/runtime/app/tabs/Overview.vue +10 -30
- package/dist/runtime/app/utils/admin-user.d.ts +11 -3
- package/dist/runtime/i18n/lang/da.json +13 -4
- package/dist/runtime/i18n/lang/en.json +13 -4
- package/dist/runtime/server/mcp/tools/get-my-profile.js +1 -1
- package/dist/runtime/server/routes/admin/new.get.js +1 -1
- package/dist/runtime/server/routes/admin/stats.get.js +1 -1
- package/dist/runtime/server/routes/admin/user-resend.post.js +1 -1
- package/dist/runtime/server/routes/admin/user.get.js +6 -9
- package/dist/runtime/server/routes/admin/user.patch.js +2 -8
- package/dist/runtime/server/routes/admin/users.get.js +21 -13
- package/dist/runtime/server/routes/admin/users.post.js +2 -5
- package/dist/runtime/server/routes/me/profile.patch.js +2 -2
- package/dist/runtime/server/utils/admin.d.ts +55 -81
- package/dist/runtime/server/utils/admin.js +58 -48
- package/dist/runtime/server/utils/dto.d.ts +1 -2
- package/dist/runtime/server/utils/dto.js +0 -1
- package/dist/runtime/server/utils/require-user.d.ts +11 -6
- package/dist/runtime/server/utils/require-user.js +3 -6
- package/dist/runtime/server/utils/roles.d.ts +17 -0
- package/dist/runtime/server/utils/roles.js +8 -0
- package/dist/runtime/utils/api.d.ts +2 -4
- package/dist/runtime/utils/api.js +3 -5
- package/package.json +13 -13
- package/dist/runtime/server/plugins/users-read-scope.d.ts +0 -2
- package/dist/runtime/server/plugins/users-read-scope.js +0 -6
- package/dist/runtime/server/routes/admin/roles.get.d.ts +0 -2
- package/dist/runtime/server/routes/admin/roles.get.js +0 -4
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { db, schema } from "@nuxthub/db";
|
|
2
|
-
import { and, count,
|
|
2
|
+
import { and, asc, count, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { escapeLike, likeEscaped as like, orderByQuery, pageQuery, pageRange, paginate } from "@frigear-nu/module-kit/server";
|
|
5
5
|
const querySchema = pageQuery({
|
|
@@ -11,27 +11,27 @@ const querySchema = pageQuery({
|
|
|
11
11
|
}
|
|
12
12
|
});
|
|
13
13
|
export default defineEventHandler(async (event) => {
|
|
14
|
-
|
|
14
|
+
await authorizeUsersAdmin(event, "list");
|
|
15
15
|
const query = await getValidatedQuery(event, querySchema.parse);
|
|
16
|
-
const
|
|
17
|
-
const columns = schema.users;
|
|
16
|
+
const userRoles = usersRoleAssignments();
|
|
18
17
|
const conditions = [];
|
|
19
18
|
if (query.q) {
|
|
20
19
|
const pattern = `%${escapeLike(query.q)}%`;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
conditions.push(or(like(schema.users.name, pattern), like(schema.users.email, pattern)));
|
|
21
|
+
}
|
|
22
|
+
if (query.role && userRoles) {
|
|
23
|
+
conditions.push(sql`exists (select 1 from ${userRoles} where ${userRoles.userId} = ${schema.users.id} and ${userRoles.role} = ${query.role})`);
|
|
24
24
|
}
|
|
25
|
-
if (query.role && withRole && columns.role) conditions.push(eq(columns.role, query.role));
|
|
26
25
|
if (query.verified) {
|
|
27
26
|
conditions.push(query.verified === "true" ? isNotNull(schema.users.emailVerifiedAt) : isNull(schema.users.emailVerifiedAt));
|
|
28
27
|
}
|
|
29
28
|
const where = conditions.length ? and(...conditions) : void 0;
|
|
29
|
+
const firstRole = userRoles ? sql`(select min(${userRoles.role}) from ${userRoles} where ${userRoles.userId} = ${schema.users.id})` : void 0;
|
|
30
30
|
const orderBy = orderByQuery({
|
|
31
31
|
id: schema.users.id,
|
|
32
32
|
name: schema.users.name,
|
|
33
33
|
email: schema.users.email,
|
|
34
|
-
role:
|
|
34
|
+
role: firstRole,
|
|
35
35
|
createdAt: schema.users.createdAt,
|
|
36
36
|
lastLoginAt: schema.users.lastLoginAt
|
|
37
37
|
}, query, { tiebreaker: schema.users.id });
|
|
@@ -41,15 +41,23 @@ export default defineEventHandler(async (event) => {
|
|
|
41
41
|
db.select({ total: count() }).from(schema.users).where(where)
|
|
42
42
|
]);
|
|
43
43
|
const subscriptions = await latestSubscriptions(rows.map((user) => user.id));
|
|
44
|
-
const
|
|
44
|
+
const rolesByUser = /* @__PURE__ */ new Map();
|
|
45
|
+
if (userRoles && rows.length) {
|
|
46
|
+
const assigned = await db.select({ userId: userRoles.userId, role: userRoles.role }).from(userRoles).where(inArray(userRoles.userId, rows.map((user) => user.id))).orderBy(asc(userRoles.role));
|
|
47
|
+
for (const { userId, role } of assigned) rolesByUser.set(userId, [...rolesByUser.get(userId) ?? [], role]);
|
|
48
|
+
}
|
|
45
49
|
return {
|
|
46
50
|
...paginate({
|
|
47
51
|
total: totals?.total ?? 0,
|
|
48
52
|
query,
|
|
49
|
-
items: rows.map((user) => ({
|
|
53
|
+
items: rows.map((user) => ({
|
|
54
|
+
...toAdminUserDto(user),
|
|
55
|
+
subscription: subscriptions.get(user.id) ?? null,
|
|
56
|
+
...userRoles ? { roles: rolesByUser.get(user.id) ?? [] } : {}
|
|
57
|
+
}))
|
|
50
58
|
}),
|
|
51
|
-
hasRoles:
|
|
59
|
+
hasRoles: !!userRoles,
|
|
52
60
|
hasSubscriptions: !!schema.subscriptions,
|
|
53
|
-
roles
|
|
61
|
+
roles: userRoles ? usersStoredRoleOptions() : []
|
|
54
62
|
};
|
|
55
63
|
});
|
|
@@ -5,7 +5,6 @@ import { emailField, nameField } from "../../schemas.js";
|
|
|
5
5
|
const bodySchema = z.object({
|
|
6
6
|
name: nameField(),
|
|
7
7
|
email: emailField(),
|
|
8
|
-
role: z.string().trim().min(1).max(60).optional(),
|
|
9
8
|
// Verified accounts are signed in by the emailed link below; leave unverified to let the user verify themselves.
|
|
10
9
|
emailVerified: z.boolean().default(false),
|
|
11
10
|
sendWelcomeEmail: z.boolean().default(true)
|
|
@@ -13,14 +12,12 @@ const bodySchema = z.object({
|
|
|
13
12
|
export default defineEventHandler(async (event) => {
|
|
14
13
|
await authorizeUsersAdmin(event, "create");
|
|
15
14
|
const input = await readValidatedBody(event, bodySchema.parse);
|
|
16
|
-
|
|
17
|
-
await authorizeUsersAdmin(event, "create", { input: { role: withRole ? input.role : void 0, email: input.email, name: input.name } });
|
|
15
|
+
if (input.emailVerified) await authorize(event, USERS_MANAGE_PERMISSION);
|
|
18
16
|
await assertEmailAvailable(input.email);
|
|
19
17
|
const [user] = await db.insert(schema.users).values({
|
|
20
18
|
name: input.name,
|
|
21
19
|
email: input.email,
|
|
22
|
-
emailVerifiedAt: input.emailVerified ? /* @__PURE__ */ new Date() : null
|
|
23
|
-
...withRole && input.role ? { role: input.role } : {}
|
|
20
|
+
emailVerifiedAt: input.emailVerified ? /* @__PURE__ */ new Date() : null
|
|
24
21
|
}).returning();
|
|
25
22
|
if (!user) {
|
|
26
23
|
throw apiError(500, "internal_error", "Failed to create the user.");
|
|
@@ -9,7 +9,7 @@ const bodySchema = z.object({
|
|
|
9
9
|
avatar: avatarField().optional()
|
|
10
10
|
});
|
|
11
11
|
export default defineEventHandler(async (event) => {
|
|
12
|
-
const user = await
|
|
12
|
+
const { user, kind } = await authorize(event, "profile:write");
|
|
13
13
|
const { name, avatar } = await readValidatedBody(event, bodySchema.parse);
|
|
14
14
|
const [updated] = await db.update(schema.users).set({
|
|
15
15
|
...name !== void 0 ? { name } : {},
|
|
@@ -17,6 +17,6 @@ export default defineEventHandler(async (event) => {
|
|
|
17
17
|
updatedAt: /* @__PURE__ */ new Date()
|
|
18
18
|
}).where(eq(schema.users.id, user.id)).returning();
|
|
19
19
|
if (!updated) throw notFound("User not found.");
|
|
20
|
-
await setUserSession(event, { user: mapUserToSession(updated) });
|
|
20
|
+
if (kind === "session") await setUserSession(event, { user: mapUserToSession(updated) });
|
|
21
21
|
return toProfileDto(updated);
|
|
22
22
|
});
|
|
@@ -1,96 +1,70 @@
|
|
|
1
1
|
import type { H3Event } from 'h3';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
target?: {
|
|
19
|
-
id: number;
|
|
20
|
-
email: string;
|
|
21
|
-
role?: string;
|
|
22
|
-
emailVerifiedAt?: Date | null;
|
|
23
|
-
};
|
|
24
|
-
/** Set to `true` to allow. Denied by default. */
|
|
25
|
-
allowed: boolean;
|
|
2
|
+
import { schema } from '@nuxthub/db';
|
|
3
|
+
import type { AuthPrincipal, AuthUser } from '@frigear-nu/auth/utils';
|
|
4
|
+
import type { Permission } from '@frigear-nu/auth/access';
|
|
5
|
+
/** What a staff member does in the users admin; each maps to one permission (`USERS_PERMISSIONS`). */
|
|
6
|
+
export type UsersAdminAction = 'view' | 'list' | 'create' | 'update' | 'delete' | 'manage';
|
|
7
|
+
/**
|
|
8
|
+
* The permissions of the users admin, by action. `view` reads one user, `list` the directory (and the dashboard
|
|
9
|
+
* numbers); `manage` covers what touches someone's sign-in: changing or verifying their email, emailing a sign-in link.
|
|
10
|
+
*/
|
|
11
|
+
export declare const USERS_PERMISSIONS: {
|
|
12
|
+
readonly view: "users:read";
|
|
13
|
+
readonly list: "users:list";
|
|
14
|
+
readonly create: "users:create";
|
|
15
|
+
readonly update: "users:update";
|
|
16
|
+
readonly delete: "users:delete";
|
|
17
|
+
readonly manage: "users:manage";
|
|
26
18
|
};
|
|
27
|
-
/**
|
|
28
|
-
export
|
|
19
|
+
/** The permission to read one user (`GET /api/admin/users/:id` and the routes other modules add below it). */
|
|
20
|
+
export declare const USERS_READ_PERMISSION: "users:read";
|
|
21
|
+
/** The permission for the actions that touch someone's sign-in (email, sign-in links). Sessions only. */
|
|
22
|
+
export declare const USERS_MANAGE_PERMISSION: "users:manage";
|
|
23
|
+
/** A stored user, as `loadUsersAdminTarget` returns it. */
|
|
24
|
+
export type UsersAdminTarget = typeof schema.users.$inferSelect;
|
|
25
|
+
export interface UsersAdminTargetOptions {
|
|
29
26
|
/**
|
|
30
|
-
*
|
|
31
|
-
*
|
|
27
|
+
* Authorize this permission instead of the action's own (`USERS_PERMISSIONS[action]`), for routes other modules add
|
|
28
|
+
* below `/api/admin/users/:id/` (`subscriptions:manage`). The action still decides whether target protection applies:
|
|
29
|
+
* every action but `view` is a write.
|
|
32
30
|
*/
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
/** The scope that lets an API token or OAuth access token read the user directory. Staff only (see the module). */
|
|
36
|
-
export declare const USERS_READ_SCOPE = "users:read";
|
|
37
|
-
/** The permission to create, change and delete users (role-based access control). Sessions only. */
|
|
38
|
-
export declare const USERS_MANAGE_PERMISSION = "users:manage";
|
|
39
|
-
export type UsersAdminRolesContext = {
|
|
40
|
-
event: H3Event;
|
|
41
|
-
/** The signed-in user making the request. */
|
|
42
|
-
userId: number;
|
|
43
|
-
/** The roles this user may assign, in display order. Replace it to narrow or extend the default (roles already in use). */
|
|
44
|
-
roles: string[];
|
|
45
|
-
};
|
|
46
|
-
/** Whether another module added a `role` column to `users` (`@frigear-nu/authorization`). */
|
|
47
|
-
export declare const usersHaveRoles: () => boolean;
|
|
48
|
-
/** Whether the host policy lets `userId` view the users admin: who may hold `users:read`. */
|
|
49
|
-
export declare const isUsersAdminViewer: (event: H3Event, userId: number) => any;
|
|
31
|
+
permission?: Permission;
|
|
32
|
+
}
|
|
50
33
|
/**
|
|
51
|
-
*
|
|
52
|
-
*
|
|
34
|
+
* Authorizes the caller for a users admin action (`USERS_PERMISSIONS[action]`, through `authorize`) and returns the
|
|
35
|
+
* caller's user. Throws 401 `unauthorized`, or 403 `session_required` / `insufficient_scope` / `forbidden`.
|
|
53
36
|
*/
|
|
54
|
-
export declare function
|
|
55
|
-
allowed: any;
|
|
56
|
-
user: any;
|
|
57
|
-
}>;
|
|
37
|
+
export declare function authorizeUsersAdmin(event: H3Event, action: UsersAdminAction): Promise<AuthUser>;
|
|
58
38
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
39
|
+
* The permissions `targetId` holds that `actor` does not (empty when the actor holds them all, or acts on themselves).
|
|
40
|
+
* The target's permissions are their roles' (assigned, default, `auto` and `authorization:roles`) plus `implicit`, as
|
|
41
|
+
* `getUserPermissions` resolves them; sensitive ones count by name. The actor holds a permission through their roles or
|
|
42
|
+
* the `authorization:before` hook. An unknown target holds nothing. Throws 403 `forbidden` when the target's roles
|
|
43
|
+
* cannot be resolved (the role provider, an `authorization:roles` listener or a requirement threw): fail closed.
|
|
61
44
|
*/
|
|
62
|
-
export declare function
|
|
45
|
+
export declare function usersAdminTargetMissing(event: H3Event, actor: AuthUser, targetId: number): Promise<string[]>;
|
|
63
46
|
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
47
|
+
* Target protection: staff may only change a user who holds no permission the staff member lacks, so a coordinator
|
|
48
|
+
* cannot edit or delete an admin. Hard-coded, not a policy: no hook or policy can turn it off. Throws 403 `forbidden`.
|
|
66
49
|
*/
|
|
67
|
-
export declare function
|
|
50
|
+
export declare function assertUsersAdminTargetProtected(event: H3Event, actor: AuthUser, targetId: number): Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* Loads the user a staff member acts on (`/api/admin/users/:id/...`) and authorizes the action against them. For the
|
|
53
|
+
* module's own routes and the routes other modules add with `extendUsersAdmin`.
|
|
54
|
+
*
|
|
55
|
+
* Authorizes before it looks anything up: 401 / 403 when the caller may not do the action at all, then 400 for a
|
|
56
|
+
* malformed id, 404 for an unknown user, 403 when a policy of the permission denies it on this user, and, for every
|
|
57
|
+
* action but `view`, 403 `forbidden` when the target holds a permission the caller does not (target protection).
|
|
58
|
+
*/
|
|
59
|
+
export declare function loadUsersAdminTarget(event: H3Event, action: Exclude<UsersAdminAction, 'create' | 'list'>, options?: UsersAdminTargetOptions): Promise<{
|
|
60
|
+
actor: AuthUser;
|
|
61
|
+
principal: AuthPrincipal;
|
|
62
|
+
target: UsersAdminTarget;
|
|
63
|
+
}>;
|
|
64
|
+
/** Whether the caller may do a write `action` to `target`: the permission (with its policies) and target protection. */
|
|
65
|
+
export declare function canUsersAdminTarget(event: H3Event, action: Exclude<UsersAdminAction, 'view' | 'list' | 'create'>, target: UsersAdminTarget): Promise<boolean>;
|
|
68
66
|
/** Latest subscription per user, when a subscriptions table is installed (`@frigear-nu/subscriptions`); else empty. */
|
|
69
67
|
export declare function latestSubscriptions(userIds: number[]): Promise<Map<number, {
|
|
70
68
|
planKey: string | null;
|
|
71
69
|
status: string;
|
|
72
70
|
}>>;
|
|
73
|
-
/** The policy view of a stored user: what the `users:admin:authorize` hook sees as `target`. */
|
|
74
|
-
export declare const usersAdminTargetInfo: (user: {
|
|
75
|
-
id: number;
|
|
76
|
-
email: string;
|
|
77
|
-
emailVerifiedAt?: Date | null;
|
|
78
|
-
}) => {
|
|
79
|
-
id: number;
|
|
80
|
-
email: string;
|
|
81
|
-
role: string | undefined;
|
|
82
|
-
emailVerifiedAt: Date | null;
|
|
83
|
-
};
|
|
84
|
-
/**
|
|
85
|
-
* Loads the user a staff member is acting on (`/api/admin/users/:id/...`) and runs the users admin policy against
|
|
86
|
-
* them (`view` for reads, `update` for changes). For routes added with `extendUsersAdmin`.
|
|
87
|
-
*
|
|
88
|
-
* `options.scopes` lets bearer credentials with those scopes in for `view` (see `UsersAdminCallerOptions`).
|
|
89
|
-
*
|
|
90
|
-
* Authorizes before it looks anything up: 401 without a session, 403 when the host denies `action` outright, then
|
|
91
|
-
* 400 for a malformed id, 404 for an unknown user, and 403 again when the host denies `action` on this target.
|
|
92
|
-
*/
|
|
93
|
-
export declare function loadUsersAdminTarget(event: H3Event, action: Exclude<UsersAdminAction, 'create'>, options?: UsersAdminCallerOptions): Promise<{
|
|
94
|
-
actor: any;
|
|
95
|
-
target: any;
|
|
96
|
-
}>;
|
|
@@ -1,42 +1,66 @@
|
|
|
1
1
|
import { db, schema } from "@nuxthub/db";
|
|
2
|
-
import { desc,
|
|
3
|
-
import { intIdParams, notFound } from "@frigear-nu/module-kit/server";
|
|
4
|
-
import {
|
|
5
|
-
export const
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
assert: (event, userId, message, extra) => (extra.action === "view" ? usersViewGate : usersManageGate).assert(event, userId, message, extra)
|
|
2
|
+
import { desc, inArray } from "drizzle-orm";
|
|
3
|
+
import { forbidden, intIdParams, notFound } from "@frigear-nu/module-kit/server";
|
|
4
|
+
import { usersAccess } from "../../access.js";
|
|
5
|
+
export const USERS_PERMISSIONS = {
|
|
6
|
+
view: usersAccess.permissions.read,
|
|
7
|
+
list: usersAccess.permissions.list,
|
|
8
|
+
create: usersAccess.permissions.create,
|
|
9
|
+
update: usersAccess.permissions.update,
|
|
10
|
+
delete: usersAccess.permissions.delete,
|
|
11
|
+
manage: usersAccess.permissions.manage
|
|
13
12
|
};
|
|
14
|
-
const
|
|
15
|
-
export const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const principal = await requireAuth(event);
|
|
19
|
-
const user = principal.user;
|
|
20
|
-
const bearerAllowed = action === "view" && !!options.scopes?.length && principalHasScopes(principal, options.scopes);
|
|
21
|
-
if (principal.kind !== "session" && !bearerAllowed) return { allowed: false, user };
|
|
22
|
-
const allowed = await usersAdminGate.isAllowed(event, user.id, { action, ...details });
|
|
23
|
-
return { allowed, user };
|
|
13
|
+
export const USERS_READ_PERMISSION = USERS_PERMISSIONS.view;
|
|
14
|
+
export const USERS_MANAGE_PERMISSION = USERS_PERMISSIONS.manage;
|
|
15
|
+
export async function authorizeUsersAdmin(event, action) {
|
|
16
|
+
return (await authorize(event, USERS_PERMISSIONS[action])).user;
|
|
24
17
|
}
|
|
25
|
-
export async function
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return
|
|
18
|
+
export async function usersAdminTargetMissing(event, actor, targetId) {
|
|
19
|
+
if (String(actor.id) === String(targetId)) return [];
|
|
20
|
+
const target = await loadAuthUser(targetId);
|
|
21
|
+
if (!target) return [];
|
|
22
|
+
try {
|
|
23
|
+
await getEffectiveRoles(event, target, { strict: true });
|
|
24
|
+
} catch (error) {
|
|
25
|
+
console.error(`[users] the roles of user ${targetId} could not be resolved, refusing to act on them`, error);
|
|
26
|
+
throw forbidden("You cannot change this user right now: their roles could not be checked.");
|
|
27
|
+
}
|
|
28
|
+
const [targetHeld, actorHeld] = await Promise.all([
|
|
29
|
+
getUserPermissions(event, target),
|
|
30
|
+
getUserPermissions(event, actor)
|
|
31
|
+
]);
|
|
32
|
+
const held = new Set(actorHeld);
|
|
33
|
+
const missing = [];
|
|
34
|
+
for (const permission of targetHeld) {
|
|
35
|
+
if (held.has(permission)) continue;
|
|
36
|
+
if (!await subjectAllowed(event, actor, permission)) missing.push(permission);
|
|
37
|
+
}
|
|
38
|
+
return missing;
|
|
39
|
+
}
|
|
40
|
+
export async function assertUsersAdminTargetProtected(event, actor, targetId) {
|
|
41
|
+
const missing = await usersAdminTargetMissing(event, actor, targetId);
|
|
42
|
+
if (missing.length) {
|
|
43
|
+
throw forbidden("You cannot change a user who holds permissions you do not have.", { missing });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export async function loadUsersAdminTarget(event, action, options = {}) {
|
|
47
|
+
const permission = options.permission ?? USERS_PERMISSIONS[action];
|
|
48
|
+
await authorize(event, permission);
|
|
49
|
+
const { id } = await getValidatedRouterParams(event, intIdParams().parse);
|
|
50
|
+
const target = await db.query.users.findFirst({ where: (t, { eq }) => eq(t.id, id) });
|
|
51
|
+
if (!target) throw notFound("User not found.");
|
|
52
|
+
const principal = await authorize(event, permission, target);
|
|
53
|
+
if (action !== "view") await assertUsersAdminTargetProtected(event, principal.user, target.id);
|
|
54
|
+
return { actor: principal.user, principal, target };
|
|
29
55
|
}
|
|
30
|
-
export async function
|
|
31
|
-
|
|
32
|
-
if (
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
56
|
+
export async function canUsersAdminTarget(event, action, target) {
|
|
57
|
+
const principal = await getAuth(event);
|
|
58
|
+
if (!principal || !await allows(event, USERS_PERMISSIONS[action], target)) return false;
|
|
59
|
+
try {
|
|
60
|
+
return !(await usersAdminTargetMissing(event, principal.user, target.id)).length;
|
|
61
|
+
} catch {
|
|
62
|
+
return false;
|
|
36
63
|
}
|
|
37
|
-
const context = { event, userId, roles };
|
|
38
|
-
await useNitroApp().hooks.callHook("users:admin:roles", context);
|
|
39
|
-
return [...new Set(context.roles)];
|
|
40
64
|
}
|
|
41
65
|
export async function latestSubscriptions(userIds) {
|
|
42
66
|
const result = /* @__PURE__ */ new Map();
|
|
@@ -52,17 +76,3 @@ export async function latestSubscriptions(userIds) {
|
|
|
52
76
|
}
|
|
53
77
|
return result;
|
|
54
78
|
}
|
|
55
|
-
export const usersAdminTargetInfo = (user) => ({
|
|
56
|
-
id: user.id,
|
|
57
|
-
email: user.email,
|
|
58
|
-
role: usersHaveRoles() ? user.role : void 0,
|
|
59
|
-
emailVerifiedAt: user.emailVerifiedAt ?? null
|
|
60
|
-
});
|
|
61
|
-
export async function loadUsersAdminTarget(event, action, options = {}) {
|
|
62
|
-
await authorizeUsersAdmin(event, action, {}, options);
|
|
63
|
-
const { id } = await getValidatedRouterParams(event, intIdParams().parse);
|
|
64
|
-
const target = await db.query.users.findFirst({ where: (t, { eq }) => eq(t.id, id) });
|
|
65
|
-
if (!target) throw notFound("User not found.");
|
|
66
|
-
const actor = await authorizeUsersAdmin(event, action, { target: usersAdminTargetInfo(target), input: {} }, options);
|
|
67
|
-
return { actor, target };
|
|
68
|
-
}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import type { AdminUserDto, ProfileDto } from '../../../types.js';
|
|
2
|
-
/** The columns the DTOs read; `
|
|
2
|
+
/** The columns the DTOs read; `emailVerifiedAt` and `lastLoginAt` come from other modules' extensions. */
|
|
3
3
|
type UserRowLike = {
|
|
4
4
|
id: number;
|
|
5
5
|
name: string;
|
|
6
6
|
email: string;
|
|
7
7
|
avatar?: string | null;
|
|
8
|
-
role?: string | null;
|
|
9
8
|
emailVerifiedAt?: Date | number | string | null;
|
|
10
9
|
lastLoginAt?: Date | number | string | null;
|
|
11
10
|
createdAt: Date | number | string;
|
|
@@ -4,7 +4,6 @@ export function toAdminUserDto(user) {
|
|
|
4
4
|
id: user.id,
|
|
5
5
|
name: user.name,
|
|
6
6
|
email: user.email,
|
|
7
|
-
...usersHaveRoles() && user.role ? { role: user.role } : {},
|
|
8
7
|
avatar: user.avatar ?? null,
|
|
9
8
|
emailVerifiedAt: isoDate(user.emailVerifiedAt),
|
|
10
9
|
lastLoginAt: isoDate(user.lastLoginAt),
|
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import type { H3Event } from 'h3';
|
|
2
|
-
|
|
2
|
+
/** How `requireUser` lets callers in. Authentication only: check what the caller may do with `authorize`. */
|
|
3
|
+
export type RequireUserAuthOptions = {
|
|
4
|
+
/** Reject bearer credentials (user tokens, OAuth access tokens). Use for account-level actions. */
|
|
5
|
+
sessionOnly?: boolean;
|
|
6
|
+
};
|
|
3
7
|
/**
|
|
4
|
-
* The signed-in user, or a thrown 401
|
|
5
|
-
*
|
|
8
|
+
* The signed-in user, or a thrown 401 (403 `session_required` with `sessionOnly` and a bearer credential). It only says
|
|
9
|
+
* who is calling: authorize what they do with `authorize(event, permission)`, which also returns the principal.
|
|
6
10
|
*/
|
|
7
|
-
export declare function requireUser(event: H3Event, options?:
|
|
11
|
+
export declare function requireUser(event: H3Event, options?: RequireUserAuthOptions): Promise<any>;
|
|
8
12
|
/**
|
|
9
13
|
* The caller's user when there is one, otherwise `null` (never throws). For routes that are open to everyone but
|
|
10
|
-
* personalise for a signed-in user.
|
|
14
|
+
* personalise for a signed-in user. Authentication only: a bearer credential counts whatever it may do, so check a
|
|
15
|
+
* permission with `allows(event, permission)` before using it for anything beyond the caller's identity.
|
|
11
16
|
*/
|
|
12
|
-
export declare function getUser(event: H3Event
|
|
17
|
+
export declare function getUser(event: H3Event): Promise<any>;
|
|
@@ -1,9 +1,6 @@
|
|
|
1
|
-
import { principalHasScopes } from "@frigear-nu/auth/utils";
|
|
2
1
|
export async function requireUser(event, options = {}) {
|
|
3
|
-
return (await requireAuth(event, options)).user;
|
|
2
|
+
return (await requireAuth(event, { sessionOnly: options.sessionOnly })).user;
|
|
4
3
|
}
|
|
5
|
-
export async function getUser(event
|
|
6
|
-
|
|
7
|
-
if (!principal) return null;
|
|
8
|
-
return !options.scopes?.length || principalHasScopes(principal, options.scopes) ? principal.user : null;
|
|
4
|
+
export async function getUser(event) {
|
|
5
|
+
return (await getAuth(event))?.user ?? null;
|
|
9
6
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AnyColumn } from 'drizzle-orm';
|
|
2
|
+
/** The `authorization_user_roles` table, when `@frigear-nu/authorization` registered it; else `undefined`. */
|
|
3
|
+
export declare function usersRoleAssignments(): {
|
|
4
|
+
userId: AnyColumn;
|
|
5
|
+
role: AnyColumn;
|
|
6
|
+
} | undefined;
|
|
7
|
+
/** A role the users list can be filtered by. */
|
|
8
|
+
export interface UsersRoleOption {
|
|
9
|
+
value: string;
|
|
10
|
+
label: string;
|
|
11
|
+
labelKey?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The roles that can be stored on a user (configured, not `auto`, not a default role), for the list filter. Default and
|
|
15
|
+
* `auto` roles are held without a stored row, so filtering by them would find nobody.
|
|
16
|
+
*/
|
|
17
|
+
export declare function usersStoredRoleOptions(): UsersRoleOption[];
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { schema } from "@nuxthub/db";
|
|
2
|
+
import { table } from "#auth/roles";
|
|
3
|
+
export function usersRoleAssignments() {
|
|
4
|
+
return schema.authorizationUserRoles;
|
|
5
|
+
}
|
|
6
|
+
export function usersStoredRoleOptions() {
|
|
7
|
+
return Object.values(table.roles).filter((role) => !role.auto && !role.default).map((role) => ({ value: role.name, label: role.label, ...role.labelKey ? { labelKey: role.labelKey } : {} })).sort((a, b) => a.label.localeCompare(b.label));
|
|
8
|
+
}
|
|
@@ -3,7 +3,7 @@ export type { AdminUserDto, ProfileDto };
|
|
|
3
3
|
/** The users API: self-service under `/api/users`, staff under `/api/admin/users`. */
|
|
4
4
|
export declare const usersApi: {
|
|
5
5
|
readonly me: {
|
|
6
|
-
/** `PATCH { name, avatar? }`: updates the caller's profile, answers the profile DTO.
|
|
6
|
+
/** `PATCH { name, avatar? }`: updates the caller's profile, answers the profile DTO. `profile:write` (implicit). */
|
|
7
7
|
readonly profile: "/api/users/me";
|
|
8
8
|
/** `PUT { email }`: changes the caller's email (or emails a confirmation link with `verifyEmailChange`). Session only. */
|
|
9
9
|
readonly email: "/api/users/me/email";
|
|
@@ -17,7 +17,7 @@ export declare const usersApi: {
|
|
|
17
17
|
/** `GET ?code=` (preview) and `POST { code }` (restore the old address). The code is the proof, no sign-in needed. */
|
|
18
18
|
readonly emailChangeRevert: "/api/users/email-change/revert";
|
|
19
19
|
readonly admin: {
|
|
20
|
-
/** `GET` (paginated list, `useTableQuery` keys plus `role`, `verified`) and `POST` (create, 201). */
|
|
20
|
+
/** `GET` (paginated list, `users:list`; `useTableQuery` keys plus `role`, `verified`) and `POST` (create, `users:create`, 201). */
|
|
21
21
|
readonly users: "/api/admin/users";
|
|
22
22
|
/** `GET` (detail), `PATCH` (edit) and `DELETE` (204). */
|
|
23
23
|
readonly user: (id: number | string) => string;
|
|
@@ -27,7 +27,5 @@ export declare const usersApi: {
|
|
|
27
27
|
readonly new: "/api/admin/users/new";
|
|
28
28
|
/** `GET`: `{ total, newUsers, days }` (dashboard). */
|
|
29
29
|
readonly stats: "/api/admin/users/stats";
|
|
30
|
-
/** `GET`: `{ roles }` the caller may assign. */
|
|
31
|
-
readonly roles: "/api/admin/users/roles";
|
|
32
30
|
};
|
|
33
31
|
};
|
|
@@ -2,7 +2,7 @@ const base = "/api/users";
|
|
|
2
2
|
const adminBase = "/api/admin/users";
|
|
3
3
|
export const usersApi = {
|
|
4
4
|
me: {
|
|
5
|
-
/** `PATCH { name, avatar? }`: updates the caller's profile, answers the profile DTO.
|
|
5
|
+
/** `PATCH { name, avatar? }`: updates the caller's profile, answers the profile DTO. `profile:write` (implicit). */
|
|
6
6
|
profile: `${base}/me`,
|
|
7
7
|
/** `PUT { email }`: changes the caller's email (or emails a confirmation link with `verifyEmailChange`). Session only. */
|
|
8
8
|
email: `${base}/me/email`,
|
|
@@ -16,7 +16,7 @@ export const usersApi = {
|
|
|
16
16
|
/** `GET ?code=` (preview) and `POST { code }` (restore the old address). The code is the proof, no sign-in needed. */
|
|
17
17
|
emailChangeRevert: `${base}/email-change/revert`,
|
|
18
18
|
admin: {
|
|
19
|
-
/** `GET` (paginated list, `useTableQuery` keys plus `role`, `verified`) and `POST` (create, 201). */
|
|
19
|
+
/** `GET` (paginated list, `users:list`; `useTableQuery` keys plus `role`, `verified`) and `POST` (create, `users:create`, 201). */
|
|
20
20
|
users: adminBase,
|
|
21
21
|
/** `GET` (detail), `PATCH` (edit) and `DELETE` (204). */
|
|
22
22
|
user: (id) => `${adminBase}/${encodeURIComponent(String(id))}`,
|
|
@@ -25,8 +25,6 @@ export const usersApi = {
|
|
|
25
25
|
/** `GET`: the newest sign-ups of the last 30 days (dashboard). */
|
|
26
26
|
new: `${adminBase}/new`,
|
|
27
27
|
/** `GET`: `{ total, newUsers, days }` (dashboard). */
|
|
28
|
-
stats: `${adminBase}/stats
|
|
29
|
-
/** `GET`: `{ roles }` the caller may assign. */
|
|
30
|
-
roles: `${adminBase}/roles`
|
|
28
|
+
stats: `${adminBase}/stats`
|
|
31
29
|
}
|
|
32
30
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frigear-nu/users",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.1.0",
|
|
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/identity/users",
|
|
6
6
|
"repository": {
|
|
@@ -34,11 +34,11 @@
|
|
|
34
34
|
"playground"
|
|
35
35
|
],
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@frigear-nu/auth": "^0.
|
|
38
|
-
"@frigear-nu/mcp": "^0.
|
|
39
|
-
"@frigear-nu/module-kit": "^1.3.
|
|
40
|
-
"@frigear-nu/notify": "^0.2.
|
|
41
|
-
"@frigear-nu/ui": "^0.2.
|
|
37
|
+
"@frigear-nu/auth": "^0.6.0",
|
|
38
|
+
"@frigear-nu/mcp": "^0.5.0",
|
|
39
|
+
"@frigear-nu/module-kit": "^1.3.5",
|
|
40
|
+
"@frigear-nu/notify": "^0.2.5",
|
|
41
|
+
"@frigear-nu/ui": "^0.2.6",
|
|
42
42
|
"@libsql/client": "^0.18.0",
|
|
43
43
|
"@nuxt/kit": "^4.6.4",
|
|
44
44
|
"drizzle-kit": "^0.31.11",
|
|
@@ -48,9 +48,9 @@
|
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
50
|
"@frigear-nu/admin": ">=0.0.0",
|
|
51
|
-
"@frigear-nu/email-templates": "^0.1.
|
|
52
|
-
"@frigear-nu/menu": "^0.
|
|
53
|
-
"@frigear-nu/widget": "^0.
|
|
51
|
+
"@frigear-nu/email-templates": "^0.1.1",
|
|
52
|
+
"@frigear-nu/menu": "^0.4.0",
|
|
53
|
+
"@frigear-nu/widget": "^0.4.0",
|
|
54
54
|
"@nuxt/ui": "^4.12.0",
|
|
55
55
|
"@nuxthub/core": "^0.10.12"
|
|
56
56
|
},
|
|
@@ -73,10 +73,10 @@
|
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"@electric-sql/pglite": "^0.5.15",
|
|
76
|
-
"@frigear-nu/admin": "^0.
|
|
77
|
-
"@frigear-nu/email-templates": "^0.1.
|
|
78
|
-
"@frigear-nu/menu": "^0.
|
|
79
|
-
"@frigear-nu/widget": "^0.
|
|
76
|
+
"@frigear-nu/admin": "^0.5.0",
|
|
77
|
+
"@frigear-nu/email-templates": "^0.1.1",
|
|
78
|
+
"@frigear-nu/menu": "^0.4.0",
|
|
79
|
+
"@frigear-nu/widget": "^0.4.0",
|
|
80
80
|
"@nuxt/devtools": "^4.1.0",
|
|
81
81
|
"@nuxt/eslint-config": "^1.17.0",
|
|
82
82
|
"@nuxt/module-builder": "^1.0.3",
|