Implement company provisioning codes and session tweaks

This commit is contained in:
Esdras Renan 2025-10-15 20:45:25 -03:00
parent 0fb9bf59b2
commit 2cba553efa
28 changed files with 1407 additions and 534 deletions

View file

@ -62,3 +62,72 @@ export async function ensureMachineAccount(params: EnsureMachineAccountParams) {
authEmail: machineEmail,
}
}
type EnsureCollaboratorAccountParams = {
email: string
name: string
tenantId: string
companyId?: string | null
}
export async function ensureCollaboratorAccount(params: EnsureCollaboratorAccountParams) {
const normalizedEmail = params.email.trim().toLowerCase()
const name = params.name.trim() || normalizedEmail
const tenantId = params.tenantId
const existingAuth = await prisma.authUser.findUnique({ where: { email: normalizedEmail } })
const authUser = existingAuth
? await prisma.authUser.update({
where: { id: existingAuth.id },
data: {
name,
tenantId,
role: "collaborator",
},
})
: await prisma.authUser.create({
data: {
email: normalizedEmail,
name,
tenantId,
role: "collaborator",
},
})
await prisma.authAccount.upsert({
where: {
providerId_accountId: {
providerId: "credential",
accountId: normalizedEmail,
},
},
update: {
userId: authUser.id,
},
create: {
providerId: "credential",
accountId: normalizedEmail,
userId: authUser.id,
password: null,
},
})
await prisma.user.upsert({
where: { email: normalizedEmail },
update: {
name,
tenantId,
role: "COLLABORATOR",
companyId: params.companyId ?? undefined,
},
create: {
email: normalizedEmail,
name,
tenantId,
role: "COLLABORATOR",
companyId: params.companyId ?? undefined,
},
})
return { authUserId: authUser.id }
}