UNPKG

@dataroadinc/setup-auth

Version:

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

54 lines (53 loc) 1.83 kB
import { SetupAuthError } from "../../utils/error.js"; import { ProjectsClient } from "@google-cloud/resource-manager"; export async function gcpGetAuth(gcpOauthProjectId) { try { const projectsClient = new ProjectsClient({ projectId: gcpOauthProjectId, }); return projectsClient.auth; } catch (error) { throw new SetupAuthError("Authentication failed.\nEnsure you ran `gcloud auth application-default login`:", { cause: error }); } } export async function gcpGetAuthClient() { try { const auth = await gcpGetAuth(); const client = await auth.getClient(); return client; } catch (error) { throw new SetupAuthError("Error getting auth client:", { cause: error }); } } export async function gcpGetAccessToken() { if (process.env.GCP_ACCESS_TOKEN) { return process.env.GCP_ACCESS_TOKEN; } try { const authClient = await gcpGetAuthClient(); const accessToken = await authClient.getAccessToken(); if (typeof accessToken === "string") { process.env.GCP_ACCESS_TOKEN = accessToken; return accessToken; } else if (accessToken && "token" in accessToken) { if (!accessToken.token) { throw new Error("Access token is undefined or invalid"); } process.env.GCP_ACCESS_TOKEN = accessToken.token; return accessToken.token; } else { throw new Error("Access token is undefined or invalid"); } } catch (error) { throw new SetupAuthError("Error retrieving access token:", { cause: error }); } } export async function gcpGetAuthorizationHeader() { const accessToken = await gcpGetAccessToken(); return `Bearer ${accessToken}`; }