@frigear-nu/users 1.0.8 → 1.0.9

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 (98) hide show
  1. package/README.md +19 -136
  2. package/dist/module.d.mts +35 -48
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +97 -169
  5. package/dist/runtime/admin-menus.js +16 -0
  6. package/dist/runtime/app/pages/admin-user.vue +52 -0
  7. package/dist/runtime/app/pages/admin.vue +252 -0
  8. package/dist/runtime/app/tabs/Overview.d.vue.ts +11 -0
  9. package/dist/runtime/app/tabs/Overview.vue +206 -0
  10. package/dist/runtime/app/tabs/Overview.vue.d.ts +11 -0
  11. package/dist/runtime/app/utils/admin-user.d.ts +22 -0
  12. package/dist/runtime/app/utils/admin-user.js +0 -0
  13. package/dist/runtime/app/widgets/NewMembers.d.vue.ts +3 -0
  14. package/dist/runtime/app/widgets/NewMembers.vue +66 -0
  15. package/dist/runtime/app/widgets/NewMembers.vue.d.ts +3 -0
  16. package/dist/runtime/db/email-changes.sqlite.d.ts +202 -0
  17. package/dist/runtime/db/email-changes.sqlite.js +16 -0
  18. package/dist/runtime/db/schema.sqlite.d.ts +5 -212
  19. package/dist/runtime/db/schema.sqlite.js +2 -21
  20. package/dist/runtime/i18n/lang/da.json +61 -87
  21. package/dist/runtime/i18n/lang/en.json +61 -87
  22. package/dist/runtime/server/mcp/tools/get-my-profile.js +6 -0
  23. package/dist/runtime/server/routes/admin/new-members.get.js +16 -0
  24. package/dist/runtime/server/routes/admin/roles.get.js +4 -0
  25. package/dist/runtime/server/routes/admin/user-resend.post.js +19 -0
  26. package/dist/runtime/server/routes/admin/user.delete.js +21 -0
  27. package/dist/runtime/server/routes/admin/user.get.js +32 -0
  28. package/dist/runtime/server/routes/admin/user.patch.js +45 -0
  29. package/dist/runtime/server/routes/admin/users.get.js +59 -0
  30. package/dist/runtime/server/routes/admin/users.post.js +33 -0
  31. package/dist/runtime/server/routes/me/change-email.post.js +35 -0
  32. package/dist/runtime/server/routes/me/change-password.post.js +27 -0
  33. package/dist/runtime/server/routes/me/profile.post.d.ts +2 -0
  34. package/dist/runtime/server/routes/me/profile.post.js +17 -0
  35. package/dist/runtime/server/routes/me/revert-email-change.get.d.ts +2 -0
  36. package/dist/runtime/server/routes/me/revert-email-change.get.js +24 -0
  37. package/dist/runtime/server/routes/me/verify-email-change.get.d.ts +2 -0
  38. package/dist/runtime/server/routes/me/verify-email-change.get.js +37 -0
  39. package/dist/runtime/server/user-store.d.ts +3 -0
  40. package/dist/runtime/server/user-store.js +70 -0
  41. package/dist/runtime/server/utils/admin.d.ts +59 -0
  42. package/dist/runtime/server/utils/admin.js +53 -0
  43. package/dist/runtime/server/utils/notifications.d.ts +16 -0
  44. package/dist/runtime/server/utils/notifications.js +32 -0
  45. package/dist/runtime/server/utils/require-user.d.ts +12 -0
  46. package/dist/runtime/server/utils/require-user.js +9 -0
  47. package/dist/runtime/utils/index.d.ts +19 -0
  48. package/dist/runtime/utils/index.js +11 -0
  49. package/dist/types.d.mts +2 -2
  50. package/package.json +28 -16
  51. package/dist/runtime/app/composables/useAuthManifest.d.ts +0 -5
  52. package/dist/runtime/app/composables/useAuthManifest.js +0 -7
  53. package/dist/runtime/app/composables/useUserLogin.d.ts +0 -12
  54. package/dist/runtime/app/composables/useUserLogin.js +0 -26
  55. package/dist/runtime/app/composables/useUserPasskeys.d.ts +0 -7
  56. package/dist/runtime/app/composables/useUserPasskeys.js +0 -22
  57. package/dist/runtime/app/composables/useUserPasswordReset.d.ts +0 -13
  58. package/dist/runtime/app/composables/useUserPasswordReset.js +0 -32
  59. package/dist/runtime/app/composables/useUserRegistration.d.ts +0 -10
  60. package/dist/runtime/app/composables/useUserRegistration.js +0 -20
  61. package/dist/runtime/app/pages/login.vue +0 -68
  62. package/dist/runtime/app/pages/register.vue +0 -40
  63. package/dist/runtime/app/utils/oauth-providers.d.ts +0 -13
  64. package/dist/runtime/app/utils/oauth-providers.js +0 -4
  65. package/dist/runtime/menus.js +0 -14
  66. package/dist/runtime/server/routes/auth/forgot-password.post.js +0 -19
  67. package/dist/runtime/server/routes/auth/github.get.js +0 -7
  68. package/dist/runtime/server/routes/auth/google.get.js +0 -6
  69. package/dist/runtime/server/routes/auth/login.post.js +0 -15
  70. package/dist/runtime/server/routes/auth/logout.get.js +0 -4
  71. package/dist/runtime/server/routes/auth/register.post.js +0 -18
  72. package/dist/runtime/server/routes/auth/reset-password.post.js +0 -29
  73. package/dist/runtime/server/routes/auth/webauthn/authenticate.post.js +0 -34
  74. package/dist/runtime/server/routes/auth/webauthn/credentials/[id].delete.js +0 -9
  75. package/dist/runtime/server/routes/auth/webauthn/credentials/index.get.js +0 -8
  76. package/dist/runtime/server/routes/auth/webauthn/register.post.js +0 -42
  77. package/dist/runtime/server/utils/oauth.d.ts +0 -8
  78. package/dist/runtime/server/utils/oauth.js +0 -18
  79. package/dist/runtime/server/utils/password-reset.d.ts +0 -22
  80. package/dist/runtime/server/utils/password-reset.js +0 -14
  81. package/dist/runtime/server/utils/session.d.ts +0 -11
  82. package/dist/runtime/server/utils/session.js +0 -5
  83. /package/dist/runtime/{menus.d.ts → admin-menus.d.ts} +0 -0
  84. /package/dist/runtime/app/pages/{login.d.vue.ts → admin-user.d.vue.ts} +0 -0
  85. /package/dist/runtime/app/pages/{login.vue.d.ts → admin-user.vue.d.ts} +0 -0
  86. /package/dist/runtime/app/pages/{register.d.vue.ts → admin.d.vue.ts} +0 -0
  87. /package/dist/runtime/app/pages/{register.vue.d.ts → admin.vue.d.ts} +0 -0
  88. /package/dist/runtime/server/{routes/auth/forgot-password.post.d.ts → mcp/tools/get-my-profile.d.ts} +0 -0
  89. /package/dist/runtime/server/routes/{auth/github.get.d.ts → admin/new-members.get.d.ts} +0 -0
  90. /package/dist/runtime/server/routes/{auth/google.get.d.ts → admin/roles.get.d.ts} +0 -0
  91. /package/dist/runtime/server/routes/{auth/login.post.d.ts → admin/user-resend.post.d.ts} +0 -0
  92. /package/dist/runtime/server/routes/{auth/logout.get.d.ts → admin/user.delete.d.ts} +0 -0
  93. /package/dist/runtime/server/routes/{auth/register.post.d.ts → admin/user.get.d.ts} +0 -0
  94. /package/dist/runtime/server/routes/{auth/reset-password.post.d.ts → admin/user.patch.d.ts} +0 -0
  95. /package/dist/runtime/server/routes/{auth/webauthn/authenticate.post.d.ts → admin/users.get.d.ts} +0 -0
  96. /package/dist/runtime/server/routes/{auth/webauthn/credentials/[id].delete.d.ts → admin/users.post.d.ts} +0 -0
  97. /package/dist/runtime/server/routes/{auth/webauthn/credentials/index.get.d.ts → me/change-email.post.d.ts} +0 -0
  98. /package/dist/runtime/server/routes/{auth/webauthn/register.post.d.ts → me/change-password.post.d.ts} +0 -0
@@ -0,0 +1,59 @@
1
+ import type { H3Event } from 'h3';
2
+ export type UsersAdminAction = 'view' | 'create' | 'update' | 'delete';
3
+ export type UsersAdminContext = {
4
+ event: H3Event;
5
+ /** The signed-in user making the request. */
6
+ userId: number;
7
+ action: UsersAdminAction;
8
+ /** `create`/`update`: the values being written (`role` only when an authorization module added the column). */
9
+ input?: {
10
+ role?: string;
11
+ email?: string;
12
+ name?: string;
13
+ };
14
+ /** `update`/`delete`: the user being changed, as stored. */
15
+ target?: {
16
+ id: number;
17
+ email: string;
18
+ role?: string;
19
+ };
20
+ /** Set to `true` to allow. Denied by default. */
21
+ allowed: boolean;
22
+ };
23
+ export type UsersAdminRolesContext = {
24
+ event: H3Event;
25
+ /** The signed-in user making the request. */
26
+ userId: number;
27
+ /** The roles this user may assign, in display order. Replace it to narrow or extend the default (roles already in use). */
28
+ roles: string[];
29
+ };
30
+ /** Whether another module added a `role` column to `users` (`@frigear-nu/authorization`). */
31
+ export declare const usersHaveRoles: () => boolean;
32
+ /** Whether the host policy allows the signed-in user to do `action` (never throws on denial). */
33
+ export declare function isUsersAdminAllowed(event: H3Event, action: UsersAdminAction, details?: Pick<UsersAdminContext, 'input' | 'target'>): Promise<{
34
+ allowed: boolean;
35
+ user: any;
36
+ }>;
37
+ /**
38
+ * Asks the host (the `users:admin:authorize` hook) whether the signed-in user may do `action`; throws 401/403
39
+ * otherwise. The users module knows nothing about roles or staff: that policy is the host's.
40
+ */
41
+ export declare function authorizeUsersAdmin(event: H3Event, action: UsersAdminAction, details?: Pick<UsersAdminContext, 'input' | 'target'>): Promise<any>;
42
+ /**
43
+ * The roles the signed-in user may assign. Defaults to the roles in use; the host narrows/extends it through the
44
+ * `users:admin:roles` hook (e.g. from a role hierarchy and the acting user's own rank).
45
+ */
46
+ export declare function assignableRoles(event: H3Event, userId: number): Promise<string[]>;
47
+ /** Latest subscription per user, when a subscriptions table is installed (`@frigear-nu/subscriptions`); else empty. */
48
+ export declare function latestSubscriptions(userIds: number[]): Promise<Map<number, {
49
+ planKey: string | null;
50
+ status: string;
51
+ }>>;
52
+ /**
53
+ * 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). Throws 400/401/403/404. For routes added with `extendUsersAdmin`.
55
+ */
56
+ export declare function loadUsersAdminTarget(event: H3Event, action: Exclude<UsersAdminAction, 'create'>): Promise<{
57
+ actor: any;
58
+ target: any;
59
+ }>;
@@ -0,0 +1,53 @@
1
+ import { db, schema } from "@nuxthub/db";
2
+ import { desc, getTableColumns, inArray } from "drizzle-orm";
3
+ export const usersHaveRoles = () => "role" in getTableColumns(schema.users);
4
+ export async function isUsersAdminAllowed(event, action, details = {}) {
5
+ const user = await requireUser(event, { sessionOnly: true });
6
+ const context = { event, userId: user.id, action, ...details, allowed: false };
7
+ await useNitroApp().hooks.callHook("users:admin:authorize", context);
8
+ return { allowed: context.allowed, user };
9
+ }
10
+ export async function authorizeUsersAdmin(event, action, details = {}) {
11
+ const { allowed, user } = await isUsersAdminAllowed(event, action, details);
12
+ if (!allowed) {
13
+ throw createError({ statusCode: 403, statusMessage: "You are not allowed to manage users." });
14
+ }
15
+ return user;
16
+ }
17
+ export async function assignableRoles(event, userId) {
18
+ let roles = [];
19
+ if (usersHaveRoles()) {
20
+ const columns = schema.users;
21
+ const rows = await db.selectDistinct({ role: columns.role }).from(schema.users);
22
+ roles = rows.map((row) => row.role).filter((role) => !!role);
23
+ }
24
+ const context = { event, userId, roles };
25
+ await useNitroApp().hooks.callHook("users:admin:roles", context);
26
+ return [...new Set(context.roles)];
27
+ }
28
+ export async function latestSubscriptions(userIds) {
29
+ const result = /* @__PURE__ */ new Map();
30
+ const table = schema.subscriptions;
31
+ if (!table || !userIds.length) return result;
32
+ const rows = await db.select({ userId: table.userId, planKey: table.planKey, status: table.status, endedAt: table.endedAt }).from(table).where(inArray(table.userId, userIds)).orderBy(desc(table.createdAt));
33
+ for (const row of rows) {
34
+ const live = !row.endedAt && ["active", "trialing", "past_due"].includes(row.status);
35
+ const current = result.get(row.userId);
36
+ if (!current || live && !["active", "trialing", "past_due"].includes(current.status)) {
37
+ result.set(row.userId, { planKey: row.planKey, status: row.status });
38
+ }
39
+ }
40
+ return result;
41
+ }
42
+ export async function loadUsersAdminTarget(event, action) {
43
+ const id = Number(getRouterParam(event, "id"));
44
+ if (!Number.isInteger(id)) throw createError({ statusCode: 400, statusMessage: "Invalid user id." });
45
+ const target = await db.query.users.findFirst({ where: (t, { eq }) => eq(t.id, id) });
46
+ const actor = await authorizeUsersAdmin(
47
+ event,
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." });
52
+ return { actor, target };
53
+ }
@@ -0,0 +1,16 @@
1
+ import type { EmailNotification } from '@frigear-nu/notify/types';
2
+ export declare function buildVerifyEmailChangeNotification({ to, name, url }: {
3
+ to: string;
4
+ name: string;
5
+ url: string;
6
+ }): EmailNotification;
7
+ export declare function buildEmailChangedNotification({ to, name, newEmail, revertUrl }: {
8
+ to: string;
9
+ name: string;
10
+ newEmail: string;
11
+ revertUrl: string;
12
+ }): EmailNotification;
13
+ export declare function buildPasswordChangedNotification({ to, name }: {
14
+ to: string;
15
+ name: string;
16
+ }): EmailNotification;
@@ -0,0 +1,32 @@
1
+ const escapeHtml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2
+ const link = (url) => `<p><a href="${escapeHtml(url)}">${escapeHtml(url)}</a></p>`;
3
+ export function buildVerifyEmailChangeNotification({ to, name, url }) {
4
+ return {
5
+ to,
6
+ subject: "Confirm your new email address",
7
+ body: `<p>Hi ${escapeHtml(name)},</p><p>Confirm that this is your new email address. The link expires in 24 hours.</p>${link(url)}`,
8
+ text: `Hi ${name},
9
+
10
+ Confirm your new email address (expires in 24 hours): ${url}`
11
+ };
12
+ }
13
+ export function buildEmailChangedNotification({ to, name, newEmail, revertUrl }) {
14
+ return {
15
+ to,
16
+ subject: "Your email address was changed",
17
+ body: `<p>Hi ${escapeHtml(name)},</p><p>The email address on your account was changed to <strong>${escapeHtml(newEmail)}</strong>. If this wasn't you, undo it within 7 days:</p>${link(revertUrl)}`,
18
+ text: `Hi ${name},
19
+
20
+ The email address on your account was changed to ${newEmail}. If this wasn't you, undo it within 7 days: ${revertUrl}`
21
+ };
22
+ }
23
+ export function buildPasswordChangedNotification({ to, name }) {
24
+ return {
25
+ to,
26
+ subject: "Your password was changed",
27
+ body: `<p>Hi ${escapeHtml(name)},</p><p>The password on your account was just changed. If this wasn't you, reset it right away.</p>`,
28
+ text: `Hi ${name},
29
+
30
+ The password on your account was just changed. If this wasn't you, reset it right away.`
31
+ };
32
+ }
@@ -0,0 +1,12 @@
1
+ import type { H3Event } from 'h3';
2
+ import { type RequireUserOptions } from '@frigear-nu/auth/utils';
3
+ /**
4
+ * The signed-in user, or a thrown 401/403 (see `requireAuth` for the credential rules: `scopes`, `sessionOnly`).
5
+ * Use `requireAuth` instead when the route only needs to know how the caller authenticated.
6
+ */
7
+ export declare function requireUser(event: H3Event, options?: RequireUserOptions): Promise<any>;
8
+ /**
9
+ * 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. A bearer credential missing the required `scopes` counts as anonymous.
11
+ */
12
+ export declare function getUser(event: H3Event, options?: Pick<RequireUserOptions, 'scopes'>): Promise<any>;
@@ -0,0 +1,9 @@
1
+ import { hasScopes } from "@frigear-nu/auth/utils";
2
+ export async function requireUser(event, options = {}) {
3
+ return (await requireAuth(event, options)).user;
4
+ }
5
+ export async function getUser(event, options = {}) {
6
+ const principal = await getAuth(event);
7
+ if (!principal) return null;
8
+ return !options.scopes?.length || hasScopes(principal.scopes, options.scopes) ? principal.user : null;
9
+ }
@@ -0,0 +1,19 @@
1
+ import type { Nuxt } from '@nuxt/schema';
2
+ import type { TabDefinition, WidgetDefinition } from '@frigear-nu/widget/utils';
3
+ export interface UsersAdminExtension {
4
+ /** Staff routes on the user, mounted at `/api/admin/users/:id/<path>`. Handlers are absolute paths. */
5
+ routes?: {
6
+ method: 'get' | 'post' | 'patch' | 'delete';
7
+ path: string;
8
+ handler: string;
9
+ }[];
10
+ /** A tab on the admin user page (`admin.users`). Needs `@frigear-nu/widget` and `@frigear-nu/admin`; skipped without them. */
11
+ tab?: TabDefinition;
12
+ /** A card on the overview tab of the admin user page (`admin.users.overview`). Needs `@frigear-nu/widget` and `@frigear-nu/admin`. */
13
+ widget?: WidgetDefinition;
14
+ }
15
+ /**
16
+ * Lets a module extend the admin user page of `@frigear-nu/users`: its own staff routes below
17
+ * `/api/admin/users/:id/`, a tab and an overview card. Routes authorize with `loadUsersAdminTarget`.
18
+ */
19
+ export declare function extendUsersAdmin(nuxt: Nuxt, extension: UsersAdminExtension): Promise<void>;
@@ -0,0 +1,11 @@
1
+ import { addServerHandler, hasNuxtModule } from "@nuxt/kit";
2
+ export async function extendUsersAdmin(nuxt, extension) {
3
+ for (const { method, path, handler } of extension.routes ?? []) {
4
+ addServerHandler({ route: `/api/admin/users/:id/${path}`, method, handler });
5
+ }
6
+ if (!extension.tab && !extension.widget) return;
7
+ if (!hasNuxtModule("@frigear-nu/widget", nuxt) || !hasNuxtModule("@frigear-nu/admin", nuxt)) return;
8
+ const { extendTabs, extendWidgets } = await import("@frigear-nu/widget/utils");
9
+ if (extension.tab) extendTabs(nuxt, "admin.users", extension.tab);
10
+ if (extension.widget) extendWidgets(nuxt, "admin.users.overview", extension.widget);
11
+ }
package/dist/types.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- export { type OAUTH_PROVIDERS, default } from './module.mjs'
1
+ export { default } from './module.mjs'
2
2
 
3
- export { type AuthManifest, type AuthMethod, type AuthMethodObject, type ModuleOptions, type OAuthProvider, type OAuthProviderDetails, type PublicModuleOptions } from './module.mjs'
3
+ export { type ModuleOptions, type PublicModuleOptions } from './module.mjs'
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@frigear-nu/users",
3
- "version": "1.0.8",
4
- "description": "A module for managing the users in the main frigear app.",
3
+ "version": "1.0.9",
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": {
7
7
  "type": "git",
@@ -15,6 +15,11 @@
15
15
  ".": {
16
16
  "types": "./dist/types.d.mts",
17
17
  "import": "./dist/module.mjs"
18
+ },
19
+ "./utils": {
20
+ "types": "./dist/runtime/utils/index.d.ts",
21
+ "import": "./dist/runtime/utils/index.js",
22
+ "default": "./dist/runtime/utils/index.js"
18
23
  }
19
24
  },
20
25
  "files": [
@@ -24,28 +29,32 @@
24
29
  "playground"
25
30
  ],
26
31
  "dependencies": {
27
- "@frigear-nu/module-kit": "0.1.6",
28
- "@frigear-nu/notify": "0.0.8",
29
- "@frigear-nu/menu": "0.0.8",
32
+ "@frigear-nu/auth": "0.0.3",
33
+ "@frigear-nu/mcp": "0.0.3",
34
+ "@frigear-nu/module-kit": "0.1.7",
35
+ "@frigear-nu/notify": "0.0.9",
30
36
  "@libsql/client": "^0.18.0",
31
37
  "@nuxt/kit": "^4.6.0",
32
38
  "drizzle-kit": "^0.31.11",
33
39
  "drizzle-orm": "^0.45.3",
34
- "nuxt-auth-utils": "^0.5.30",
35
- "zod": "^4.6.5",
36
- "scule": "^1.3.0"
40
+ "scule": "^1.3.0",
41
+ "zod": "^4.6.5"
37
42
  },
38
43
  "peerDependencies": {
39
- "@nuxthub/core": "^0.10.8",
40
- "@simplewebauthn/browser": "^11.0.0",
41
- "@simplewebauthn/server": "^11.0.0",
42
- "@nuxt/ui": "^4.10.0"
44
+ "@frigear-nu/admin": ">=0.0.0",
45
+ "@frigear-nu/menu": "0.0.9",
46
+ "@frigear-nu/widget": "0.0.2",
47
+ "@nuxt/ui": "^4.10.0",
48
+ "@nuxthub/core": "^0.10.8"
43
49
  },
44
50
  "peerDependenciesMeta": {
45
- "@simplewebauthn/browser": {
51
+ "@frigear-nu/admin": {
52
+ "optional": true
53
+ },
54
+ "@frigear-nu/menu": {
46
55
  "optional": true
47
56
  },
48
- "@simplewebauthn/server": {
57
+ "@frigear-nu/widget": {
49
58
  "optional": true
50
59
  },
51
60
  "@nuxt/ui": {
@@ -53,11 +62,15 @@
53
62
  }
54
63
  },
55
64
  "devDependencies": {
65
+ "@frigear-nu/admin": "0.0.2",
66
+ "@frigear-nu/menu": "0.0.9",
67
+ "@frigear-nu/widget": "0.0.2",
56
68
  "@nuxt/devtools": "^3.4.2",
57
69
  "@nuxt/eslint-config": "^1.17.0",
58
70
  "@nuxt/module-builder": "^1.0.3",
59
71
  "@nuxt/schema": "^4.6.0",
60
72
  "@nuxt/test-utils": "^4.3.2",
73
+ "@nuxt/ui": "^4.11.0",
61
74
  "@nuxthub/core": "^0.10.8",
62
75
  "@types/node": "latest",
63
76
  "changelogen": "^0.6.2",
@@ -65,8 +78,7 @@
65
78
  "nuxt": "^4.6.1",
66
79
  "typescript": "^6.0.3",
67
80
  "vitest": "^5.0.1",
68
- "vue-tsc": "^3.3.11",
69
- "@nuxt/ui": "^4.11.0"
81
+ "vue-tsc": "^3.3.11"
70
82
  },
71
83
  "scripts": {
72
84
  "postinstall": "nuxt-module-build build --stub && nuxt prepare",
@@ -1,5 +0,0 @@
1
- export declare const useAuthManifest: () => {
2
- readonly name: "users";
3
- readonly version: "1.0.0";
4
- readonly description: "User management module for authentication and authorization.";
5
- };
@@ -1,7 +0,0 @@
1
- export const useAuthManifest = () => {
2
- return {
3
- name: "users",
4
- version: "1.0.0",
5
- description: "User management module for authentication and authorization."
6
- };
7
- };
@@ -1,12 +0,0 @@
1
- export declare const useUserLogin: () => {
2
- login: (payload: {
3
- email: string;
4
- password: string;
5
- }) => Promise<void>;
6
- pending: any;
7
- error: any;
8
- isEnabled: any;
9
- passwordLoginEnabled: any;
10
- passkeyLoginEnabled: any;
11
- oauthProviders: any;
12
- };
@@ -1,26 +0,0 @@
1
- import { OAUTH_PROVIDER_META } from "../utils/oauth-providers.js";
2
- export const useUserLogin = () => {
3
- const config = useRuntimeConfig().public.users;
4
- const passwordLoginEnabled = computed(() => config?.password === true);
5
- const passkeyLoginEnabled = computed(() => config?.webAuthn === true);
6
- const oauthProviders = computed(() => (config?.oauth ?? []).map((provider) => {
7
- return typeof provider === "object" ? provider : OAUTH_PROVIDER_META[provider];
8
- }));
9
- const isEnabled = computed(() => passwordLoginEnabled.value || passkeyLoginEnabled.value || oauthProviders.value.length > 0);
10
- const pending = ref(false);
11
- const error = ref(null);
12
- async function login(payload) {
13
- pending.value = true;
14
- error.value = null;
15
- try {
16
- await $fetch("/api/auth/login", { method: "POST", body: payload });
17
- await useUserSession().fetch();
18
- } catch (err) {
19
- error.value = err instanceof Error ? err.message : "Failed to log in.";
20
- throw err;
21
- } finally {
22
- pending.value = false;
23
- }
24
- }
25
- return { login, pending, error, isEnabled, passwordLoginEnabled, passkeyLoginEnabled, oauthProviders };
26
- };
@@ -1,7 +0,0 @@
1
- export declare const useUserPasskeys: () => {
2
- isEnabled: any;
3
- registerPasskey: (userName: string) => Promise<void>;
4
- authenticateWithPasskey: (userName?: string) => Promise<void>;
5
- listPasskeys: () => any;
6
- removePasskey: (id: string) => any;
7
- };
@@ -1,22 +0,0 @@
1
- export const useUserPasskeys = () => {
2
- const config = useRuntimeConfig().public.users;
3
- const isEnabled = computed(() => config?.webAuthn === true);
4
- const { register, authenticate } = useWebAuthn({
5
- registerEndpoint: "/api/auth/webauthn/register",
6
- authenticateEndpoint: "/api/auth/webauthn/authenticate"
7
- });
8
- const { fetch: fetchUserSession } = useUserSession();
9
- async function registerPasskey(userName) {
10
- await register({ userName }).then(fetchUserSession);
11
- }
12
- async function authenticateWithPasskey(userName) {
13
- await authenticate(userName).then(fetchUserSession);
14
- }
15
- function listPasskeys() {
16
- return $fetch("/api/auth/webauthn/credentials");
17
- }
18
- function removePasskey(id) {
19
- return $fetch(`/api/auth/webauthn/credentials/${id}`, { method: "DELETE" });
20
- }
21
- return { isEnabled, registerPasskey, authenticateWithPasskey, listPasskeys, removePasskey };
22
- };
@@ -1,13 +0,0 @@
1
- export declare const useUserPasswordReset: () => {
2
- requestReset: (payload: {
3
- email: string;
4
- }) => Promise<void>;
5
- resetPassword: (payload: {
6
- code: string;
7
- password: string;
8
- confirmPassword: string;
9
- }) => Promise<void>;
10
- pending: any;
11
- error: any;
12
- isEnabled: any;
13
- };
@@ -1,32 +0,0 @@
1
- export const useUserPasswordReset = () => {
2
- const config = useRuntimeConfig().public.users;
3
- const isEnabled = computed(() => config?.passwordReset === true);
4
- const pending = ref(false);
5
- const error = ref(null);
6
- async function requestReset(payload) {
7
- pending.value = true;
8
- error.value = null;
9
- try {
10
- await $fetch("/api/auth/forgot-password", { method: "POST", body: payload });
11
- } catch (err) {
12
- error.value = err instanceof Error ? err.message : "Failed to request a password reset.";
13
- throw err;
14
- } finally {
15
- pending.value = false;
16
- }
17
- }
18
- async function resetPassword(payload) {
19
- pending.value = true;
20
- error.value = null;
21
- try {
22
- await $fetch("/api/auth/reset-password", { method: "POST", body: payload });
23
- await useUserSession().fetch();
24
- } catch (err) {
25
- error.value = err instanceof Error ? err.message : "Failed to reset password.";
26
- throw err;
27
- } finally {
28
- pending.value = false;
29
- }
30
- }
31
- return { requestReset, resetPassword, pending, error, isEnabled };
32
- };
@@ -1,10 +0,0 @@
1
- export declare const useUserRegistration: () => {
2
- register: (payload: {
3
- name: string;
4
- email: string;
5
- password: string;
6
- }) => Promise<void>;
7
- pending: any;
8
- error: any;
9
- isEnabled: any;
10
- };
@@ -1,20 +0,0 @@
1
- export const useUserRegistration = () => {
2
- const config = useRuntimeConfig().public.users;
3
- const isEnabled = computed(() => config?.password === true);
4
- const pending = ref(false);
5
- const error = ref(null);
6
- async function register(payload) {
7
- pending.value = true;
8
- error.value = null;
9
- try {
10
- await $fetch("/api/auth/register", { method: "POST", body: payload });
11
- await useUserSession().fetch();
12
- } catch (err) {
13
- error.value = err instanceof Error ? err.message : "Failed to register.";
14
- throw err;
15
- } finally {
16
- pending.value = false;
17
- }
18
- }
19
- return { register, pending, error, isEnabled };
20
- };
@@ -1,68 +0,0 @@
1
- <script setup>
2
- defineOptions({ name: "UsersLoginPage" });
3
- const t = useModuleT("auth");
4
- const { login, pending, error, passwordLoginEnabled, passkeyLoginEnabled, oauthProviders } = useUserLogin();
5
- const passkeys = passkeyLoginEnabled.value ? useUserPasskeys() : void 0;
6
- const passkeyPending = ref(false);
7
- const redirectTarget = computed(() => {
8
- const target = useRoute().query.redirect;
9
- return typeof target === "string" && target.startsWith("/") && !target.startsWith("//") ? target : "/";
10
- });
11
- const afterLogin = () => navigateTo(redirectTarget.value, { external: redirectTarget.value !== "/" });
12
- const fields = computed(() => passwordLoginEnabled.value ? [
13
- { name: "email", type: "text", label: t("email.label", "Email"), required: true },
14
- { name: "password", type: "password", label: t("password.label", "Password"), required: true }
15
- ] : []);
16
- async function onSubmit(payload) {
17
- await login(payload.data);
18
- await afterLogin();
19
- }
20
- async function onPasskeyLogin() {
21
- error.value = null;
22
- passkeyPending.value = true;
23
- try {
24
- await passkeys?.authenticateWithPasskey();
25
- await afterLogin();
26
- } catch (err) {
27
- error.value = err instanceof Error ? err.message : "Failed to log in.";
28
- } finally {
29
- passkeyPending.value = false;
30
- }
31
- }
32
- </script>
33
-
34
- <template>
35
- <UContainer>
36
- <UPage>
37
- <UPageBody>
38
- <UAuthForm
39
- :title="t('signIn', 'Log in')"
40
- :fields="fields"
41
- :providers="oauthProviders"
42
- :loading="pending"
43
- :submit="{ label: t('signIn', 'Log in') }"
44
- @submit="onSubmit"
45
- >
46
- <template
47
- v-if="error"
48
- #validation
49
- >
50
- <UAlert
51
- color="error"
52
- :title="error"
53
- />
54
- </template>
55
- </UAuthForm>
56
- <UButton
57
- v-if="passkeyLoginEnabled"
58
- class="mt-4 w-full"
59
- :loading="passkeyPending"
60
- :disabled="pending"
61
- @click="onPasskeyLogin"
62
- >
63
- {{ t("passkey.login", "Log in with a passkey") }}
64
- </UButton>
65
- </UPageBody>
66
- </UPage>
67
- </UContainer>
68
- </template>
@@ -1,40 +0,0 @@
1
- <script setup>
2
- defineOptions({ name: "UsersRegisterPage" });
3
- const t = useModuleT("auth");
4
- const { register, pending, error } = useUserRegistration();
5
- const fields = computed(() => [
6
- { name: "name", type: "text", label: t("name.label", "Name"), required: true },
7
- { name: "email", type: "text", label: t("email.label", "Email"), required: true },
8
- { name: "password", type: "password", label: t("password.label", "Password"), required: true }
9
- ]);
10
- async function onSubmit(payload) {
11
- await register(payload.data);
12
- await navigateTo("/");
13
- }
14
- </script>
15
-
16
- <template>
17
- <UContainer>
18
- <UPage>
19
- <UPageBody>
20
- <UAuthForm
21
- :title="t('signUp', 'Register')"
22
- :fields="fields"
23
- :loading="pending"
24
- :submit="{ label: t('signUp', 'Register') }"
25
- @submit="onSubmit"
26
- >
27
- <template
28
- v-if="error"
29
- #validation
30
- >
31
- <UAlert
32
- color="error"
33
- :title="error"
34
- />
35
- </template>
36
- </UAuthForm>
37
- </UPageBody>
38
- </UPage>
39
- </UContainer>
40
- </template>
@@ -1,13 +0,0 @@
1
- export declare const OAUTH_PROVIDER_META: {
2
- readonly github: {
3
- readonly label: "GitHub";
4
- readonly icon: "i-simple-icons-github";
5
- readonly to: "/api/auth/github";
6
- };
7
- readonly google: {
8
- readonly label: "Google";
9
- readonly icon: "i-simple-icons-google";
10
- readonly to: "/api/auth/google";
11
- };
12
- };
13
- export type OAuthProviderKey = keyof typeof OAUTH_PROVIDER_META;
@@ -1,4 +0,0 @@
1
- export const OAUTH_PROVIDER_META = {
2
- github: { label: "GitHub", icon: "i-simple-icons-github", to: "/api/auth/github" },
3
- google: { label: "Google", icon: "i-simple-icons-google", to: "/api/auth/google" }
4
- };
@@ -1,14 +0,0 @@
1
- import { defineMenuSource, extendMenuItem } from "@frigear-nu/menu/utils";
2
- export default defineMenuSource(() => {
3
- extendMenuItem("account.dropdown", {
4
- id: "logout",
5
- label: "Logout",
6
- labelKey: "users.menu.logout.label",
7
- description: "Sign out of your account.",
8
- descriptionKey: "users.menu.logout.description",
9
- icon: "i-lucide-log-out",
10
- to: "/auth/logout",
11
- external: true,
12
- order: 99
13
- });
14
- });
@@ -1,19 +0,0 @@
1
- import { db, schema } from "@nuxthub/db";
2
- import { z } from "zod";
3
- const bodySchema = z.object({
4
- email: z.string().email()
5
- });
6
- const RESET_CODE_TTL_MINUTES = 30;
7
- export default defineEventHandler(async (event) => {
8
- const { email } = await readValidatedBody(event, bodySchema.parse);
9
- const user = await db.query.users.findFirst({ where: (t, { eq }) => eq(t.email, email) });
10
- if (!user) {
11
- return { ok: true };
12
- }
13
- const code = createPasswordResetCode();
14
- const expiresAt = new Date(Date.now() + RESET_CODE_TTL_MINUTES * 60 * 1e3);
15
- await db.insert(schema.passwordResets).values({ userId: user.id, code, expiresAt });
16
- const resetUrl = new URL(`/reset-password?code=${code}`, getRequestURL(event).origin).toString();
17
- await dispatchPasswordResetEmail({ to: user.email, resetUrl });
18
- return { ok: true };
19
- });