Repository: GoogleCloudPlatform/google-auth-library-python
Pull request #24 (2016-10-14 22:32:18)

Add oauth2 credentials

dhermes: LGTM, be sure to file the `Credentials` naming issue before merging
jonparrott: Oh I see you already said so, merging.

Patch:
diff --git a/docs/reference/google.oauth2.credentials.rst b/docs/reference/google.oauth2.credentials.rst
new file mode 100644
index 0000000..ca978d1
--- /dev/null
+++ b/docs/reference/google.oauth2.credentials.rst
@@ -0,0 +1,7 @@
+google.oauth2.credentials module
+================================
+
+.. automodule:: google.oauth2.credentials
+    :members:
+    :inherited-members:
+    :show-inheritance:
diff --git a/google/oauth2/credentials.py b/google/oauth2/credentials.py
new file mode 100644
index 0000000..9727e18
--- /dev/null
+++ b/google/oauth2/credentials.py
@@ -0,0 +1,94 @@
+# Copyright 2016 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""OAuth 2.0 Credentials.
+
+This module provides credentials based on OAuth 2.0 access and refresh tokens.
+These credentials usually access resources on behalf of a user (resource
+owner).
+
+Specifically, this is intended to use access tokens acquired using the
+`Authorization Code grant`_ and can refresh those tokens using a
+optional `refresh token`_.
+
+Obtaining the initial access and refresh token is outside of the scope of this
+module. Consult `rfc6749 section 4.1`_ for complete details on the
+Authorization Code grant flow.
+
+.. _Authorization Code grant: https://tools.ietf.org/html/rfc6749#section-1.3.1
+.. _refresh token: https://tools.ietf.org/html/rfc6749#section-6
+.. _rfc6749 section 4.1: https://tools.ietf.org/html/rfc6749#section-4.1
+"""
+
+from google.auth import _helpers
+from google.auth import credentials
+from google.oauth2 import _client
+
+
+class Credentials(credentials.Scoped, credentials.Credentials):
+    """Credentials using OAuth 2.0 access and refresh tokens."""
+
+    def __init__(self, token, refresh_token=None, token_uri=None,
+                 client_id=None, client_secret=None, scopes=None):
+        """
+        Args:
+            token (Optional(str)): The OAuth 2.0 access token. Can be None
+                if refresh information is provided.
+            refresh_token (str): The OAuth 2.0 refresh token. If specified,
+                credentials can be refreshed.
+            token_uri (str): The OAuth 2.0 authorization server's token
+                endpoint URI. Must be specified for refresh, can be left as
+                None if the token can not be refreshed.
+            client_id (str): The OAuth 2.0 client ID. Must be specified for
+                refresh, can be left as None if the token can not be refreshed.
+            client_secret(str): The OAuth 2.0 client secret. Must be specified
+                for refresh, can be left as None if the token can not be
+                refreshed.
+            scopes (Sequence[str]): The scopes that were originally used
+                to obtain authorization. This is a purely informative parameter
+                that can be used by :meth:`has_scopes`. OAuth 2.0 credentials
+                can not request additional scopes after authorization.
+        """
+        super(Credentials, self).__init__()
+        self.token = token
+        self._refresh_token = refresh_token
+        self._scopes = scopes
+        self._token_uri = token_uri
+        self._client_id = client_id
+        self._client_secret = client_secret
+
+    @property
+    def requires_scopes(self):
+        """False: OAuth 2.0 credentials have their scopes set when
+        the initial token is requested and can not be changed."""
+        return False
+
+    def with_scopes(self, scopes):
+        """Unavailable, OAuth 2.0 credentials can not be re-scoped.
+
+        OAuth 2.0 credentials have their scopes set when the initial token is
+        requested and can not be changed.
+        """
+        raise NotImplementedError(
+            'OAuth 2.0 Credentials can not modify their scopes.')
+
+    @_helpers.copy_docstring(credentials.Credentials)
+    def refresh(self, request):
+        access_token, refresh_token, expiry, _ = _client.refresh_grant(
+            request, self._token_uri, self._refresh_token, self._client_id,
+            self._client_secret)
+
+        self.token = access_token
+        self.expiry = expiry
+        self._refresh_token = refresh_token


Test patch:
diff --git a/tests/oauth2/test_credentials.py b/tests/oauth2/test_credentials.py
new file mode 100644
index 0000000..173bb00
--- /dev/null
+++ b/tests/oauth2/test_credentials.py
@@ -0,0 +1,79 @@
+# Copyright 2016 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import datetime
+
+import mock
+import pytest
+
+from google.auth import _helpers
+from google.oauth2 import credentials
+
+
+class TestCredentials(object):
+    TOKEN_URI = 'https://example.com/oauth2/token'
+    REFRESH_TOKEN = 'refresh_token'
+    CLIENT_ID = 'client_id'
+    CLIENT_SECRET = 'client_secret'
+
+    @pytest.fixture(autouse=True)
+    def credentials(self):
+        self.credentials = credentials.Credentials(
+            token=None, refresh_token=self.REFRESH_TOKEN,
+            token_uri=self.TOKEN_URI, client_id=self.CLIENT_ID,
+            client_secret=self.CLIENT_SECRET)
+
+    def test_default_state(self):
+        assert not self.credentials.valid
+        # Expiration hasn't been set yet
+        assert not self.credentials.expired
+        # Scopes aren't required for these credentials
+        assert not self.credentials.requires_scopes
+
+    def test_create_scoped(self):
+        with pytest.raises(NotImplementedError):
+            self.credentials.with_scopes(['email'])
+
+    @mock.patch('google.oauth2._client.refresh_grant')
+    @mock.patch(
+        'google.auth._helpers.utcnow', return_value=datetime.datetime.min)
+    def test_refresh_success(self, now_mock, refresh_grant_mock):
+        token = 'token'
+        expiry = _helpers.utcnow() + datetime.timedelta(seconds=500)
+        refresh_grant_mock.return_value = (
+            # Access token
+            token,
+            # New refresh token
+            None,
+            # Expiry,
+            expiry,
+            # Extra data
+            {})
+        request_mock = mock.Mock()
+
+        # Refresh credentials
+        self.credentials.refresh(request_mock)
+
+        # Check jwt grant call.
+        refresh_grant_mock.assert_called_with(
+            request_mock, self.TOKEN_URI, self.REFRESH_TOKEN, self.CLIENT_ID,
+            self.CLIENT_SECRET)
+
+        # Check that the credentials have the token and expiry
+        assert self.credentials.token == token
+        assert self.credentials.expiry == expiry
+
+        # Check that the credentials are valid (have a token and are not
+        # expired)
+        assert self.credentials.valid