import { getAuth, hasSessionAuthConfig } from "@/lib/auth"; import { AuthRepository } from "@/server/auth/repositories/AuthRepository"; import { AppError } from "@/server/lib/errors"; import type { EnsuredUserContext } from "./types"; // `team` mode: a Better Auth session resolves to a membership in the single // shared workspace. Unlike hosted, there is no per-user fallback organization — // a signed-in user with no membership was removed by the owner, so they are // treated as signed out rather than handed a fresh personal workspace. export async function resolveTeamContext( headers: Headers, ): Promise { if (!hasSessionAuthConfig()) { throw new AppError( "AUTH_CONFIG_MISSING", "team mode needs BETTER_AUTH_URL and BETTER_AUTH_SECRET (32+ characters) on the deployment.", ); } const session = await getAuth().api.getSession({ headers }); if (!session?.user?.id || !session.user.email) { throw new AppError("UNAUTHENTICATED"); } const organizationId = await AuthRepository.findFirstOrganizationIdForUser( session.user.id, ); if (!organizationId) { throw new AppError("UNAUTHENTICATED"); } const membership = await AuthRepository.getMembership( session.user.id, organizationId, ); if (!membership) { throw new AppError("UNAUTHENTICATED"); } return { userId: session.user.id, userEmail: session.user.email, // `team` mode has no email-verification step. emailVerified: true, organizationId, role: membership.role, }; }