fix: Corrige sistema de recuperação de senha (Esqueci minha senha)

- Corrige nomes de colunas SQL (expires_at -> expiresAt)
- Link de reset agora aparece na tela
- Adiciona documentação de solução
- Sistema totalmente funcional
This commit is contained in:
2025-11-21 14:29:20 +00:00
parent 0524656198
commit 45f819b95d
5 changed files with 827 additions and 0 deletions

View File

@@ -0,0 +1,102 @@
// app/api/auth/reset-password/route.ts
import { NextRequest, NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { hashPassword } from "@/lib/auth/credentials"
export async function POST(request: NextRequest) {
try {
const { token, password } = await request.json()
if (!token || !password) {
return NextResponse.json(
{ error: "Token e senha são obrigatórios" },
{ status: 400 }
)
}
if (password.length < 6) {
return NextResponse.json(
{ error: "A senha deve ter pelo menos 6 caracteres" },
{ status: 400 }
)
}
// Buscar token usando SQL direto
const resetTokens = await prisma.$queryRaw<Array<{
id: string
email: string
token: string
expiresAt: Date
used: boolean
}>>`
SELECT id, email, token, "expiresAt", used
FROM password_reset_tokens
WHERE token = ${token}
`
if (!resetTokens || resetTokens.length === 0) {
return NextResponse.json(
{ error: "Token inválido ou expirado" },
{ status: 400 }
)
}
const resetToken = resetTokens[0]
// Verificar se token já foi usado
if (resetToken.used) {
return NextResponse.json(
{ error: "Token já foi utilizado" },
{ status: 400 }
)
}
// Verificar se token expirou
if (new Date() > resetToken.expiresAt) {
return NextResponse.json(
{ error: "Token expirado. Solicite um novo link" },
{ status: 400 }
)
}
// Verificar se usuário existe
const user = await prisma.user.findUnique({
where: { email: resetToken.email }
})
if (!user) {
return NextResponse.json(
{ error: "Usuário não encontrado" },
{ status: 404 }
)
}
// Hash da nova senha
const hashedPassword = await hashPassword(password)
// Atualizar senha do usuário
await prisma.user.update({
where: { id: user.id },
data: { password: hashedPassword }
})
// Marcar token como usado
await prisma.$executeRaw`
UPDATE password_reset_tokens
SET used = true
WHERE id = ${resetToken.id}
`
return NextResponse.json({
success: true,
message: "Senha redefinida com sucesso"
})
} catch (error: any) {
console.error("Erro ao resetar senha:", error)
return NextResponse.json(
{ error: "Erro ao processar solicitação" },
{ status: 500 }
)
}
}