85 lines
2.0 KiB
TypeScript
85 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'
|
|
|
|
// 修改密码
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions)
|
|
|
|
if (!session?.user?.email) {
|
|
return NextResponse.json(
|
|
{ error: '未登录' },
|
|
{ status: 401 }
|
|
)
|
|
}
|
|
|
|
const { oldPassword, newPassword } = await req.json()
|
|
|
|
if (!oldPassword || !newPassword) {
|
|
return NextResponse.json(
|
|
{ error: '请提供旧密码和新密码' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
if (newPassword.length < 6) {
|
|
return NextResponse.json(
|
|
{ error: '新密码长度至少为6位' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const user = await prisma.user.findUnique({
|
|
where: { email: session.user.email }
|
|
})
|
|
|
|
if (!user) {
|
|
return NextResponse.json(
|
|
{ error: '用户不存在' },
|
|
{ status: 404 }
|
|
)
|
|
}
|
|
|
|
// 验证旧密码
|
|
const isOldPasswordValid = await bcrypt.compare(oldPassword, user.password)
|
|
|
|
if (!isOldPasswordValid) {
|
|
return NextResponse.json(
|
|
{ error: '旧密码错误' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 检查新密码是否与旧密码相同
|
|
const isSamePassword = await bcrypt.compare(newPassword, user.password)
|
|
if (isSamePassword) {
|
|
return NextResponse.json(
|
|
{ error: '新密码不能与旧密码相同' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 更新密码
|
|
const hashedNewPassword = await bcrypt.hash(newPassword, 10)
|
|
await prisma.user.update({
|
|
where: { id: user.id },
|
|
data: { password: hashedNewPassword }
|
|
})
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: '密码修改成功'
|
|
})
|
|
} catch (error: any) {
|
|
console.error('修改密码失败:', error)
|
|
return NextResponse.json(
|
|
{ error: '修改密码失败' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|