@frigear-nu/users 2.0.0 → 3.0.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.
Files changed (39) hide show
  1. package/README.md +6 -3
  2. package/dist/module.d.mts +3 -13
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +14 -8
  5. package/dist/runtime/admin-menus.js +3 -1
  6. package/dist/runtime/app/components/UserCreateSlideover.d.vue.ts +3 -6
  7. package/dist/runtime/app/components/UserCreateSlideover.vue +3 -21
  8. package/dist/runtime/app/components/UserCreateSlideover.vue.d.ts +3 -6
  9. package/dist/runtime/app/composables/useUserActions.d.ts +1 -3
  10. package/dist/runtime/app/composables/useUserActions.js +2 -2
  11. package/dist/runtime/app/pages/admin.vue +8 -8
  12. package/dist/runtime/app/tabs/Overview.vue +10 -30
  13. package/dist/runtime/app/utils/admin-user.d.ts +11 -3
  14. package/dist/runtime/i18n/lang/da.json +13 -4
  15. package/dist/runtime/i18n/lang/en.json +13 -4
  16. package/dist/runtime/server/mcp/tools/get-my-profile.js +1 -1
  17. package/dist/runtime/server/routes/admin/new.get.js +1 -1
  18. package/dist/runtime/server/routes/admin/stats.get.js +1 -1
  19. package/dist/runtime/server/routes/admin/user-resend.post.js +1 -1
  20. package/dist/runtime/server/routes/admin/user.get.js +6 -9
  21. package/dist/runtime/server/routes/admin/user.patch.js +2 -8
  22. package/dist/runtime/server/routes/admin/users.get.js +21 -13
  23. package/dist/runtime/server/routes/admin/users.post.js +2 -5
  24. package/dist/runtime/server/routes/me/profile.patch.js +2 -2
  25. package/dist/runtime/server/utils/admin.d.ts +54 -81
  26. package/dist/runtime/server/utils/admin.js +57 -48
  27. package/dist/runtime/server/utils/dto.d.ts +1 -2
  28. package/dist/runtime/server/utils/dto.js +0 -1
  29. package/dist/runtime/server/utils/require-user.d.ts +11 -6
  30. package/dist/runtime/server/utils/require-user.js +3 -6
  31. package/dist/runtime/server/utils/roles.d.ts +17 -0
  32. package/dist/runtime/server/utils/roles.js +8 -0
  33. package/dist/runtime/utils/api.d.ts +2 -4
  34. package/dist/runtime/utils/api.js +3 -5
  35. package/package.json +13 -13
  36. package/dist/runtime/server/plugins/users-read-scope.d.ts +0 -2
  37. package/dist/runtime/server/plugins/users-read-scope.js +0 -6
  38. package/dist/runtime/server/routes/admin/roles.get.d.ts +0 -2
  39. package/dist/runtime/server/routes/admin/roles.get.js +0 -4
package/README.md CHANGED
@@ -10,11 +10,14 @@ change about themselves. How people sign in lives in [`@frigear-nu/auth`](../aut
10
10
 
11
11
  ## Features
12
12
 
13
- - ⛰ The `users` table and its schema, extended by other modules (credentials by `auth`, `role` by `authorization`, ...).
13
+ - ⛰ The `users` table and its schema, extended by other modules (credentials by `auth`, ...).
14
14
  - 🛠 Staff administration (`settings.admin`): list, create, edit, delete and re-invite users, a "new users" widget and
15
- an admin page (with `@frigear-nu/admin`). Policy is the host's, through the `users:admin:authorize` hook.
15
+ an admin page (with `@frigear-nu/admin`). Access is by permission (`users:read`, `users:list`, `users:create`,
16
+ `users:update`, `users:delete`, `users:manage`), granted through roles; staff can never change a user who holds a
17
+ permission they lack. Roles themselves are assigned through `@frigear-nu/authorization`.
16
18
  - 🧑 Self-service: change profile, email (optionally confirmed from the inbox) and password.
17
- - 🧩 `requireUser` / `getUser` for server routes, and `extendUsersAdmin` for modules that add to the admin user page.
19
+ - 🧩 `requireUser` / `getUser` (authentication only) for server routes, and `extendUsersAdmin` plus
20
+ `loadUsersAdminTarget` for modules that add to the admin user page.
18
21
  - 🔌 Registers the user store `@frigear-nu/auth` reads and writes users through.
19
22
 
20
23
  ## Quick Setup
package/dist/module.d.mts CHANGED
@@ -1,5 +1,4 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
- import { UsersAdminContext, UsersAdminRolesContext } from '../dist/runtime/server/utils/admin.js';
3
2
 
4
3
  type PublicModuleOptions = {
5
4
  /** Where the page of the signed-in user's profile lives; the email change confirmation link lands there. */
@@ -14,8 +13,9 @@ type ModuleOptions = {
14
13
  settings?: {
15
14
  /**
16
15
  * User administration for staff: list/create/edit users (`/api/admin/users`), a "new users" widget and an
17
- * admin page. Who may do what is decided by the host in the `users:admin:authorize` Nitro hook (denied by
18
- * default). `page` is the admin page path (`true` = `/admin/users`, `false` = no page).
16
+ * admin page. Who may do what is decided by the permissions `users:read`, `users:list`, `users:create`,
17
+ * `users:update`, `users:delete` and `users:manage` (grant them to roles). `page` is the admin page path
18
+ * (`true` = `/admin/users`, `false` = no page).
19
19
  */
20
20
  admin?: boolean | {
21
21
  page?: string | boolean;
@@ -38,8 +38,6 @@ type AdminUserDto = {
38
38
  id: number;
39
39
  name: string;
40
40
  email: string;
41
- /** Only when an authorization module added the `role` column. */
42
- role?: string;
43
41
  avatar: string | null;
44
42
  emailVerifiedAt: string | null;
45
43
  lastLoginAt: string | null;
@@ -54,14 +52,6 @@ type ProfileDto = {
54
52
  emailVerifiedAt: string | null;
55
53
  };
56
54
 
57
- declare module 'nitropack' {
58
- interface NitroRuntimeHooks {
59
- /** Staff gate of the users admin (`settings.admin`): set `ctx.allowed = true` to allow `ctx.action`. Denied by default. */
60
- 'users:admin:authorize': (ctx: UsersAdminContext) => void | Promise<void>;
61
- /** Roles the signed-in user may assign in the users admin: set `ctx.roles`. Defaults to the roles in use. */
62
- 'users:admin:roles': (ctx: UsersAdminRolesContext) => void | Promise<void>;
63
- }
64
- }
65
55
  declare module 'nuxt/schema' {
66
56
  interface NuxtConfig {
67
57
  users?: ModuleOptions;
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@frigear-nu/users",
3
3
  "configKey": "users",
4
- "version": "2.0.0",
4
+ "version": "3.0.0",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "unknown"
package/dist/module.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { defineNuxtModule, createResolver, addServerImportsDir, hasNuxtModule, addServerPlugin } from '@nuxt/kit';
1
+ import { defineNuxtModule, createResolver, addServerImportsDir, hasNuxtModule } from '@nuxt/kit';
2
2
  import { registerTailwindSource, registerLocales, registerDatabaseTable, inlineModuleRuntime, addModulePages, addModuleRoutes, resolvePagePath, addOptionalMenuSource } from '@frigear-nu/module-kit/utils';
3
- import { setAuthUserStore, addAuthScope } from '@frigear-nu/auth/utils';
3
+ import { addPermission, setAuthUserStore } from '@frigear-nu/auth/utils';
4
4
 
5
5
  const module$1 = defineNuxtModule({
6
6
  meta: { name: "@frigear-nu/users", configKey: "users" },
@@ -47,6 +47,11 @@ const module$1 = defineNuxtModule({
47
47
  resolver,
48
48
  schema: (dialect) => `./runtime/db/schema.${dialect}`
49
49
  });
50
+ addPermission(
51
+ nuxt,
52
+ { name: "profile:read", label: "Read your profile", labelKey: "users.permissions.profileRead", description: "Read your own name, email and avatar.", group: "profile", implicit: true },
53
+ { name: "profile:write", label: "Change your profile", labelKey: "users.permissions.profileWrite", description: "Change your own name and avatar.", group: "profile", implicit: true }
54
+ );
50
55
  setAuthUserStore(nuxt, resolver.resolve("./runtime/server/user-store"));
51
56
  nuxt.hook("notify:email:templates", (sources) => sources.push({ dir: resolver.resolve("./runtime/emails") }));
52
57
  addServerImportsDir(resolver.resolve("./runtime/server/utils"));
@@ -81,7 +86,6 @@ const module$1 = defineNuxtModule({
81
86
  addModuleRoutes(resolver, selfRoutes, { base: "/api/users" });
82
87
  if (settings.mcp === true) {
83
88
  const { addMcpDefinitions } = await import('@frigear-nu/mcp/utils');
84
- addAuthScope(nuxt, { name: "profile:read", description: "Read your own name, email and role (MCP)", aggregateTo: ["user"] });
85
89
  addMcpDefinitions(nuxt, resolver.resolve("./runtime/server/mcp"));
86
90
  }
87
91
  nuxt.options.runtimeConfig.users = { verifyEmailChange: settings.verifyEmailChange === true };
@@ -93,18 +97,20 @@ const module$1 = defineNuxtModule({
93
97
  }
94
98
  const adminPagePath = withAdmin && withAdminShell ? resolvePagePath(adminOptions.page ?? true, (await import('@frigear-nu/admin/utils')).adminRoute(nuxt, "users")) : void 0;
95
99
  if (withAdmin) {
96
- addAuthScope(
100
+ addPermission(
97
101
  nuxt,
98
- { name: "users:read", description: "Read the user directory (staff only)" },
99
- { name: "users:manage", description: "Create, change and delete users (staff only)", sessionOnly: true }
102
+ { name: "users:read", label: "View users", labelKey: "users.permissions.read", description: "See a user's profile, sign-in methods and what other modules show on the user page.", group: "users" },
103
+ { name: "users:list", label: "List users", labelKey: "users.permissions.list", description: "Search the user directory and see the sign-up numbers.", group: "users" },
104
+ { name: "users:create", label: "Add users", labelKey: "users.permissions.create", description: "Create users and email them a sign-in link.", group: "users" },
105
+ { name: "users:update", label: "Edit users", labelKey: "users.permissions.update", description: "Change a user's name.", group: "users" },
106
+ { name: "users:delete", label: "Delete users", labelKey: "users.permissions.delete", description: "Delete users and their sign-in methods.", group: "users", sessionOnly: true },
107
+ { name: "users:manage", label: "Manage sign-in of users", labelKey: "users.permissions.manage", description: "Change or verify a user's email address and email them a sign-in link.", group: "users", sessionOnly: true }
100
108
  );
101
- addServerPlugin(resolver.resolve("./runtime/server/plugins/users-read-scope"));
102
109
  addModuleRoutes(resolver, [
103
110
  { method: "get", path: "", file: "admin/users.get" },
104
111
  { method: "post", path: "", file: "admin/users.post" },
105
112
  { method: "get", path: "new", file: "admin/new.get" },
106
113
  { method: "get", path: "stats", file: "admin/stats.get" },
107
- { method: "get", path: "roles", file: "admin/roles.get" },
108
114
  { method: "get", path: ":id", file: "admin/user.get" },
109
115
  { method: "patch", path: ":id", file: "admin/user.patch" },
110
116
  { method: "delete", path: ":id", file: "admin/user.delete" },
@@ -11,7 +11,9 @@ export default defineMenuSource(() => {
11
11
  descriptionKey: "users.admin.nav.description",
12
12
  icon: "i-lucide-users",
13
13
  to: adminPage,
14
- order: 10
14
+ order: 10,
15
+ // Hidden (by `menus:filter`) from staff who may not list users; the routes check it themselves.
16
+ permission: "users:list"
15
17
  });
16
18
  }
17
19
  });
@@ -1,11 +1,8 @@
1
1
  import type { UserRow } from '../utils/admin-user.js';
2
- type __VLS_Props = {
3
- roles?: string[];
4
- };
5
- declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
2
+ declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
6
3
  close: (created: false | UserRow) => any;
7
- }, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
4
+ }, string, import("vue").PublicProps, Readonly<{}> & Readonly<{
8
5
  onClose?: ((created: false | UserRow) => any) | undefined;
9
- }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
6
+ }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
10
7
  declare const _default: typeof __VLS_export;
11
8
  export default _default;
@@ -1,29 +1,23 @@
1
1
  <script setup>
2
2
  import { usersApi } from "../../utils/api";
3
3
  import { z } from "zod";
4
- import { $fetch, computed, reactive, useAction, useModuleT } from "#imports";
4
+ import { $fetch, reactive, useAction, useModuleT } from "#imports";
5
5
  defineOptions({ name: "UsersUserCreateSlideover" });
6
- const props = defineProps({
7
- roles: { type: Array, required: false }
8
- });
9
6
  const emit = defineEmits(["close"]);
10
7
  const t = useModuleT("users");
11
8
  const { busy, run } = useAction();
12
9
  const schema = z.object({
13
10
  name: z.string().trim().min(1, t("admin.nameRequired", "Enter a name.")).max(120),
14
11
  email: z.string().trim().email(t("admin.emailInvalid", "Enter a valid email address.")),
15
- role: z.string().optional(),
16
12
  emailVerified: z.boolean(),
17
13
  sendWelcomeEmail: z.boolean()
18
14
  });
19
- const state = reactive({ name: "", email: "", role: void 0, emailVerified: false, sendWelcomeEmail: true });
20
- const roleLabel = (value) => t(`admin.roleNames.${value}`, value.charAt(0).toUpperCase() + value.slice(1));
21
- const roleItems = computed(() => (props.roles ?? []).map((value) => ({ label: roleLabel(value), value })));
15
+ const state = reactive({ name: "", email: "", emailVerified: false, sendWelcomeEmail: true });
22
16
  async function save(event) {
23
17
  const created = await run(
24
18
  () => $fetch(usersApi.admin.users, {
25
19
  method: "POST",
26
- body: { ...event.data, role: roleItems.value.length && event.data.role ? event.data.role : void 0 }
20
+ body: event.data
27
21
  }),
28
22
  { success: t("admin.createdOk", "User created.") }
29
23
  );
@@ -68,18 +62,6 @@ async function save(event) {
68
62
  class="w-full"
69
63
  />
70
64
  </UFormField>
71
- <UFormField
72
- v-if="roleItems.length"
73
- name="role"
74
- :label="t('admin.role', 'Role')"
75
- >
76
- <USelect
77
- v-model="state.role"
78
- :items="roleItems"
79
- class="w-full"
80
- :placeholder="t('admin.rolePlaceholder', 'Select a role')"
81
- />
82
- </UFormField>
83
65
  <UCheckbox
84
66
  v-model="state.emailVerified"
85
67
  :label="t('admin.emailVerified', 'Mark the email address as verified')"
@@ -1,11 +1,8 @@
1
1
  import type { UserRow } from '../utils/admin-user.js';
2
- type __VLS_Props = {
3
- roles?: string[];
4
- };
5
- declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
2
+ declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
6
3
  close: (created: false | UserRow) => any;
7
- }, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
4
+ }, string, import("vue").PublicProps, Readonly<{}> & Readonly<{
8
5
  onClose?: ((created: false | UserRow) => any) | undefined;
9
- }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
6
+ }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
10
7
  declare const _default: typeof __VLS_export;
11
8
  export default _default;
@@ -20,9 +20,7 @@ export interface UserMenuOptions {
20
20
  export declare function useUserActions(): {
21
21
  listPath: import("vue").ComputedRef<any>;
22
22
  userPath: (id: number) => string;
23
- create: (options?: {
24
- roles?: string[];
25
- }) => Promise<UserRow | false>;
23
+ create: () => Promise<UserRow | false>;
26
24
  remove: (user: UserSubject, options?: Pick<UserMenuOptions, "onRemoved">) => Promise<boolean>;
27
25
  resend: (user: UserSubject) => Promise<boolean>;
28
26
  menu: (user: UserSubject, options?: UserMenuOptions) => DropdownMenuItem[][];
@@ -11,8 +11,8 @@ export function useUserActions() {
11
11
  const adminPage = useRuntimeConfig().public.users?.pages?.admin ?? "/admin/users";
12
12
  const listPath = computed(() => localize(adminPage.replace(/\/+$/, "")));
13
13
  const userPath = (id) => `${listPath.value}/${id}`;
14
- async function create(options = {}) {
15
- const created = await overlay.create(UserCreateSlideover).open({ roles: options.roles ?? [] });
14
+ async function create() {
15
+ const created = await overlay.create(UserCreateSlideover).open();
16
16
  if (created) await navigateTo(userPath(created.id));
17
17
  return created;
18
18
  }
@@ -22,9 +22,9 @@ const hasRoles = computed(() => data.value?.hasRoles ?? false);
22
22
  const hasSubscriptions = computed(() => data.value?.hasSubscriptions ?? false);
23
23
  const roles = computed(() => data.value?.roles ?? []);
24
24
  const forbidden = computed(() => [401, 403].includes(error.value?.statusCode ?? 0));
25
- const roleLabel = (value) => t(`admin.roleNames.${value}`, value.charAt(0).toUpperCase() + value.slice(1));
26
- const roleItems = computed(() => roles.value.map((value) => ({ label: roleLabel(value), value })));
27
- const roleFilterItems = computed(() => [{ label: t("admin.filters.allRoles", "All roles"), value: "all" }, ...roleItems.value]);
25
+ const roleLabels = computed(() => new Map(roles.value.map((role) => [role.value, role.label])));
26
+ const roleLabel = (value) => roleLabels.value.get(value) ?? value;
27
+ const roleFilterItems = computed(() => [{ label: t("admin.filters.allRoles", "All roles"), value: "all" }, ...roles.value.map(({ value, label }) => ({ value, label }))]);
28
28
  const pending = computed(() => status.value === "pending");
29
29
  const loading = computed(() => pending.value && !data.value);
30
30
  const refreshing = computed(() => pending.value && !!data.value);
@@ -43,9 +43,9 @@ const columns = computed(() => [
43
43
  })
44
44
  },
45
45
  ...hasRoles.value ? [{
46
- accessorKey: "role",
47
- header: sort.header("role", t("admin.role", "Role")),
48
- cell: ({ row }) => row.original.role ? roleLabel(row.original.role) : emptyCell()
46
+ id: "role",
47
+ header: sort.header("role", t("admin.roles", "Roles")),
48
+ cell: ({ row }) => row.original.roles?.length ? row.original.roles.map(roleLabel).join(", ") : emptyCell()
49
49
  }] : [],
50
50
  ...hasSubscriptions.value ? [{
51
51
  id: "subscription",
@@ -85,7 +85,7 @@ const verifiedOptions = computed(() => [
85
85
  function openUser(_event, row) {
86
86
  return navigateTo(actions.userPath(row.original.id));
87
87
  }
88
- const addUser = () => actions.create({ roles: hasRoles.value ? roles.value : [] });
88
+ const addUser = () => actions.create();
89
89
  </script>
90
90
 
91
91
  <template>
@@ -115,7 +115,7 @@ const addUser = () => actions.create({ roles: hasRoles.value ? roles.value : []
115
115
  class="w-full max-w-sm"
116
116
  icon="i-lucide-search"
117
117
  :loading="pending"
118
- :placeholder="t('admin.search', 'Search name, email or role...')"
118
+ :placeholder="t('admin.search', 'Search name or email...')"
119
119
  />
120
120
  <USelect
121
121
  v-model="filters.verified"
@@ -15,40 +15,33 @@ const overviewWidgets = typeof OverviewWidgets === "string" ? void 0 : OverviewW
15
15
  const schema = z.object({
16
16
  name: z.string().trim().min(1, t("admin.nameRequired", "Enter a name.")).max(120),
17
17
  email: z.string().trim().email(t("admin.emailInvalid", "Enter a valid email address.")),
18
- role: z.string(),
19
18
  emailVerified: z.boolean()
20
19
  });
21
- const form = reactive({ name: "", email: "", role: "", emailVerified: false });
20
+ const form = reactive({ name: "", email: "", emailVerified: false });
22
21
  function fill(value) {
23
- Object.assign(form, { name: value.name, email: value.email, role: value.role ?? "", emailVerified: !!value.emailVerifiedAt });
22
+ Object.assign(form, { name: value.name, email: value.email, emailVerified: !!value.emailVerifiedAt });
24
23
  }
25
24
  fill(props.user);
26
25
  watch(() => props.user, fill);
27
- const roleLabel = (value) => t(`admin.roleNames.${value}`, value.charAt(0).toUpperCase() + value.slice(1));
28
- const roleItems = computed(() => {
29
- const roles = new Set(props.user.roles ?? []);
30
- if (props.user.role) roles.add(props.user.role);
31
- return [...roles].map((value) => ({ label: roleLabel(value), value }));
32
- });
33
26
  const accountFacts = computed(() => [
34
27
  { key: "created", label: t("admin.created", "Created"), value: format.dateTime(props.user.createdAt) },
35
28
  { key: "lastLogin", label: t("admin.lastLogin", "Last sign-in"), value: format.dateTime(props.user.lastLoginAt) || t("admin.detail.never", "Never") },
36
29
  { key: "password", label: t("admin.detail.password", "Password"), value: props.user.hasPassword ? t("admin.detail.set", "Set") : null },
37
30
  { key: "passkeys", label: t("admin.detail.passkeys", "Passkeys"), value: props.user.passkeys }
38
31
  ]);
39
- const dirty = computed(() => form.name !== props.user.name || form.email !== props.user.email || props.user.hasRoles && form.role !== (props.user.role ?? "") || form.emailVerified !== !!props.user.emailVerifiedAt);
32
+ const dirty = computed(() => form.name !== props.user.name || form.email !== props.user.email || form.emailVerified !== !!props.user.emailVerifiedAt);
40
33
  async function save(event) {
41
- const { name, email, role, emailVerified } = event.data;
34
+ const { name, email, emailVerified } = event.data;
42
35
  const emailChanged = email !== props.user.email;
43
36
  const saved = await run(
44
37
  () => $fetch(usersApi.admin.user(props.user.id), {
45
38
  method: "PATCH",
46
39
  body: {
47
40
  name,
48
- email,
49
- ...props.user.hasRoles && role ? { role } : {},
50
- // An unchanged address keeps its state unless staff toggled it; a changed one is verified by email.
51
- ...emailChanged ? {} : { emailVerified }
41
+ ...emailChanged ? { email } : {},
42
+ // An unchanged address keeps its state unless staff toggled it; a changed one is verified by email. Both
43
+ // need `users:manage`, so they are only sent when they change.
44
+ ...!emailChanged && emailVerified !== !!props.user.emailVerifiedAt ? { emailVerified } : {}
52
45
  }
53
46
  }).then(() => true),
54
47
  { success: emailChanged ? t("admin.detail.savedEmail", "Saved. A verification email was sent to the new address.") : t("admin.detail.saved", "Saved.") }
@@ -96,20 +89,7 @@ async function save(event) {
96
89
  v-model="form.email"
97
90
  type="email"
98
91
  class="w-full sm:max-w-sm"
99
- :disabled="!user.can.update"
100
- />
101
- </FormRow>
102
- <FormRow
103
- v-if="user.hasRoles"
104
- name="role"
105
- :label="t('admin.role', 'Role')"
106
- >
107
- <USelect
108
- v-model="form.role"
109
- :items="roleItems"
110
- class="w-full sm:max-w-sm"
111
- :placeholder="t('admin.rolePlaceholder', 'Select a role')"
112
- :disabled="!user.can.update"
92
+ :disabled="!user.can.manage"
113
93
  />
114
94
  </FormRow>
115
95
  <FormRow
@@ -119,7 +99,7 @@ async function save(event) {
119
99
  <UCheckbox
120
100
  v-model="form.emailVerified"
121
101
  :label="t('admin.emailVerified', 'Mark the email address as verified')"
122
- :disabled="!user.can.update || form.email !== user.email"
102
+ :disabled="!user.can.manage || form.email !== user.email"
123
103
  />
124
104
  </FormRow>
125
105
  </UForm>
@@ -6,6 +6,14 @@ export type UserSubscription = {
6
6
  /** One row of `GET /api/admin/users` (and `GET /api/admin/users/new`); the create response has no `subscription`. */
7
7
  export type UserRow = AdminUserDto & {
8
8
  subscription?: UserSubscription | null;
9
+ /** The user's stored roles (`@frigear-nu/authorization`), when it is installed. */
10
+ roles?: string[];
11
+ };
12
+ /** A role the list can be filtered by. */
13
+ export type UserRoleOption = {
14
+ value: string;
15
+ label: string;
16
+ labelKey?: string;
9
17
  };
10
18
  /** `GET /api/admin/users` */
11
19
  export type UsersPage = {
@@ -15,18 +23,18 @@ export type UsersPage = {
15
23
  pageSize: number;
16
24
  hasRoles: boolean;
17
25
  hasSubscriptions: boolean;
18
- roles: string[];
26
+ roles: UserRoleOption[];
19
27
  };
20
28
  /** The shape of `GET /api/admin/users/:id`. */
21
29
  export type UserDetail = AdminUserDto & {
22
30
  hasPassword: boolean;
23
31
  passkeys: number;
24
32
  subscription: UserSubscription | null;
25
- hasRoles: boolean;
26
- roles: string[];
33
+ /** `manage`: change or verify the email address (`users:manage`). */
27
34
  can: {
28
35
  update: boolean;
29
36
  delete: boolean;
37
+ manage: boolean;
30
38
  };
31
39
  };
32
40
  /** What the actions need of a user: the list rows and the detail both satisfy it. */
@@ -10,7 +10,6 @@
10
10
  "user": "Bruger",
11
11
  "name": "Navn",
12
12
  "email": "E-mail",
13
- "role": "Rolle",
14
13
  "verified": "Verificeret",
15
14
  "emailVerified": "Markér e-mailadressen som verificeret",
16
15
  "sendWelcome": "Send et login-link på e-mail",
@@ -26,7 +25,7 @@
26
25
  "description": "Tilmeldt inden for de seneste 30 dage.",
27
26
  "empty": "Ingen nye endnu."
28
27
  },
29
- "search": "Søg på navn, e-mail eller rolle...",
28
+ "search": "Søg i navn eller e-mail...",
30
29
  "empty": "Ingen brugere matcher",
31
30
  "total": "{count} brugere",
32
31
  "lastLogin": "Seneste login",
@@ -40,7 +39,6 @@
40
39
  "allRoles": "Alle roller"
41
40
  },
42
41
  "subscription": "Medlemskab",
43
- "rolePlaceholder": "Vælg en rolle",
44
42
  "detail": {
45
43
  "profile": "Profil",
46
44
  "account": "Konto",
@@ -75,7 +73,8 @@
75
73
  "deleteUser": "Slet bruger",
76
74
  "deleteTitle": "Slet {name}?",
77
75
  "deleteBody": "Kontoen og dens loginmetoder fjernes permanent. Det kan ikke fortrydes.",
78
- "deleted": "Brugeren er slettet."
76
+ "deleted": "Brugeren er slettet.",
77
+ "roles": "Roller"
79
78
  },
80
79
  "emailChange": {
81
80
  "verify": {
@@ -117,6 +116,16 @@
117
116
  "taken": "En anden konto bruger nu din gamle e-mailadresse. Kontakt os for at få din konto tilbage.",
118
117
  "failed": "Din e-mailadresse kunne ikke gendannes. Prøv igen."
119
118
  }
119
+ },
120
+ "permissions": {
121
+ "profileRead": "Se din profil",
122
+ "profileWrite": "Ændre din profil",
123
+ "read": "Se brugere",
124
+ "list": "Liste over brugere",
125
+ "create": "Tilføje brugere",
126
+ "update": "Redigere brugere",
127
+ "delete": "Slette brugere",
128
+ "manage": "Administrere brugeres login"
120
129
  }
121
130
  }
122
131
  }
@@ -10,7 +10,6 @@
10
10
  "user": "User",
11
11
  "name": "Name",
12
12
  "email": "Email",
13
- "role": "Role",
14
13
  "verified": "Verified",
15
14
  "emailVerified": "Mark the email address as verified",
16
15
  "sendWelcome": "Email a sign-in link",
@@ -26,7 +25,7 @@
26
25
  "description": "Signed up in the last 30 days.",
27
26
  "empty": "Nobody new yet."
28
27
  },
29
- "search": "Search name, email or role...",
28
+ "search": "Search name or email...",
30
29
  "empty": "No users match",
31
30
  "total": "{count} users",
32
31
  "lastLogin": "Last sign-in",
@@ -40,7 +39,6 @@
40
39
  "allRoles": "All roles"
41
40
  },
42
41
  "subscription": "Membership",
43
- "rolePlaceholder": "Select a role",
44
42
  "detail": {
45
43
  "profile": "Profile",
46
44
  "account": "Account",
@@ -75,7 +73,8 @@
75
73
  "deleteUser": "Delete user",
76
74
  "deleteTitle": "Delete {name}?",
77
75
  "deleteBody": "This permanently removes the account and its sign-in methods. It cannot be undone.",
78
- "deleted": "User deleted."
76
+ "deleted": "User deleted.",
77
+ "roles": "Roles"
79
78
  },
80
79
  "emailChange": {
81
80
  "verify": {
@@ -117,6 +116,16 @@
117
116
  "taken": "Another account now uses your old e-mail address. Contact us to get your account back.",
118
117
  "failed": "Could not restore your e-mail address. Try again."
119
118
  }
119
+ },
120
+ "permissions": {
121
+ "profileRead": "Read your profile",
122
+ "profileWrite": "Change your profile",
123
+ "read": "View users",
124
+ "list": "List users",
125
+ "create": "Add users",
126
+ "update": "Edit users",
127
+ "delete": "Delete users",
128
+ "manage": "Manage sign-in of users"
120
129
  }
121
130
  }
122
131
  }
@@ -1,6 +1,6 @@
1
1
  export default defineScopedMcpTool({
2
2
  description: "Get your own profile (id, name, email and role).",
3
- scopes: ["profile:read"],
3
+ permission: "profile:read",
4
4
  annotations: { readOnlyHint: true },
5
5
  handler: (_args, { user }) => pick(user, ["id", "name", "email", "role"])
6
6
  });
@@ -2,7 +2,7 @@ import { db, schema } from "@nuxthub/db";
2
2
  import { desc, gte } from "drizzle-orm";
3
3
  const DAYS = 30;
4
4
  export default defineEventHandler(async (event) => {
5
- await authorizeUsersAdmin(event, "view");
5
+ await authorizeUsersAdmin(event, "list");
6
6
  const since = new Date(Date.now() - DAYS * 24 * 60 * 60 * 1e3);
7
7
  const rows = await db.select().from(schema.users).where(gte(schema.users.createdAt, since)).orderBy(desc(schema.users.createdAt)).limit(10);
8
8
  const subscriptions = await latestSubscriptions(rows.map((row) => row.id));
@@ -2,7 +2,7 @@ import { db, schema } from "@nuxthub/db";
2
2
  import { count, gte } from "drizzle-orm";
3
3
  const DAYS = 30;
4
4
  export default defineEventHandler(async (event) => {
5
- await authorizeUsersAdmin(event, "view");
5
+ await authorizeUsersAdmin(event, "list");
6
6
  const since = new Date(Date.now() - DAYS * 24 * 60 * 60 * 1e3);
7
7
  const [[total], [recent]] = await Promise.all([
8
8
  db.select({ value: count() }).from(schema.users),
@@ -1,6 +1,6 @@
1
1
  import { notConfigured } from "@frigear-nu/module-kit/server";
2
2
  export default defineEventHandler(async (event) => {
3
- const { target } = await loadUsersAdminTarget(event, "update");
3
+ const { target } = await loadUsersAdminTarget(event, "manage");
4
4
  const sent = await sendVerificationLink(event, target);
5
5
  if (!sent) {
6
6
  throw notConfigured("Sign-in links are not enabled.");
@@ -1,22 +1,19 @@
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 { actor, target } = await loadUsersAdminTarget(event, "view", { scopes: [USERS_READ_SCOPE] });
5
- const withRole = usersHaveRoles();
6
- const targetInfo = usersAdminTargetInfo(target);
4
+ const { actor, target } = await loadUsersAdminTarget(event, "view");
7
5
  const passkeys = schema.userCredentials ? (await db.select({ total: count() }).from(schema.userCredentials).where(eq(schema.userCredentials.userId, target.id)))[0]?.total ?? 0 : 0;
8
6
  const subscription = (await latestSubscriptions([target.id])).get(target.id) ?? null;
9
- const [canUpdate, canDelete] = await Promise.all([
10
- isUsersAdminAllowed(event, "update", { target: targetInfo, input: {} }),
11
- isUsersAdminAllowed(event, "delete", { target: targetInfo })
7
+ const [canUpdate, canDelete, canManage] = await Promise.all([
8
+ canUsersAdminTarget(event, "update", target),
9
+ canUsersAdminTarget(event, "delete", target),
10
+ canUsersAdminTarget(event, "manage", target)
12
11
  ]);
13
12
  return {
14
13
  ...toAdminUserDto(target),
15
14
  hasPassword: !!target.password,
16
15
  passkeys,
17
16
  subscription,
18
- hasRoles: withRole,
19
- roles: withRole ? await assignableRoles(event, actor.id) : [],
20
- can: { update: canUpdate.allowed, delete: canDelete.allowed && target.id !== actor.id }
17
+ can: { update: canUpdate, delete: canDelete && target.id !== actor.id, manage: canUpdate && canManage }
21
18
  };
22
19
  });
@@ -5,26 +5,20 @@ import { emailField, nameField } from "../../schemas.js";
5
5
  const bodySchema = z.object({
6
6
  name: nameField().optional(),
7
7
  email: emailField().optional(),
8
- role: z.string().trim().min(1).max(60).optional(),
9
8
  emailVerified: z.boolean().optional()
10
9
  });
11
10
  export default defineEventHandler(async (event) => {
12
11
  const { target } = await loadUsersAdminTarget(event, "update");
13
12
  const input = await readValidatedBody(event, bodySchema.parse);
14
- const withRole = usersHaveRoles();
15
- await authorizeUsersAdmin(event, "update", {
16
- input: { role: withRole ? input.role : void 0, email: input.email, name: input.name },
17
- target: usersAdminTargetInfo(target)
18
- });
19
13
  const emailChanged = !!input.email && !sameUserEmail(input.email, target.email);
14
+ if (emailChanged || input.emailVerified !== void 0) await authorize(event, USERS_MANAGE_PERMISSION, target);
20
15
  if (emailChanged) await assertEmailAvailable(input.email, { exceptUserId: target.id });
21
16
  const changes = {
22
17
  ...input.name ? { name: input.name } : {},
23
18
  // A changed address was typed in by staff, so it is unverified until its owner confirms it (unless staff
24
19
  // explicitly marks it verified in the same request).
25
20
  ...emailChanged ? { email: input.email, emailVerifiedAt: input.emailVerified ? /* @__PURE__ */ new Date() : null } : {},
26
- ...!emailChanged && input.emailVerified !== void 0 ? { emailVerifiedAt: input.emailVerified ? target.emailVerifiedAt ?? /* @__PURE__ */ new Date() : null } : {},
27
- ...withRole && input.role ? { role: input.role } : {}
21
+ ...!emailChanged && input.emailVerified !== void 0 ? { emailVerifiedAt: input.emailVerified ? target.emailVerifiedAt ?? /* @__PURE__ */ new Date() : null } : {}
28
22
  };
29
23
  if (!Object.keys(changes).length) return toAdminUserDto(target);
30
24
  const [updated] = await db.update(schema.users).set(changes).where(eq(schema.users.id, target.id)).returning();