nuxt-users
Version:
A comprehensive user management module for Nuxt 3 and Nuxt 4 applications with authentication, authorization, database support, and CLI tools
61 lines (60 loc) • 2.15 kB
JavaScript
import { createError, defineEventHandler, getCookie, readBody } from "h3";
import bcrypt from "bcrypt";
import { useRuntimeConfig } from "#imports";
import { getCurrentUserFromToken, updateUserPassword } from "../../../utils/index.js";
import { validatePassword, getPasswordValidationOptions } from "../../../../../utils.js";
export default defineEventHandler(async (event) => {
const { nuxtUsers } = useRuntimeConfig();
const options = nuxtUsers;
const token = getCookie(event, "auth_token");
if (!token) {
throw createError({
statusCode: 401,
statusMessage: "Unauthorized - No authentication token found"
});
}
const user = await getCurrentUserFromToken(token, options, true);
if (!user) {
throw createError({
statusCode: 401,
statusMessage: "Unauthorized - Invalid authentication token"
});
}
const body = await readBody(event);
const { currentPassword, newPassword, newPasswordConfirmation } = body;
if (!currentPassword || typeof currentPassword !== "string") {
throw createError({
statusCode: 400,
statusMessage: "Current password is required"
});
}
if (!newPassword || typeof newPassword !== "string") {
throw createError({
statusCode: 400,
statusMessage: "New password is required"
});
}
if (newPassword !== newPasswordConfirmation) {
throw createError({
statusCode: 400,
statusMessage: "New password confirmation does not match"
});
}
const passwordOptions = getPasswordValidationOptions(options);
const passwordValidation = validatePassword(newPassword, passwordOptions);
if (!passwordValidation.isValid) {
throw createError({
statusCode: 400,
statusMessage: `Password validation failed: ${passwordValidation.errors.join(", ")}`
});
}
const currentPasswordMatch = await bcrypt.compare(currentPassword, user.password);
if (!currentPasswordMatch) {
throw createError({
statusCode: 400,
statusMessage: "Current password is incorrect"
});
}
await updateUserPassword(user.email, newPassword, options);
return { message: "Password updated successfully" };
});