monaco-editor-lsp-next/src/app/(protected)/dashboard/management/actions/changePassword.ts

59 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-06-20 12:18:13 +00:00
"use server";
2025-06-21 15:19:49 +00:00
import bcrypt from "bcryptjs";
2025-06-21 09:44:14 +00:00
import { auth } from "@/lib/auth";
import prisma from "@/lib/prisma";
2025-06-20 12:18:13 +00:00
export async function changePassword(formData: FormData) {
const oldPassword = formData.get("oldPassword") as string;
const newPassword = formData.get("newPassword") as string;
if (!oldPassword || !newPassword) {
throw new Error("旧密码和新密码不能为空");
}
try {
2025-06-21 09:44:14 +00:00
// 获取当前登录用户
const session = await auth();
const userId = session?.user?.id;
if (!userId) {
throw new Error("用户未登录");
}
// 查询当前用户信息
2025-06-20 12:18:13 +00:00
const user = await prisma.user.findUnique({
2025-06-21 09:44:14 +00:00
where: { id: userId },
2025-06-20 12:18:13 +00:00
});
2025-06-21 09:44:14 +00:00
if (!user) {
throw new Error("用户不存在");
}
2025-06-20 12:18:13 +00:00
if (!user.password) {
throw new Error("用户密码未设置");
}
2025-06-21 09:44:14 +00:00
// 验证旧密码
2025-06-20 12:18:13 +00:00
const passwordHash: string = user.password as string;
const isMatch = await bcrypt.compare(oldPassword, passwordHash);
2025-06-21 09:44:14 +00:00
if (!isMatch) {
throw new Error("旧密码错误");
}
2025-06-20 12:18:13 +00:00
2025-06-21 09:44:14 +00:00
// 加密新密码
2025-06-20 12:18:13 +00:00
const hashedPassword = await bcrypt.hash(newPassword, 10);
2025-06-21 09:44:14 +00:00
// 更新密码
2025-06-20 12:18:13 +00:00
await prisma.user.update({
2025-06-21 09:44:14 +00:00
where: { id: userId },
2025-06-20 12:18:13 +00:00
data: { password: hashedPassword },
});
return { success: true };
} catch (error) {
console.error("修改密码失败:", error);
throw new Error("修改密码失败");
}
2025-06-21 15:19:49 +00:00
}