import { NextRequest, NextResponse } from 'next/server' import { prisma } from '@/lib/prisma' import { verifyToken, hashPassword, verifyPassword } from '@/lib/auth' export async function PUT(request: NextRequest) { try { const authHeader = request.headers.get('Authorization') const token = authHeader?.replace('Bearer ', '') if (!token) { return NextResponse.json({ message: '未提供认证令牌' }, { status: 401 }) } const decoded = verifyToken(token) if (!decoded) { return NextResponse.json({ message: '无效的认证令牌' }, { status: 401 }) } const { currentPassword, newPassword } = await request.json() if (!currentPassword || !newPassword) { return NextResponse.json({ message: '请提供当前密码和新密码' }, { status: 400 }) } if (newPassword.length < 6) { return NextResponse.json({ message: '新密码长度至少6位' }, { status: 400 }) } // 获取用户当前信息 const user = await prisma.user.findUnique({ where: { id: decoded.userId } }) if (!user) { return NextResponse.json({ message: '用户不存在' }, { status: 404 }) } // 验证当前密码 const isCurrentPasswordValid = await verifyPassword(currentPassword, user.password) if (!isCurrentPasswordValid) { return NextResponse.json({ message: '当前密码错误' }, { status: 400 }) } // 哈希新密码 const hashedNewPassword = await hashPassword(newPassword) // 更新密码 await prisma.user.update({ where: { id: decoded.userId }, data: { password: hashedNewPassword } }) return NextResponse.json({ message: '密码修改成功' }) } catch (error) { console.error('修改密码失败:', error) return NextResponse.json({ message: '修改密码失败' }, { status: 500 }) } }