Skip to content

Commit

Permalink
feat(auth): add GDRIVE_NON_INTERACTIVE to avoid launching browser
Browse files Browse the repository at this point in the history
  • Loading branch information
shcheklein committed Dec 25, 2023
1 parent be873e6 commit 771f871
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
9 changes: 9 additions & 0 deletions pydrive2/auth.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import json
import webbrowser
import httplib2
Expand Down Expand Up @@ -224,6 +225,9 @@ def LocalWebserverAuth(
This function is not for web server application. It creates local web
server for user from standalone application.
If GDRIVE_NON_INTERACTIVE environment variable is set, this function
raises AuthenticationError.
:param host_name: host name of the local web server.
:type host_name: str.
:param port_numbers: list of port numbers to be tried to used.
Expand All @@ -237,6 +241,11 @@ def LocalWebserverAuth(
:returns: str -- code returned from local web server
:raises: AuthenticationRejected, AuthenticationError
"""
if os.getenv("GDRIVE_NON_INTERACTIVE"):
raise AuthenticationError(
"Non interactive mode (GDRIVE_NON_INTERACTIVE env) is enabled"
)

if port_numbers is None:
port_numbers = [
8080,
Expand Down
25 changes: 24 additions & 1 deletion pydrive2/test/test_oauth.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import json
import os
import re
import time
import pytest
from pytest import MonkeyPatch

from pydrive2.auth import GoogleAuth
from pydrive2.auth import AuthenticationError, GoogleAuth
from pydrive2.test.test_util import (
setup_credentials,
delete_file,
Expand Down Expand Up @@ -188,6 +190,27 @@ def test_12_ServiceAuthFromJsonDictNoCredentialsSaving():
time.sleep(1)


def test_13_LocalWebServerAuthNonInterativeRaises():
settings = {
"client_config_backend": "file",
"client_config_file": "client_secrets.json",
"oauth_scope": ["https://www.googleapis.com/auth/drive"],
}
ga = GoogleAuth(settings=settings)

with MonkeyPatch.context() as m:
m.setenv("GDRIVE_NON_INTERACTIVE", "true")
# Test that exception is raised on trying to do browser auth if
# we are running in a non interactive environment.
with pytest.raises(
AuthenticationError,
match=re.escape(
"Non interactive mode (GDRIVE_NON_INTERACTIVE env) is enabled"
),
):
ga.LocalWebserverAuth()


def CheckCredentialsFile(credentials, no_file=False):
ga = GoogleAuth(settings_file_path("test_oauth_default.yaml"))
ga.LoadCredentialsFile(credentials)
Expand Down

0 comments on commit 771f871

Please sign in to comment.