import type { FastifyInstance } from "fastify" import { and, eq } from "drizzle-orm" import { authProfiles, authTenantUsers } from "../../db/schema" export async function resolveLoginTenant(server: FastifyInstance, userId: string, domainTenantId: number | null) { const memberships = await server.db .selectDistinct({ tenantId: authTenantUsers.tenant_id, portalCustomerId: authProfiles.customer_for_portal, }) .from(authTenantUsers) .leftJoin(authProfiles, and( eq(authProfiles.user_id, authTenantUsers.user_id), eq(authProfiles.tenant_id, authTenantUsers.tenant_id), eq(authProfiles.active, true) )) .where(eq(authTenantUsers.user_id, userId)) if (domainTenantId) { if (!memberships.some((membership) => membership.tenantId === domainTenantId)) { throw Object.assign(new Error("Not a member of this tenant"), { statusCode: 403 }) } return domainTenantId } // Portal invitations assign one customer account. Load its profile immediately, // even when the customer signs in through the shared FEDEO address. if (memberships.length === 1 && memberships[0].portalCustomerId) { return memberships[0].tenantId } return null }