aboutsummaryrefslogtreecommitdiff
path: root/src/app/api/user/password/route.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/app/api/user/password/route.ts')
-rw-r--r--src/app/api/user/password/route.ts76
1 files changed, 76 insertions, 0 deletions
diff --git a/src/app/api/user/password/route.ts b/src/app/api/user/password/route.ts
new file mode 100644
index 0000000..9972fb5
--- /dev/null
+++ b/src/app/api/user/password/route.ts
@@ -0,0 +1,76 @@
+import { NextRequest, NextResponse } from "next/server"
+import { getServerSession } from "next-auth/next"
+import bcrypt from "bcryptjs"
+import dbConnect from "@/lib/mongodb"
+import User from "@/model/User"
+import { authOptions } from "@/lib/auth"
+import { updatePasswordSchema } from "@/lib/validation"
+
+export async function PATCH(request: NextRequest) {
+ try {
+ const session = await getServerSession(authOptions)
+
+ if (!session?.user?.id) {
+ return NextResponse.json(
+ { error: "Unauthorized" },
+ { status: 401 }
+ )
+ }
+
+ const body = await request.json()
+
+ const result = updatePasswordSchema.safeParse(body)
+
+ if (!result.success) {
+ return NextResponse.json(
+ { error: "Validation failed", details: result.error.errors },
+ { status: 400 }
+ )
+ }
+
+ const { currentPassword, newPassword } = result.data
+
+ await dbConnect()
+
+ // Get user with current password
+ const user = await User.findById(session.user.id)
+
+ if (!user) {
+ return NextResponse.json(
+ { error: "User not found" },
+ { status: 404 }
+ )
+ }
+
+ // Verify current password
+ const isCurrentPasswordValid = await bcrypt.compare(currentPassword, user.password)
+
+ if (!isCurrentPasswordValid) {
+ return NextResponse.json(
+ { error: "Current password is incorrect" },
+ { status: 400 }
+ )
+ }
+
+ // Hash new password
+ const hashedNewPassword = await bcrypt.hash(newPassword, 12)
+
+ // Update password
+ await User.findByIdAndUpdate(
+ session.user.id,
+ { password: hashedNewPassword }
+ )
+
+ return NextResponse.json({
+ message: "Password updated successfully"
+ })
+
+ } catch (error) {
+ console.error("Password update error:", error)
+
+ return NextResponse.json(
+ { error: "Internal server error" },
+ { status: 500 }
+ )
+ }
+} \ No newline at end of file