Skip to content

Commit

Permalink
feat: add to_json method to google.oauth2.credentials.Credentials (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
patkasper authored and busunkim96 committed Dec 5, 2019
1 parent 7305072 commit bfb1f8c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
30 changes: 30 additions & 0 deletions google/oauth2/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,33 @@ def from_authorized_user_file(cls, filename, scopes=None):
with io.open(filename, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
return cls.from_authorized_user_info(data, scopes)

def to_json(self, strip=None):
"""Utility function that creates a JSON representation of a Credentials
object.
Args:
strip (Sequence[str]): Optional list of members to exclude from the
generated JSON.
Returns:
str: A JSON representation of this instance, suitable to pass to
from_json().
"""
prep = {
"token": self.token,
"refresh_token": self.refresh_token,
"token_uri": self.token_uri,
"client_id": self.client_id,
"client_secret": self.client_secret,
"scopes": self.scopes,
}

# Remove empty entries
prep = {k: v for k, v in prep.items() if v is not None}

# Remove entries that explicitely need to be removed
if strip is not None:
prep = {k: v for k, v in prep.items() if k not in strip}

return json.dumps(prep)
24 changes: 24 additions & 0 deletions tests/oauth2/test_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,27 @@ def test_from_authorized_user_file(self):
assert creds.refresh_token == info["refresh_token"]
assert creds.token_uri == credentials._GOOGLE_OAUTH2_TOKEN_ENDPOINT
assert creds.scopes == scopes

def test_to_json(self):
info = AUTH_USER_INFO.copy()
creds = credentials.Credentials.from_authorized_user_info(info)

# Test with no `strip` arg
json_output = creds.to_json()
json_asdict = json.loads(json_output)
assert json_asdict.get("token") == creds.token
assert json_asdict.get("refresh_token") == creds.refresh_token
assert json_asdict.get("token_uri") == creds.token_uri
assert json_asdict.get("client_id") == creds.client_id
assert json_asdict.get("scopes") == creds.scopes
assert json_asdict.get("client_secret") == creds.client_secret

# Test with a `strip` arg
json_output = creds.to_json(strip=["client_secret"])
json_asdict = json.loads(json_output)
assert json_asdict.get("token") == creds.token
assert json_asdict.get("refresh_token") == creds.refresh_token
assert json_asdict.get("token_uri") == creds.token_uri
assert json_asdict.get("client_id") == creds.client_id
assert json_asdict.get("scopes") == creds.scopes
assert json_asdict.get("client_secret") is None

0 comments on commit bfb1f8c

Please sign in to comment.