feat: overhaul admin user management and desktop UX

This commit is contained in:
Esdras Renan 2025-10-13 10:36:38 -03:00
parent 7d6f3bea01
commit ecad81b0ea
16 changed files with 1546 additions and 395 deletions

View file

@ -0,0 +1,66 @@
import { NextResponse } from "next/server"
import { hashPassword } from "better-auth/crypto"
import { prisma } from "@/lib/prisma"
import { assertAdminSession } from "@/lib/auth-server"
function generatePassword(length = 12) {
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
let result = ""
for (let index = 0; index < length; index += 1) {
const randomIndex = Math.floor(Math.random() * alphabet.length)
result += alphabet[randomIndex]
}
return result
}
export const runtime = "nodejs"
export async function POST(request: Request, { params }: { params: { id: string } }) {
const session = await assertAdminSession()
if (!session) {
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
}
const user = await prisma.authUser.findUnique({
where: { id: params.id },
select: { id: true, role: true },
})
if (!user) {
return NextResponse.json({ error: "Usuário não encontrado" }, { status: 404 })
}
if ((user.role ?? "").toLowerCase() === "machine") {
return NextResponse.json({ error: "Contas de máquina não possuem senha web" }, { status: 400 })
}
const body = (await request.json().catch(() => null)) as { password?: string } | null
const temporaryPassword = body?.password?.trim() || generatePassword()
const hashedPassword = await hashPassword(temporaryPassword)
const credentialAccount = await prisma.authAccount.findFirst({
where: { userId: user.id, providerId: "credential" },
})
if (credentialAccount) {
await prisma.authAccount.update({ where: { id: credentialAccount.id }, data: { password: hashedPassword } })
} else {
// se a conta não existir, cria automaticamente
const authUser = await prisma.authUser.findUnique({ where: { id: user.id } })
if (!authUser) {
return NextResponse.json({ error: "Usuário não encontrado" }, { status: 404 })
}
await prisma.authAccount.create({
data: {
userId: user.id,
providerId: "credential",
accountId: authUser.email,
password: hashedPassword,
},
})
}
return NextResponse.json({ temporaryPassword })
}