nuxt-users 1.9.0 → 1.11.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 (40) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/cli.mjs +1 -1
  3. package/dist/module.d.mts +1 -1
  4. package/dist/module.d.ts +1 -1
  5. package/dist/module.json +2 -2
  6. package/dist/module.mjs +39 -15
  7. package/dist/runtime/components/LoginForm.vue +3 -2
  8. package/dist/runtime/components/ResetPasswordForm.vue +6 -5
  9. package/dist/runtime/composables/useAuthentication.js +5 -7
  10. package/dist/runtime/constants.d.ts +1 -0
  11. package/dist/runtime/constants.js +2 -1
  12. package/dist/runtime/middleware/authorization.client.js +6 -1
  13. package/dist/runtime/server/api/nuxt-users/[id].delete.d.ts +4 -0
  14. package/dist/runtime/server/api/nuxt-users/[id].delete.js +23 -0
  15. package/dist/runtime/server/api/nuxt-users/[id].get.js +32 -0
  16. package/dist/runtime/server/api/nuxt-users/[id].patch.d.ts +4 -0
  17. package/dist/runtime/server/api/nuxt-users/[id].patch.js +24 -0
  18. package/dist/runtime/server/api/nuxt-users/index.post.d.ts +4 -0
  19. package/dist/runtime/server/api/nuxt-users/index.post.js +29 -0
  20. package/dist/runtime/server/api/nuxt-users/me.get.d.ts +4 -0
  21. package/dist/runtime/server/api/{auth/forgot-password.post.js → nuxt-users/password/forgot.post.js} +1 -1
  22. package/dist/runtime/server/api/{auth/update-password.post.js → nuxt-users/password/index.patch.js} +2 -2
  23. package/dist/runtime/server/api/{auth/reset-password.post.js → nuxt-users/password/reset.post.js} +2 -2
  24. package/dist/runtime/server/api/{auth/logout.get.js → nuxt-users/session/index.delete.js} +1 -1
  25. package/dist/runtime/server/api/{auth/login.post.js → nuxt-users/session/index.post.js} +1 -1
  26. package/dist/runtime/server/middleware/authorization.server.js +6 -1
  27. package/dist/runtime/server/utils/user.d.ts +12 -0
  28. package/dist/runtime/server/utils/user.js +54 -0
  29. package/dist/shared/{nuxt-users.CXezgQLO.d.mts → nuxt-users.C7T1DKBV.d.mts} +7 -1
  30. package/dist/shared/{nuxt-users.CXezgQLO.d.ts → nuxt-users.C7T1DKBV.d.ts} +7 -1
  31. package/dist/utils.d.mts +1 -1
  32. package/dist/utils.d.ts +1 -1
  33. package/package.json +2 -2
  34. /package/dist/runtime/server/api/{user/profile.get.d.ts → nuxt-users/[id].get.d.ts} +0 -0
  35. /package/dist/runtime/server/api/{user/profile.get.js → nuxt-users/me.get.js} +0 -0
  36. /package/dist/runtime/server/api/{auth/forgot-password.post.d.ts → nuxt-users/password/forgot.post.d.ts} +0 -0
  37. /package/dist/runtime/server/api/{auth/logout.get.d.ts → nuxt-users/password/index.patch.d.ts} +0 -0
  38. /package/dist/runtime/server/api/{auth/reset-password.post.d.ts → nuxt-users/password/reset.post.d.ts} +0 -0
  39. /package/dist/runtime/server/api/{auth/update-password.post.d.ts → nuxt-users/session/index.delete.d.ts} +0 -0
  40. /package/dist/runtime/server/api/{auth/login.post.d.ts → nuxt-users/session/index.post.d.ts} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,6 +1,44 @@
1
1
  # Changelog
2
2
 
3
3
 
4
+ ## v1.11.0
5
+
6
+ [compare changes](https://github.com/rrd108/nuxt-users/compare/v1.9.0...v1.11.0)
7
+
8
+ ### 🚀 Enhancements
9
+
10
+ - Add user CRUD API endpoints ([8cf5e0a](https://github.com/rrd108/nuxt-users/commit/8cf5e0a))
11
+ - Add user API endpoints ([05f326e](https://github.com/rrd108/nuxt-users/commit/05f326e))
12
+
13
+ ### 💅 Refactors
14
+
15
+ - API endpoints ([784dca4](https://github.com/rrd108/nuxt-users/commit/784dca4))
16
+
17
+ ### 🏡 Chore
18
+
19
+ - **release:** V1.10.0 ([d6100db](https://github.com/rrd108/nuxt-users/commit/d6100db))
20
+
21
+ ### ✅ Tests
22
+
23
+ - Skip for jiti error ([ce562c5](https://github.com/rrd108/nuxt-users/commit/ce562c5))
24
+
25
+ ### ❤️ Contributors
26
+
27
+ - Rrd108 ([@rrd108](https://github.com/rrd108))
28
+
29
+ ## v1.10.0
30
+
31
+ [compare changes](https://github.com/rrd108/nuxt-users/compare/v1.9.0...v1.10.0)
32
+
33
+ ### 🚀 Enhancements
34
+
35
+ - Add user CRUD API endpoints ([8cf5e0a](https://github.com/rrd108/nuxt-users/commit/8cf5e0a))
36
+ - Add user API endpoints ([05f326e](https://github.com/rrd108/nuxt-users/commit/05f326e))
37
+
38
+ ### ❤️ Contributors
39
+
40
+ - Rrd108 ([@rrd108](https://github.com/rrd108))
41
+
4
42
  ## v2.0.0
5
43
 
6
44
  [compare changes](https://github.com/rrd108/nuxt-users/compare/v1.8.5...v2.0.0)
package/dist/cli.mjs CHANGED
@@ -248,7 +248,7 @@ const main = defineCommand({
248
248
  meta: {
249
249
  name: "nuxt-users",
250
250
  description: "CLI for Nuxt Users Module - Manage users, migrations, and database operations",
251
- version: "1.8.5"
251
+ version: "1.10.0"
252
252
  },
253
253
  subCommands: {
254
254
  migrate,
package/dist/module.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
- import { R as RuntimeModuleOptions, M as ModuleOptions } from './shared/nuxt-users.CXezgQLO.mjs';
2
+ import { R as RuntimeModuleOptions, M as ModuleOptions } from './shared/nuxt-users.C7T1DKBV.mjs';
3
3
  export * from '../dist/runtime/server/utils/index.js';
4
4
 
5
5
  declare const defaultOptions: ModuleOptions;
package/dist/module.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
- import { R as RuntimeModuleOptions, M as ModuleOptions } from './shared/nuxt-users.CXezgQLO.js';
2
+ import { R as RuntimeModuleOptions, M as ModuleOptions } from './shared/nuxt-users.C7T1DKBV.js';
3
3
  export * from '../dist/runtime/server/utils/index.js';
4
4
 
5
5
  declare const defaultOptions: ModuleOptions;
package/dist/module.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "nuxt-users",
3
3
  "configKey": "nuxtUsers",
4
- "version": "1.9.0",
4
+ "version": "1.11.0",
5
5
  "builder": {
6
- "@nuxt/module-builder": "1.0.1",
6
+ "@nuxt/module-builder": "1.0.2",
7
7
  "unbuild": "3.6.0"
8
8
  }
9
9
  }
package/dist/module.mjs CHANGED
@@ -9,6 +9,7 @@ const defaultOptions = {
9
9
  path: "./data/users.sqlite3"
10
10
  }
11
11
  },
12
+ apiBasePath: "/api/nuxt-users",
12
13
  tables: {
13
14
  migrations: "migrations",
14
15
  users: "users",
@@ -59,6 +60,7 @@ const module = defineNuxtModule({
59
60
  const runtimeConfigOptions = defu(options, nuxt.options.runtimeConfig.nuxtUsers || {}, defaultOptions);
60
61
  nuxt.options.runtimeConfig.nuxtUsers = {
61
62
  ...runtimeConfigOptions,
63
+ apiBasePath: options.apiBasePath || defaultOptions.apiBasePath,
62
64
  tables: {
63
65
  migrations: options.tables?.migrations || defaultOptions.tables.migrations,
64
66
  users: options.tables?.users || defaultOptions.tables.users,
@@ -84,7 +86,8 @@ const module = defineNuxtModule({
84
86
  auth: {
85
87
  whitelist: [...defaultOptions.auth?.whitelist || [], ...options.auth?.whitelist || []],
86
88
  permissions: options.auth?.permissions || defaultOptions.auth.permissions
87
- }
89
+ },
90
+ apiBasePath: options.apiBasePath || defaultOptions.apiBasePath
88
91
  };
89
92
  addPlugin({
90
93
  src: resolver.resolve("./runtime/plugin"),
@@ -96,35 +99,56 @@ const module = defineNuxtModule({
96
99
  path: resolver.resolve("./runtime/middleware/authorization.client"),
97
100
  global: true
98
101
  });
102
+ const base = nuxt.options.runtimeConfig.nuxtUsers.apiBasePath || defaultOptions.apiBasePath;
103
+ addServerHandler({
104
+ route: `${base}/session`,
105
+ method: "post",
106
+ handler: resolver.resolve("./runtime/server/api/nuxt-users/session/index.post")
107
+ });
108
+ addServerHandler({
109
+ route: `${base}/session`,
110
+ method: "delete",
111
+ handler: resolver.resolve("./runtime/server/api/nuxt-users/session/index.delete")
112
+ });
99
113
  addServerHandler({
100
- route: "/api/auth/login",
114
+ route: `${base}/me`,
115
+ method: "get",
116
+ handler: resolver.resolve("./runtime/server/api/nuxt-users/me.get")
117
+ });
118
+ addServerHandler({
119
+ route: `${base}/password`,
120
+ method: "patch",
121
+ handler: resolver.resolve("./runtime/server/api/nuxt-users/password/index.patch")
122
+ });
123
+ addServerHandler({
124
+ route: `${base}/password/forgot`,
101
125
  method: "post",
102
- handler: resolver.resolve("./runtime/server/api/auth/login.post")
126
+ handler: resolver.resolve("./runtime/server/api/nuxt-users/password/forgot.post")
103
127
  });
104
128
  addServerHandler({
105
- route: "/api/auth/forgot-password",
129
+ route: `${base}/password/reset`,
106
130
  method: "post",
107
- handler: resolver.resolve("./runtime/server/api/auth/forgot-password.post")
131
+ handler: resolver.resolve("./runtime/server/api/nuxt-users/password/reset.post")
108
132
  });
109
133
  addServerHandler({
110
- route: "/api/auth/reset-password",
134
+ route: `${base}`,
111
135
  method: "post",
112
- handler: resolver.resolve("./runtime/server/api/auth/reset-password.post")
136
+ handler: resolver.resolve("./runtime/server/api/nuxt-users/index.post")
113
137
  });
114
138
  addServerHandler({
115
- route: "/api/auth/logout",
139
+ route: `${base}/:id`,
116
140
  method: "get",
117
- handler: resolver.resolve("./runtime/server/api/auth/logout.get")
141
+ handler: resolver.resolve("./runtime/server/api/nuxt-users/[id].get")
118
142
  });
119
143
  addServerHandler({
120
- route: "/api/user/profile",
121
- method: "get",
122
- handler: resolver.resolve("./runtime/server/api/user/profile.get")
144
+ route: `${base}/:id`,
145
+ method: "patch",
146
+ handler: resolver.resolve("./runtime/server/api/nuxt-users/[id].patch")
123
147
  });
124
148
  addServerHandler({
125
- route: "/api/auth/update-password",
126
- method: "post",
127
- handler: resolver.resolve("./runtime/server/api/auth/update-password.post")
149
+ route: `${base}/:id`,
150
+ method: "delete",
151
+ handler: resolver.resolve("./runtime/server/api/nuxt-users/[id].delete")
128
152
  });
129
153
  nuxt.hook("nitro:config", async (nitroConfig) => {
130
154
  nitroConfig.experimental = nitroConfig.experimental || {};
@@ -4,10 +4,11 @@ import { navigateTo } from "#app";
4
4
  import { useRuntimeConfig } from "#imports";
5
5
  const { public: { nuxtUsers } } = useRuntimeConfig();
6
6
  const { passwordValidation } = nuxtUsers;
7
+ const apiBasePath = nuxtUsers?.apiBasePath;
7
8
  const props = defineProps({
8
- apiEndpoint: { type: String, required: false, default: "/api/auth/login" },
9
+ apiEndpoint: { type: String, required: false, default: `${apiBasePath}/session` },
9
10
  redirectTo: { type: String, required: false, default: "/" },
10
- forgotPasswordEndpoint: { type: String, required: false, default: "/api/auth/forgot-password" }
11
+ forgotPasswordEndpoint: { type: String, required: false, default: `${apiBasePath}/password/forgot` }
11
12
  });
12
13
  const emit = defineEmits(["success", "error", "forgot-password-error", "submit", "forgot-password-success"]);
13
14
  const isLoading = ref(false);
@@ -3,9 +3,12 @@ import { ref, watch } from "vue";
3
3
  import { usePasswordValidation } from "../composables/usePasswordValidation";
4
4
  import { useRuntimeConfig } from "#imports";
5
5
  import PasswordStrengthIndicator from "./PasswordStrengthIndicator.vue";
6
+ const { public: { nuxtUsers } } = useRuntimeConfig();
7
+ const apiBasePath = nuxtUsers?.apiBasePath;
8
+ const moduleOptions = nuxtUsers;
6
9
  const props = defineProps({
7
- apiEndpoint: { type: String, required: false, default: "/api/user/profile" },
8
- updatePasswordEndpoint: { type: String, required: false, default: "/api/auth/update-password" }
10
+ apiEndpoint: { type: String, required: false, default: `${apiBasePath}/me` },
11
+ updatePasswordEndpoint: { type: String, required: false, default: `${apiBasePath}/password` }
9
12
  });
10
13
  const emit = defineEmits(["success", "error", "password-error", "password-updated"]);
11
14
  const isPasswordLoading = ref(false);
@@ -16,8 +19,6 @@ const passwordForm = ref({
16
19
  newPassword: "",
17
20
  newPasswordConfirmation: ""
18
21
  });
19
- const { public: { nuxtUsers } } = useRuntimeConfig();
20
- const moduleOptions = nuxtUsers;
21
22
  const passwordValidation = usePasswordValidation(moduleOptions);
22
23
  watch(() => passwordForm.value.newPassword, (newPassword) => {
23
24
  if (newPassword) {
@@ -32,7 +33,7 @@ const updatePassword = async () => {
32
33
  passwordSuccess.value = "";
33
34
  try {
34
35
  await $fetch(props.updatePasswordEndpoint, {
35
- method: "POST",
36
+ method: "PATCH",
36
37
  body: passwordForm.value
37
38
  });
38
39
  passwordSuccess.value = "Password updated successfully";
@@ -1,7 +1,9 @@
1
- import { useState } from "#app";
1
+ import { useState, useRuntimeConfig } from "#app";
2
2
  import { computed, readonly } from "vue";
3
3
  export const useAuthentication = () => {
4
4
  const user = useState("user", () => null);
5
+ const { public: { nuxtUsers } } = useRuntimeConfig();
6
+ const apiBasePath = nuxtUsers?.apiBasePath;
5
7
  const isAuthenticated = computed(() => !!user.value);
6
8
  const login = (userData) => {
7
9
  const { password: _, ...userWithoutPassword } = userData;
@@ -12,9 +14,7 @@ export const useAuthentication = () => {
12
14
  };
13
15
  const logout = async () => {
14
16
  try {
15
- await $fetch("/api/auth/logout", {
16
- method: "GET"
17
- });
17
+ await $fetch(`${apiBasePath}/session`, { method: "DELETE" });
18
18
  user.value = null;
19
19
  if (import.meta.client) {
20
20
  localStorage.removeItem("user");
@@ -26,9 +26,7 @@ export const useAuthentication = () => {
26
26
  };
27
27
  const fetchUser = async () => {
28
28
  try {
29
- const response = await $fetch("/api/user/profile", {
30
- method: "GET"
31
- });
29
+ const response = await $fetch(`${apiBasePath}/me`, { method: "GET" });
32
30
  user.value = response.user;
33
31
  if (import.meta.client) {
34
32
  localStorage.setItem("user", JSON.stringify(response.user));
@@ -1 +1,2 @@
1
1
  export declare const NO_AUTH_PATHS: string[];
2
+ export declare const NO_AUTH_API_PATHS: string[];
@@ -1 +1,2 @@
1
- export const NO_AUTH_PATHS = ["/login", "/api/auth/login", "/api/auth/forgot-password"];
1
+ export const NO_AUTH_PATHS = ["/login"];
2
+ export const NO_AUTH_API_PATHS = ["/session", "/password/forgot", "/password/reset"];
@@ -1,14 +1,19 @@
1
1
  import { defineNuxtRouteMiddleware, navigateTo, useRuntimeConfig } from "#app";
2
2
  import { useAuthentication } from "../composables/useAuthentication.js";
3
3
  import { hasPermission, isWhitelisted } from "../utils/permissions.js";
4
- import { NO_AUTH_PATHS } from "../constants.js";
4
+ import { NO_AUTH_PATHS, NO_AUTH_API_PATHS } from "../constants.js";
5
5
  export default defineNuxtRouteMiddleware((to) => {
6
6
  const { public: { nuxtUsers: publicNuxtUsers } } = useRuntimeConfig();
7
7
  const publicOptions = publicNuxtUsers;
8
+ const base = publicOptions.apiBasePath || "/api/nuxt-users";
8
9
  if (NO_AUTH_PATHS.includes(to.path)) {
9
10
  console.log(`[Nuxt Users] client.middleware.auth.global: ${to.path}`);
10
11
  return;
11
12
  }
13
+ const openApiPaths = NO_AUTH_API_PATHS.map((path) => `${base}${path}`);
14
+ if (openApiPaths.includes(to.path)) {
15
+ return;
16
+ }
12
17
  if (isWhitelisted(to.path, publicOptions.auth.whitelist)) {
13
18
  console.log(`[Nuxt Users] client.middleware.auth.global: Whitelisted: ${to.path}`);
14
19
  return;
@@ -0,0 +1,4 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ success: boolean;
3
+ }>>;
4
+ export default _default;
@@ -0,0 +1,23 @@
1
+ import { createError, defineEventHandler } from "h3";
2
+ import { useRuntimeConfig } from "#imports";
3
+ import { deleteUser } from "../../utils/user.js";
4
+ export default defineEventHandler(async (event) => {
5
+ const { nuxtUsers } = useRuntimeConfig();
6
+ const options = nuxtUsers;
7
+ const userId = Number(event.context.params?.id);
8
+ if (!userId) {
9
+ throw createError({
10
+ statusCode: 400,
11
+ statusMessage: "Invalid user ID"
12
+ });
13
+ }
14
+ try {
15
+ await deleteUser(userId, options);
16
+ return { success: true };
17
+ } catch (error) {
18
+ throw createError({
19
+ statusCode: 500,
20
+ statusMessage: `Error deleting user: ${error.message}`
21
+ });
22
+ }
23
+ });
@@ -0,0 +1,32 @@
1
+ import { createError, defineEventHandler } from "h3";
2
+ import { useRuntimeConfig } from "#imports";
3
+ import { findUserById } from "../../utils/user.js";
4
+ export default defineEventHandler(async (event) => {
5
+ const { nuxtUsers } = useRuntimeConfig();
6
+ const options = nuxtUsers;
7
+ const userId = Number(event.context.params?.id);
8
+ if (!userId) {
9
+ throw createError({
10
+ statusCode: 400,
11
+ statusMessage: "Invalid user ID"
12
+ });
13
+ }
14
+ try {
15
+ const user = await findUserById(userId, options);
16
+ if (!user) {
17
+ throw createError({
18
+ statusCode: 404,
19
+ statusMessage: "User not found"
20
+ });
21
+ }
22
+ return { user };
23
+ } catch (error) {
24
+ if (error && typeof error === "object" && "statusCode" in error) {
25
+ throw error;
26
+ }
27
+ throw createError({
28
+ statusCode: 500,
29
+ statusMessage: `Error fetching user: ${error instanceof Error ? error.message : String(error)}`
30
+ });
31
+ }
32
+ });
@@ -0,0 +1,4 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ user: import("../../../../types.js").UserWithoutPassword;
3
+ }>>;
4
+ export default _default;
@@ -0,0 +1,24 @@
1
+ import { createError, defineEventHandler, readBody } from "h3";
2
+ import { useRuntimeConfig } from "#imports";
3
+ import { updateUser } from "../../utils/user.js";
4
+ export default defineEventHandler(async (event) => {
5
+ const { nuxtUsers } = useRuntimeConfig();
6
+ const options = nuxtUsers;
7
+ const userId = Number(event.context.params?.id);
8
+ if (!userId) {
9
+ throw createError({
10
+ statusCode: 400,
11
+ statusMessage: "Invalid user ID"
12
+ });
13
+ }
14
+ const body = await readBody(event);
15
+ try {
16
+ const updatedUser = await updateUser(userId, body, options);
17
+ return { user: updatedUser };
18
+ } catch (error) {
19
+ throw createError({
20
+ statusCode: 500,
21
+ statusMessage: `Error updating user: ${error.message}`
22
+ });
23
+ }
24
+ });
@@ -0,0 +1,4 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ user: Omit<import("../../../../types.js").User, "password">;
3
+ }>>;
4
+ export default _default;
@@ -0,0 +1,29 @@
1
+ import { createError, defineEventHandler, readBody } from "h3";
2
+ import { useRuntimeConfig } from "#imports";
3
+ import { createUser } from "../../utils/user.js";
4
+ export default defineEventHandler(async (event) => {
5
+ const { nuxtUsers } = useRuntimeConfig();
6
+ const options = nuxtUsers;
7
+ const body = await readBody(event);
8
+ if (!body.email || !body.name || !body.password) {
9
+ throw createError({
10
+ statusCode: 400,
11
+ statusMessage: "Missing required fields: email, name, password"
12
+ });
13
+ }
14
+ try {
15
+ const newUser = await createUser({
16
+ email: body.email,
17
+ name: body.name,
18
+ password: body.password,
19
+ role: body.role
20
+ // role is optional
21
+ }, options);
22
+ return { user: newUser };
23
+ } catch (error) {
24
+ throw createError({
25
+ statusCode: 500,
26
+ statusMessage: `Error creating user: ${error.message}`
27
+ });
28
+ }
29
+ });
@@ -0,0 +1,4 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ user: import("../../../../types.js").UserWithoutPassword;
3
+ }>>;
4
+ export default _default;
@@ -1,5 +1,5 @@
1
1
  import { defineEventHandler, readBody, createError } from "h3";
2
- import { sendPasswordResetLink } from "../../services/password.js";
2
+ import { sendPasswordResetLink } from "../../../services/password.js";
3
3
  export default defineEventHandler(async (event) => {
4
4
  const body = await readBody(event);
5
5
  const { email } = body;
@@ -1,8 +1,8 @@
1
1
  import { createError, defineEventHandler, getCookie, readBody } from "h3";
2
2
  import bcrypt from "bcrypt";
3
3
  import { useRuntimeConfig } from "#imports";
4
- import { getCurrentUserFromToken, updateUserPassword } from "../../utils/index.js";
5
- import { validatePassword, getPasswordValidationOptions } from "../../../../utils.js";
4
+ import { getCurrentUserFromToken, updateUserPassword } from "../../../utils/index.js";
5
+ import { validatePassword, getPasswordValidationOptions } from "../../../../../utils.js";
6
6
  export default defineEventHandler(async (event) => {
7
7
  const { nuxtUsers } = useRuntimeConfig();
8
8
  const options = nuxtUsers;
@@ -1,7 +1,7 @@
1
1
  import { defineEventHandler, readBody, createError, H3Error } from "h3";
2
- import { resetPassword } from "../../services/password.js";
2
+ import { resetPassword } from "../../../services/password.js";
3
3
  import { useRuntimeConfig } from "#imports";
4
- import { validatePassword, getPasswordValidationOptions } from "../../../../utils.js";
4
+ import { validatePassword, getPasswordValidationOptions } from "../../../../../utils.js";
5
5
  export default defineEventHandler(async (event) => {
6
6
  const body = await readBody(event);
7
7
  const { token, email, password, password_confirmation } = body;
@@ -1,6 +1,6 @@
1
1
  import { defineEventHandler, getCookie, setCookie } from "h3";
2
2
  import { useRuntimeConfig } from "#imports";
3
- import { useDb } from "../../utils/index.js";
3
+ import { useDb } from "../../../utils/index.js";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const { nuxtUsers } = useRuntimeConfig();
6
6
  const options = nuxtUsers;
@@ -2,7 +2,7 @@ import { createError, defineEventHandler, readBody, setCookie } from "h3";
2
2
  import bcrypt from "bcrypt";
3
3
  import crypto from "node:crypto";
4
4
  import { useRuntimeConfig } from "#imports";
5
- import { useDb } from "../../utils/index.js";
5
+ import { useDb } from "../../../utils/index.js";
6
6
  export default defineEventHandler(async (event) => {
7
7
  const body = await readBody(event);
8
8
  const { email, password } = body;
@@ -2,10 +2,11 @@ import { defineEventHandler, getCookie, sendRedirect } from "h3";
2
2
  import { useRuntimeConfig } from "#imports";
3
3
  import { getCurrentUserFromToken } from "../utils/index.js";
4
4
  import { hasPermission, isWhitelisted } from "../../utils/permissions.js";
5
- import { NO_AUTH_PATHS } from "../../constants.js";
5
+ import { NO_AUTH_PATHS, NO_AUTH_API_PATHS } from "../../constants.js";
6
6
  export default defineEventHandler(async (event) => {
7
7
  const { nuxtUsers } = useRuntimeConfig();
8
8
  const options = nuxtUsers;
9
+ const base = options.apiBasePath || "/api/nuxt-users";
9
10
  const isPageOrApiRoute = !event.path.includes(".") && (event.path === "/" || event.path.startsWith("/api/") || !event.path.startsWith("/_"));
10
11
  if (!isPageOrApiRoute) {
11
12
  return;
@@ -14,6 +15,10 @@ export default defineEventHandler(async (event) => {
14
15
  console.log("[Nuxt Users] server.middleware.auth.global: /login");
15
16
  return;
16
17
  }
18
+ const openApiPaths = NO_AUTH_API_PATHS.map((path) => `${base}${path}`);
19
+ if (openApiPaths.includes(event.path)) {
20
+ return;
21
+ }
17
22
  if (isWhitelisted(event.path, options.auth.whitelist)) {
18
23
  console.log(`[Nuxt Users] server.middleware.auth.global: whitelisted: ${event.path}`);
19
24
  return;
@@ -14,6 +14,18 @@ export declare const createUser: (userData: CreateUserParams, options: ModuleOpt
14
14
  * Finds a user by their email address.
15
15
  */
16
16
  export declare const findUserByEmail: (email: string, options: ModuleOptions) => Promise<User | null>;
17
+ /**
18
+ * Finds a user by their ID.
19
+ */
20
+ export declare const findUserById: <T extends boolean = false>(id: number, options: ModuleOptions, withPass?: T) => Promise<T extends true ? User | null : UserWithoutPassword | null>;
21
+ /**
22
+ * Updates a user's details.
23
+ */
24
+ export declare const updateUser: (id: number, userData: Partial<User>, options: ModuleOptions) => Promise<UserWithoutPassword>;
25
+ /**
26
+ * Deletes a user by their ID.
27
+ */
28
+ export declare const deleteUser: (id: number, options: ModuleOptions) => Promise<void>;
17
29
  /**
18
30
  * Updates a user's password.
19
31
  * Hashes the new password before storing.
@@ -47,6 +47,60 @@ export const findUserByEmail = async (email, options) => {
47
47
  updated_at: user.updated_at instanceof Date ? user.updated_at.toISOString() : user.updated_at
48
48
  };
49
49
  };
50
+ export const findUserById = async (id, options, withPass = false) => {
51
+ const db = await useDb(options);
52
+ const usersTable = options.tables.users;
53
+ const result = await db.sql`SELECT * FROM {${usersTable}} WHERE id = ${id}`;
54
+ if (result.rows.length === 0) {
55
+ return null;
56
+ }
57
+ const user = result.rows[0];
58
+ const normalizedUser = {
59
+ ...user,
60
+ created_at: typeof user.created_at === "object" ? user.created_at.toISOString() : user.created_at,
61
+ updated_at: typeof user.updated_at === "object" ? user.updated_at.toISOString() : user.updated_at
62
+ };
63
+ if (withPass === true) {
64
+ return normalizedUser;
65
+ }
66
+ const { password, ...userWithoutPassword } = normalizedUser;
67
+ return userWithoutPassword;
68
+ };
69
+ export const updateUser = async (id, userData, options) => {
70
+ const db = await useDb(options);
71
+ const usersTable = options.tables.users;
72
+ const currentUser = await findUserById(id, options, true);
73
+ if (!currentUser) {
74
+ throw new Error("User not found.");
75
+ }
76
+ const fieldsToUpdate = { ...userData };
77
+ delete fieldsToUpdate.id;
78
+ delete fieldsToUpdate.password;
79
+ if (Object.keys(fieldsToUpdate).length === 0) {
80
+ const { password, ...user } = currentUser;
81
+ return user;
82
+ }
83
+ for (const [key, value] of Object.entries(fieldsToUpdate)) {
84
+ await db.sql`
85
+ UPDATE {${usersTable}}
86
+ SET ${key} = ${value}, updated_at = CURRENT_TIMESTAMP
87
+ WHERE id = ${id}
88
+ `;
89
+ }
90
+ const updatedUser = await findUserById(id, options);
91
+ if (!updatedUser) {
92
+ throw new Error("Failed to retrieve updated user.");
93
+ }
94
+ return updatedUser;
95
+ };
96
+ export const deleteUser = async (id, options) => {
97
+ const db = await useDb(options);
98
+ const usersTable = options.tables.users;
99
+ const result = await db.sql`DELETE FROM {${usersTable}} WHERE id = ${id}`;
100
+ if (result.rows?.length === 0) {
101
+ throw new Error("User not found or could not be deleted.");
102
+ }
103
+ };
50
104
  export const updateUserPassword = async (email, newPassword, options) => {
51
105
  const db = await useDb(options);
52
106
  const usersTable = options.tables.users;
@@ -12,6 +12,11 @@ interface RuntimeModuleOptions {
12
12
  name: DatabaseType;
13
13
  options: DatabaseConfig;
14
14
  };
15
+ /**
16
+ * Base path for all module API endpoints
17
+ * @default '/api/nuxt-users'
18
+ */
19
+ apiBasePath?: string;
15
20
  tables?: {
16
21
  migrations?: string;
17
22
  users?: string;
@@ -49,7 +54,7 @@ interface RuntimeModuleOptions {
49
54
  * @default {}
50
55
  * @example {
51
56
  * admin: ['*'], // admin can access everything
52
- * user: ['/profile', '/api/user/profile'],
57
+ * user: ['/profile', '/api/nuxt-users/me'],
53
58
  * moderator: ['/admin/*', '/api/admin/*']
54
59
  * }
55
60
  */
@@ -96,6 +101,7 @@ interface ModuleOptions {
96
101
  name: DatabaseType;
97
102
  options: DatabaseConfig;
98
103
  };
104
+ apiBasePath: string;
99
105
  tables: {
100
106
  migrations: string;
101
107
  users: string;
@@ -12,6 +12,11 @@ interface RuntimeModuleOptions {
12
12
  name: DatabaseType;
13
13
  options: DatabaseConfig;
14
14
  };
15
+ /**
16
+ * Base path for all module API endpoints
17
+ * @default '/api/nuxt-users'
18
+ */
19
+ apiBasePath?: string;
15
20
  tables?: {
16
21
  migrations?: string;
17
22
  users?: string;
@@ -49,7 +54,7 @@ interface RuntimeModuleOptions {
49
54
  * @default {}
50
55
  * @example {
51
56
  * admin: ['*'], // admin can access everything
52
- * user: ['/profile', '/api/user/profile'],
57
+ * user: ['/profile', '/api/nuxt-users/me'],
53
58
  * moderator: ['/admin/*', '/api/admin/*']
54
59
  * }
55
60
  */
@@ -96,6 +101,7 @@ interface ModuleOptions {
96
101
  name: DatabaseType;
97
102
  options: DatabaseConfig;
98
103
  };
104
+ apiBasePath: string;
99
105
  tables: {
100
106
  migrations: string;
101
107
  users: string;
package/dist/utils.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- export { L as LoginFormData, M as ModuleOptions, b as PasswordResetToken, P as PersonalAccessToken, U as User, a as UserWithoutPassword } from './shared/nuxt-users.CXezgQLO.mjs';
1
+ export { L as LoginFormData, M as ModuleOptions, b as PasswordResetToken, P as PersonalAccessToken, U as User, a as UserWithoutPassword } from './shared/nuxt-users.C7T1DKBV.mjs';
2
2
  export { findUserByEmail, getCurrentUserFromToken, getLastLoginTime } from '../dist/runtime/server/utils/user.js';
3
3
 
4
4
  interface PasswordValidationResult {
package/dist/utils.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { L as LoginFormData, M as ModuleOptions, b as PasswordResetToken, P as PersonalAccessToken, U as User, a as UserWithoutPassword } from './shared/nuxt-users.CXezgQLO.js';
1
+ export { L as LoginFormData, M as ModuleOptions, b as PasswordResetToken, P as PersonalAccessToken, U as User, a as UserWithoutPassword } from './shared/nuxt-users.C7T1DKBV.js';
2
2
  export { findUserByEmail, getCurrentUserFromToken, getLastLoginTime } from '../dist/runtime/server/utils/user.js';
3
3
 
4
4
  interface PasswordValidationResult {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nuxt-users",
3
- "version": "1.9.0",
3
+ "version": "1.11.0",
4
4
  "description": "A comprehensive user management module for Nuxt 3 and Nuxt 4 applications with authentication, authorization, database support, and CLI tools",
5
5
  "keywords": [
6
6
  "nuxt",
@@ -111,7 +111,7 @@
111
111
  "@nuxt/devtools": "^2.6.2",
112
112
  "@nuxt/eslint-config": "^1.5.2",
113
113
  "@nuxt/kit": "^3.17.6",
114
- "@nuxt/module-builder": "^1.0.1",
114
+ "@nuxt/module-builder": "^1.0.2",
115
115
  "@nuxt/schema": "^3.17.6",
116
116
  "@nuxt/test-utils": "^3.19.2",
117
117
  "@types/bcrypt": "^6.0.0",