UNPKG

@dataroadinc/setup-auth

Version:

CLI tool and programmatic API for automated OAuth setup across cloud platforms

42 lines (41 loc) 1.92 kB
import { SetupAuthError } from "../../utils/error.js"; import { OrganizationsClient } from "@google-cloud/resource-manager"; import { gcpGetAuth } from "./auth.js"; export async function gcpGetOAuthOrganizationID() { try { const envOrgId = process.env.GCP_OAUTH_ORGANIZATION_ID; if (envOrgId) { return envOrgId; } const auth = await gcpGetAuth(); const client = new OrganizationsClient({ auth }); console.log("Searching for organizations..."); const organizations = []; for await (const org of client.searchOrganizationsAsync()) { organizations.push(org); } console.log(`Found ${organizations.length} organization(s)`); if (organizations.length === 0) { throw new SetupAuthError("No organizations found. Ensure credentials have Organization Viewer permissions."); } if (organizations.length > 1) { console.warn("Multiple organizations found:", organizations.map(o => ({ name: o.name, displayName: o.displayName }))); throw new SetupAuthError(`Multiple organizations found (${organizations.length}). Set GCP_OAUTH_ORGANIZATION_ID environment variable to specify which one to use.`); } const organizationId = organizations[0].name?.split("/").pop(); if (!organizationId) { throw new SetupAuthError("Failed to parse organization ID from response."); } console.log(`Using organization ID: ${organizationId} (Display Name: ${organizations[0].displayName})`); return organizationId; } catch (error) { console.error("Error during organization ID retrieval:", error); if (error instanceof SetupAuthError) { throw error; } throw new SetupAuthError("Organization ID retrieval failed unexpectedly.", { cause: error, }); } }