Class CloudRunAuthClass

CloudRunAuth This class provides the CloudRunAuthClass for managing authentication and initialization of Google Cloud services, including Translation API and Vertex AI.

The CloudRunAuthClass simplifies the process of authenticating and interacting with Google Cloud services. It supports multiple authentication methods, including:

  • Access Token: Authenticate using an access token obtained from a Cloud Run service.
  • Service Account: Authenticate using a service account key file or credentials.
  • API Key: Authenticate using a Google API key.

The class automatically detects the available authentication method and initializes the necessary Google API clients accordingly. It also provides methods to check the readiness of the Translation API and Vertex AI clients.

  • Multiple Authentication Methods: Supports access token, service account, and API key authentication.
  • Automatic Authentication Detection: Determines the appropriate authentication method based on the provided credentials.
  • Google API Client Initialization: Initializes the Translation API and Vertex AI clients.
  • Readiness Checks: Provides methods to check if the Translation API and Vertex AI clients are ready.
  • Cloud Run Authentication: Supports authentication via a Cloud Run service, prompting the user for an access token.
  • Error Handling: Includes error handling to gracefully manage authentication and initialization failures.
  • Configuration Options: Allows configuration of API keys, key files, and credentials.
npm install @google-cloud/translate @google-cloud/vertexai google-auth-library yoctocolors
import { CloudRunAuthClass } from './CloudRunAuth.class';

async function main() {
const auth = new CloudRunAuthClass();
await auth.getGoogleApi();

if (auth.isTranslateReady) {
console.log('Translation API is ready.');
// Use the translationClient here
}

if (auth.isVertexReady) {
console.log('Vertex AI is ready.');
// Use the vertexAI client here
}
}

main().catch(console.error);
  1. Set up a Cloud Run service that provides an authentication endpoint.
  2. Call getGoogleApi() to initiate the authentication process.
  3. The class will prompt the user to visit the authentication URL and enter the received access token.
  1. Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of your service account key file.
  2. Alternatively, use setkeyFile() or setCredentials() to provide the key file path or credentials.
  3. Call getGoogleApi() to initialize the Google API clients.
  1. Set the GOOGLE_API_KEY environment variable to your API key.
  2. Alternatively, use setApiKey() to provide the API key.
  3. Call getGoogleApi() to initialize the Google API clients.
  • constructor(): Initializes the CloudRunAuthClass with default values and attempts to set the API key and key file from environment variables.
  • getGoogleApi(): Initializes the Google API clients based on the determined authentication method.
  • displayAuthUrl(): Displays the URL for Google authentication via a Cloud Run service.
  • setApiKey(apiKey?: string): Sets the API key for Google API authentication.
  • setCredentials(credentials?: any): Sets the service account credentials for Google API authentication.
  • setkeyFile(keyFile?: string): Sets the path to the service account key file for Google API authentication.
  • setAccessToken(accessToken: string): Sets the access token for Cloud Run authentication.
  • isTranslateReady: Returns true if the Translation API client is ready; false otherwise.
  • isVertexReady: Returns true if the Vertex AI client is ready; false otherwise.

Constructors

  • Initializes the CloudRunAuthClass.

    Sets the initial values of the class properties to undefined, and sets the project ID to 'your_project_id'. It also attempts to set the API key and key file using the setApiKey() and setkeyFile() methods.

    Returns CloudRunAuthClass

Properties

_accessToken: undefined | string
_apiKey: undefined | string
_authMethod: "serviceAccount" | "apiKey" | "accessToken" | "none" = 'none'
_credentials: any
_isTranslateReady: boolean = false
_isVertexReady: boolean = false
_keyFile: undefined | string
auth: undefined | GoogleAuth | OAuth2Client
project_id: undefined | string
translationClient: undefined | TranslationServiceClient
vertexAI: undefined | VertexAI

Accessors

  • get isTranslateReady(): boolean
  • Retrieves the readiness status of the Google Cloud Translation API client.

    This getter method provides a way to check if the Translation API client has been successfully initialized and is ready for use. It returns true if the client is ready, and false otherwise.

    Returns boolean

    true if the Translation API client is ready; false otherwise.

  • get isVertexReady(): boolean
  • Retrieves the readiness status of the Vertex AI client.

    This getter method allows you to check if the Vertex AI client has been successfully initialized and is ready for use. It returns true if the client is ready, and false otherwise.

    Returns boolean

    true if the Vertex AI client is ready; false otherwise.

Methods

  • Private

    Disables the Google Cloud Translation API and Vertex AI services.

    This private method is used to disable both the Translation API and Vertex AI services by setting their respective readiness flags (_isTranslateReady and _isVertexReady) to false. This is typically done when an error occurs during the initialization of these services or when they are no longer needed.

    Returns void


    this._disableServices(); // Disables both Translation API and Vertex AI services.
  • Retrieves an access token by prompting the user to authenticate via a Cloud Run service.

    This method guides the user through the process of obtaining an access token by directing them to a specific URL for authentication. Upon successful authentication, the user is expected to provide the received access token, which is then used to initialize the Google API clients.

    Returns Promise<void>

    This method relies on the setAccessTokenPrompt function to interact with the user and obtain the access token. If the user fails to provide an access token, the Google services are disabled.

    If there is an error during the process of getting the access token.


    // Initiates the process of getting an access token from the user.
    await this._getAccessTokenFromCloudRun();
  • Private

    Initializes the Google Cloud Translation API client.

    This method creates a new instance of the TranslationServiceClient using the provided options or the class's stored credentials, API key, or key file. It configures the client with the necessary authentication details and sets the library version to 'v3'.

    Parameters

    • Optionalopts: GoogleKeyOptions

      Optional configuration options for the Translation API client.

      • OptionalapiKey?: string
      • Optionalcredentials?: any
      • OptionalkeyFile?: string

    Returns void

    If the initialization is successful, the _isTranslateReady flag is set to true. Otherwise, it's set to false.


    // Initialize the Translation API client with a specific API key
    this._initializeTranslateClient({ apiKey: 'your_api_key' });
  • Initializes the Vertex AI client.

    This method creates a new instance of the Vertex AI client using the provided options or the class's stored credentials, API key, or key file. It configures the client with the project ID, location, and API endpoint.

    Parameters

    • Optionalopts: GoogleKeyOptions

      Optional configuration options for the Vertex AI client.

      • OptionalapiKey?: string
      • Optionalcredentials?: any
      • OptionalkeyFile?: string

    Returns void

    If the initialization is successful, the _isVertexReady flag is set to true. Otherwise, it's set to false.


    // Initialize Vertex AI with a specific API key
    this._initializeVertexAI({ apiKey: 'your_api_key' });
  • Initializes the Google API clients using an access token.

    Returns Promise<void>

    This method uses the provided access token to initialize the Google API clients (Translation and Vertex AI) by creating a new instance of OAuth2Client and setting the credentials using the access token. It then uses the obtained API key to initialize the Translation and Vertex AI clients.

    If an error occurs during initialization, it disables the services and logs the error.


    await this._initializeWithAccessToken();
  • Initializes the Google API clients using an API key.

    Returns Promise<void>

    This method uses the API key to initialize the Google API clients (Translation and Vertex AI) by creating a new instance of GoogleAuth. It sets the necessary scopes for cloud translation and proceeds to initialize the Translation and Vertex AI clients.

    If an error occurs during initialization, it disables the services.

    If there is an error during the initialization of the Google API clients.


    await this._initializeWithApiKey();
  • Initializes the Google API clients using a service account.

    Returns Promise<void>

    This method uses the service account key file and credentials to initialize the Google API clients (Translation and Vertex AI) by creating a new instance of GoogleAuth. It sets the necessary scopes for cloud translation and proceeds to initialize the Translation and Vertex AI clients.

    If an error occurs during initialization, it disables the services.

    If there is an error during the initialization of the Google API clients.


    await this._initializeWithAccessToken();
  • Returns void

  • Returns void

  • Determines and sets the authentication method based on the provided credentials, key file, or access token.

    This method analyzes the presence of an access token, service account key file, or API key to determine the appropriate authentication method. It sets the _authMethod property accordingly and logs warnings if multiple authentication methods are provided, prioritizing the access token, followed by the service account key.

    Returns void

    The priority order for authentication methods is:

    1. Access Token
    2. Service Account Key
    3. API Key

    // If both an access token and an API key are provided, the access token will be used, and a warning will be logged.
    this._accessToken = 'your_access_token';
    this._apiKey = 'your_api_key';
    this._showKeyInfo(); // _authMethod will be 'accessToken'
  • Displays the URL for Google authentication.

    This method logs instructions on how to authenticate with the Google Cloud services using the provided Cloud Run base URL.

    Returns Promise<void>

    The method logs a URL that the user must open in their browser to authenticate with their Google account. After authenticating, the user will receive an access token that must be copied and pasted into the prompt.


    this.displayAuthUrl();
  • Returns Promise<void>

  • Initializes the Google API clients based on the determined authentication method.

    This method orchestrates the initialization of Google API clients (Translation and Vertex AI) based on the authentication method determined by _showKeyInfo(). It handles three authentication methods: access token, service account, and API key. If no authentication method is configured, it attempts to use Cloud Run authentication.

    Returns Promise<void>

    This method is a central point for setting up the Google API clients. It uses the _authMethod property to decide which initialization path to take. If an error occurs during initialization, it disables the services and logs the error.

    If there is an error during the initialization of the Google API.


    // Assuming _authMethod is 'accessToken'
    await this.initializeGoogleAPI(); // Initializes with access token
  • Sets the access token for Cloud Run authentication.

    Parameters

    • accessToken: string

      The Cloud Run access token.

    Returns void

  • Sets the API key for Google API authentication.

    Parameters

    • OptionalapiKey: string

      The Google API key.

    Returns void

  • Sets the path to the service account key file for Google API authentication.

    Parameters

    • Optionalcredentials: any

      The path to the service account key file.

    Returns void

  • Sets the path to the service account key file for Google API authentication.

    Parameters

    • OptionalkeyFile: string

      The path to the service account key file.

    Returns void