69 lines
2.0 KiB
TypeScript
69 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server"
|
|
import { getServerSession } from "next-auth"
|
|
import { authOptions } from "@/lib/auth"
|
|
import { prisma } from "@/lib/prisma"
|
|
import bcrypt from "bcryptjs"
|
|
import { z } from "zod"
|
|
|
|
const changePasswordSchema = z.object({
|
|
currentPassword: z.string().min(1, "请输入当前密码"),
|
|
newPassword: z.string().min(6, "新密码至少需要6个字符"),
|
|
confirmPassword: z.string().min(1, "请确认新密码"),
|
|
}).refine((data) => data.newPassword === data.confirmPassword, {
|
|
message: "两次输入的密码不一致",
|
|
path: ["confirmPassword"],
|
|
})
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions)
|
|
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: "未授权" }, { status: 401 })
|
|
}
|
|
|
|
const body = await req.json()
|
|
const { currentPassword, newPassword } = changePasswordSchema.parse(body)
|
|
|
|
// 获取用户当前密码
|
|
const user = await prisma.user.findUnique({
|
|
where: { id: session.user.id },
|
|
select: { password: true }
|
|
})
|
|
|
|
if (!user || !user.password) {
|
|
return NextResponse.json({ error: "用户不存在" }, { status: 404 })
|
|
}
|
|
|
|
// 验证当前密码
|
|
const isValid = await bcrypt.compare(currentPassword, user.password)
|
|
if (!isValid) {
|
|
return NextResponse.json({ error: "当前密码错误" }, { status: 400 })
|
|
}
|
|
|
|
// 加密新密码
|
|
const hashedPassword = await bcrypt.hash(newPassword, 10)
|
|
|
|
// 更新密码
|
|
await prisma.user.update({
|
|
where: { id: session.user.id },
|
|
data: { password: hashedPassword }
|
|
})
|
|
|
|
return NextResponse.json({ message: "密码修改成功" })
|
|
} catch (error) {
|
|
if (error instanceof z.ZodError) {
|
|
return NextResponse.json(
|
|
{ error: error.errors[0].message },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
console.error("修改密码失败:", error)
|
|
return NextResponse.json(
|
|
{ error: "修改密码失败,请稍后重试" },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|