Skip to content

Commit

Permalink
Allow GoogleDrive to authenticate via application default credentials…
Browse files Browse the repository at this point in the history
… on Cloud Run/GCE etc without service key (#6035)

@eyurtsev

The existing GoogleDrive implementation always needs a service account
to be available at the credentials location. When running on GCP
services such as Cloud Run, a service account already exists in the
metadata of the service, so no physical key is necessary. This change
adds a check to see if it is running in such an environment, and uses
that authentication instead.

---------

Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
  • Loading branch information
MarkEdmondson1234 and hwchase17 authored Jun 17, 2023
1 parent 6f36f0f commit b7ba7e8
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions langchain/document_loaders/googledrive.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
# 4. For service accounts visit
# https://cloud.google.com/iam/docs/service-accounts-create

import os
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Union

Expand Down Expand Up @@ -91,6 +92,7 @@ def _load_credentials(self) -> Any:
"""Load credentials."""
# Adapted from https://developers.google.com/drive/api/v3/quickstart/python
try:
from google.auth import default
from google.auth.transport.requests import Request
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials
Expand All @@ -116,6 +118,12 @@ def _load_credentials(self) -> Any:
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
elif "GOOGLE_APPLICATION_CREDENTIALS" not in os.environ:
creds, project = default()
creds = creds.with_scopes(SCOPES)
# no need to write to file
if creds:
return creds
else:
flow = InstalledAppFlow.from_client_secrets_file(
str(self.credentials_path), SCOPES
Expand Down

0 comments on commit b7ba7e8

Please sign in to comment.