Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds ability to authenticate using m2m without the file system #8

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 69 additions & 2 deletions carto_auth/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ class CartoAuth:
api_base_url (str, optional): Base URL for a CARTO account.
access_token (str, optional): Token already generated with CARTO.
expiration (int, optional): Time in seconds when the token will be expired.
client_id (str, optional): Client id of a M2M application
client_id (str, optional): Client id of an M2M application
provided by CARTO.
client_secret (str, optional): Client secret of a M2M application
client_secret (str, optional): Client secret of an M2M application
provided by CARTO.
cache_filepath (str, optional): File path where the token is stored.
Default "home()/.carto-auth/token.json".
Expand Down Expand Up @@ -116,6 +116,73 @@ def from_oauth(
open_browser=open_browser,
)

@classmethod
def from_m2m_token(
cls,
api_base_url,
client_id,
client_secret,
cache_filepath=None,
use_cache=True,
):
"""Create a CartoAuth object using an M2M token.

Args:
api_base_url (str): Base URL for a CARTO account.
client_id (str, optional): Client id of an M2M application
provided by CARTO.
client_secret (str, optional): Client secret of an M2M application
provided by CARTO.
cache_filepath (str, optional): File path where the token is stored.
Default "home()/.carto-auth/token_m2m.json".
use_cache (bool, optional): Whether the stored cached token should be used.
Default True.

Raises:
ValueError: If "api_base_url", "client_id", "client_secret" parameters are not provided.
"""
if api_base_url is None:
raise ValueError("api_base_url is required")
if client_id is None:
raise ValueError("client_id is required")
if client_secret is None:
raise ValueError("client_secret is required")

mode = "m2m"

if cache_filepath is None:
cache_filepath = get_cache_filepath(mode)

if use_cache:
data = load_cache_file(cache_filepath)
if (
data
and data.get("api_base_url")
and not is_token_expired(data.get("expiration"))
):
return cls(
mode=mode,
api_base_url=data.get("api_base_url"),
access_token=data.get("access_token"),
expiration=data.get("expiration"),
client_id=client_id,
client_secret=client_secret,
cache_filepath=cache_filepath,
use_cache=use_cache,
)

data = get_m2m_token_info(client_id, client_secret)
return cls(
mode=mode,
api_base_url=api_base_url,
access_token=data.get("access_token"),
expiration=data.get("expiration"),
client_id=client_id,
client_secret=client_secret,
cache_filepath=cache_filepath,
use_cache=use_cache,
)

@classmethod
def from_m2m(cls, filepath, cache_filepath=None, use_cache=True):
"""Create a CartoAuth object using CARTO credentials file.
Expand Down
111 changes: 111 additions & 0 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,117 @@ def test_from_oauth__use_cache_expired(mocker):
get_oauth.assert_called_once()
get_api_base_url.assert_called_once()

def test_from_m2m_token__not_use_cache(mocker):
expiration = int((datetime.utcnow() + timedelta(seconds=10)).timestamp())
load_mock = mocker.patch("carto_auth.auth.load_cache_file")
save_mock = mocker.patch("carto_auth.auth.save_cache_file")
get_m2m = mocker.patch(
"carto_auth.auth.get_m2m_token_info",
return_value={
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpX",
"expiration": expiration,
},
)

api_base_url = "https://gcp-us-east1.api.carto.com"
client_id = "1234"
client_secret = "1234567890"

carto_auth = CartoAuth.from_m2m_token(api_base_url, client_id, client_secret, use_cache=False)
assert carto_auth._mode == "m2m"
assert carto_auth._api_base_url == api_base_url
assert str(carto_auth._cache_filepath).endswith(".carto-auth/token_m2m.json")
assert carto_auth._use_cache is False
assert carto_auth._access_token == "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpX"
assert carto_auth._expiration == expiration
assert carto_auth._client_id == client_id
assert carto_auth._client_secret == client_secret
load_mock.assert_not_called()
save_mock.assert_not_called()
get_m2m.assert_called_once()


def test_from_m2m_token__use_cache(mocker):
expiration = int((datetime.utcnow() + timedelta(seconds=10)).timestamp())
load_mock = mocker.patch(
"carto_auth.auth.load_cache_file",
return_value={
"api_base_url": "https://gcp-us-east1.api.carto.com",
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpX",
"expiration": expiration,
},
)
save_mock = mocker.patch("carto_auth.auth.save_cache_file")
get_m2m = mocker.patch("carto_auth.auth.get_m2m_token_info")

api_base_url = "https://gcp-us-east1.api.carto.com"
client_id = "1234"
client_secret = "1234567890"

carto_auth = CartoAuth.from_m2m_token(api_base_url, client_id, client_secret, use_cache=True)
assert carto_auth._mode == "m2m"
assert carto_auth._api_base_url == api_base_url
assert str(carto_auth._cache_filepath).endswith(".carto-auth/token_m2m.json")
assert carto_auth._use_cache is True
assert carto_auth._access_token == "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpX"
assert carto_auth._expiration == expiration
assert carto_auth._client_id == client_id
assert carto_auth._client_secret == client_secret
load_mock.assert_called_once()
save_mock.assert_called_once()
get_m2m.assert_not_called()


def test_from_m2m_token__use_cache_expired(mocker):
expiration = int((datetime.utcnow() - timedelta(seconds=10)).timestamp())
load_mock = mocker.patch(
"carto_auth.auth.load_cache_file",
return_value={
"api_base_url": "https://gcp-us-east1.api.carto.com",
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpX",
"expiration": expiration, # token expired
},
)
save_mock = mocker.patch("carto_auth.auth.save_cache_file")
expiration = int((datetime.utcnow() + timedelta(seconds=10)).timestamp())
get_m2m = mocker.patch(
"carto_auth.auth.get_m2m_token_info",
return_value={
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpX",
"expiration": expiration, # new token expiration
},
)

api_base_url = "https://gcp-us-east1.api.carto.com"
client_id = "1234"
client_secret = "1234567890"

carto_auth = CartoAuth.from_m2m_token(api_base_url, client_id, client_secret, use_cache=True)
assert carto_auth._mode == "m2m"
assert carto_auth._api_base_url == api_base_url
assert str(carto_auth._cache_filepath).endswith(".carto-auth/token_m2m.json")
assert carto_auth._use_cache is True
assert carto_auth._access_token == "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpX"
assert carto_auth._expiration == expiration
assert carto_auth._client_id == client_id
assert carto_auth._client_secret == client_secret
load_mock.assert_called_once()
save_mock.assert_called_once()
get_m2m.assert_called_once()

def test_from_m2m_token_error():
api_base_url = "https://gcp-us-east1.api.carto.com"
client_id = "1234"
client_secret = "1234567890"

with pytest.raises(ValueError):
CartoAuth.from_m2m_token(None, client_id, client_secret)

with pytest.raises(ValueError):
CartoAuth.from_m2m_token(api_base_url, None, client_secret)

with pytest.raises(ValueError):
CartoAuth.from_m2m_token(api_base_url, client_id, None)

def test_from_m2m__not_use_cache(mocker):
expiration = int((datetime.utcnow() + timedelta(seconds=10)).timestamp())
Expand Down