Fix domain user role typing

This commit is contained in:
Esdras Renan 2025-10-13 14:03:55 -03:00
parent 4f812a2e4c
commit a8abb68e36

View file

@ -4,6 +4,7 @@ import { randomBytes } from "crypto"
import { hashPassword } from "better-auth/crypto"
import { ConvexHttpClient } from "convex/browser"
import type { UserRole } from "@prisma/client"
import { api } from "@/convex/_generated/api"
import { prisma } from "@/lib/prisma"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
@ -17,6 +18,13 @@ function normalizeRole(input: string | null | undefined): RoleOption {
return (ROLE_OPTIONS as readonly string[]).includes(role) ? role : "agent"
}
const USER_ROLE_OPTIONS: ReadonlyArray<UserRole> = ["ADMIN", "MANAGER", "AGENT", "COLLABORATOR"]
function mapToUserRole(role: RoleOption): UserRole {
const candidate = role.toUpperCase() as UserRole
return USER_ROLE_OPTIONS.includes(candidate) ? candidate : "AGENT"
}
function generatePassword(length = 12) {
const bytes = randomBytes(length)
return Array.from(bytes)
@ -68,6 +76,7 @@ export async function POST(request: Request) {
const role = normalizeRole(roleInput)
const tenantId = tenantInput || session.user.tenantId || DEFAULT_TENANT_ID
const userRole = mapToUserRole(role)
const existing = await prisma.authUser.findUnique({ where: { email: emailInput } })
if (existing) {
@ -105,13 +114,13 @@ export async function POST(request: Request) {
where: { email: user.email },
update: {
name: user.name ?? user.email,
role: role.toUpperCase(),
role: userRole,
tenantId,
},
create: {
email: user.email,
name: user.name ?? user.email,
role: role.toUpperCase(),
role: userRole,
tenantId,
},
})
@ -125,7 +134,7 @@ export async function POST(request: Request) {
email: emailInput,
name: nameInput || emailInput,
avatarUrl: undefined,
role: role.toUpperCase(),
role: userRole,
})
} catch (error) {
console.warn("Falha ao sincronizar usuário no Convex", error)