54 lines
1.4 KiB
JavaScript
54 lines
1.4 KiB
JavaScript
import { PrismaClient } from "@prisma/client"
|
|
import bcrypt from "bcryptjs"
|
|
|
|
const prisma = new PrismaClient()
|
|
|
|
export default async function handler(req, res) {
|
|
if (req.method !== "POST") {
|
|
return res.status(405).json({ error: "Método não permitido" })
|
|
}
|
|
|
|
const { username, password } = req.body
|
|
|
|
if (!username || !password) {
|
|
return res.status(400).json({ error: "Username e senha são obrigatórios" })
|
|
}
|
|
|
|
try {
|
|
const user = await prisma.user.findUnique({
|
|
where: { username }
|
|
})
|
|
|
|
if (!user) {
|
|
return res.status(401).json({ error: "Usuário não encontrado" })
|
|
}
|
|
|
|
if (!user.password) {
|
|
return res.status(401).json({ error: "Senha não configurada" })
|
|
}
|
|
|
|
const isValid = await bcrypt.compare(password, user.password)
|
|
|
|
if (!isValid) {
|
|
return res.status(401).json({ error: "Senha incorreta" })
|
|
}
|
|
|
|
// Create a JWT token manually for the session
|
|
const token = require("jsonwebtoken").sign(
|
|
{ sub: user.id, email: user.email, name: user.name || user.username },
|
|
process.env.NEXTAUTH_SECRET || "test-secret-2x4=",
|
|
{ expiresIn: "30d" }
|
|
)
|
|
|
|
return res.status(200).json({
|
|
ok: true,
|
|
user: { id: user.id, email: user.email, name: user.name || user.username },
|
|
token
|
|
})
|
|
} catch (error) {
|
|
console.error("Signin error:", error)
|
|
return res.status(500).json({ error: "Erro interno do servidor" })
|
|
} finally {
|
|
await prisma.$disconnect()
|
|
}
|
|
} |