Jon Wayne Parrott | 3ff4d55 | 2017-02-08 14:43:38 -0800 | [diff] [blame] | 1 | # Copyright 2017 Google Inc. |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | """Integration with oauthlib |
| 16 | |
| 17 | .. warning:: |
| 18 | This module is experimental and is subject to change signficantly |
| 19 | within major version releases. |
| 20 | |
| 21 | This module provides helpers for integrating with `requests-oauthlib`_. |
| 22 | Typically, you'll want to use the higher-level helpers in |
| 23 | :mod:`google.oauth2.flow`. |
| 24 | |
| 25 | .. _requests-oauthlib: http://requests-oauthlib.readthedocs.io/en/stable/ |
| 26 | """ |
| 27 | |
| 28 | import json |
| 29 | |
Jon Wayne Parrott | b9101e3 | 2017-03-06 12:26:10 -0800 | [diff] [blame] | 30 | try: |
| 31 | import requests_oauthlib |
| 32 | except ImportError: # pragma: NO COVER |
| 33 | raise ImportError( |
| 34 | 'The requests-oauthlib library is not installed, please install the ' |
| 35 | 'requests-oauthlib package to use google.oauth2.oauthlib.') |
Jon Wayne Parrott | 3ff4d55 | 2017-02-08 14:43:38 -0800 | [diff] [blame] | 36 | |
| 37 | import google.oauth2.credentials |
| 38 | |
| 39 | _REQUIRED_CONFIG_KEYS = frozenset(('auth_uri', 'token_uri', 'client_id')) |
| 40 | |
| 41 | |
| 42 | def session_from_client_config(client_config, scopes, **kwargs): |
| 43 | """Creates a :class:`requests_oauthlib.OAuth2Session` from client |
| 44 | configuration loaded from a Google-format client secrets file. |
| 45 | |
| 46 | Args: |
| 47 | client_config (Mapping[str, Any]): The client |
| 48 | configuration in the Google `client secrets`_ format. |
| 49 | scopes (Sequence[str]): The list of scopes to request during the |
| 50 | flow. |
| 51 | kwargs: Any additional parameters passed to |
| 52 | :class:`requests_oauthlib.OAuth2Session` |
| 53 | |
| 54 | Raises: |
| 55 | ValueError: If the client configuration is not in the correct |
| 56 | format. |
| 57 | |
| 58 | Returns: |
| 59 | Tuple[requests_oauthlib.OAuth2Session, Mapping[str, Any]]: The new |
| 60 | oauthlib session and the validated client configuration. |
| 61 | |
| 62 | .. _client secrets: |
| 63 | https://developers.google.com/api-client-library/python/guide |
| 64 | /aaa_client_secrets |
| 65 | """ |
| 66 | |
| 67 | if 'web' in client_config: |
| 68 | config = client_config['web'] |
| 69 | elif 'installed' in client_config: |
| 70 | config = client_config['installed'] |
| 71 | else: |
| 72 | raise ValueError( |
| 73 | 'Client secrets must be for a web or installed app.') |
| 74 | |
| 75 | if not _REQUIRED_CONFIG_KEYS.issubset(config.keys()): |
| 76 | raise ValueError('Client secrets is not in the correct format.') |
| 77 | |
| 78 | session = requests_oauthlib.OAuth2Session( |
| 79 | client_id=config['client_id'], |
| 80 | scope=scopes, |
| 81 | **kwargs) |
| 82 | |
| 83 | return session, client_config |
| 84 | |
| 85 | |
| 86 | def session_from_client_secrets_file(client_secrets_file, scopes, **kwargs): |
| 87 | """Creates a :class:`requests_oauthlib.OAuth2Session` instance from a |
| 88 | Google-format client secrets file. |
| 89 | |
| 90 | Args: |
| 91 | client_secrets_file (str): The path to the `client secrets`_ .json |
| 92 | file. |
| 93 | scopes (Sequence[str]): The list of scopes to request during the |
| 94 | flow. |
| 95 | kwargs: Any additional parameters passed to |
| 96 | :class:`requests_oauthlib.OAuth2Session` |
| 97 | |
| 98 | Returns: |
| 99 | Tuple[requests_oauthlib.OAuth2Session, Mapping[str, Any]]: The new |
| 100 | oauthlib session and the validated client configuration. |
| 101 | |
| 102 | .. _client secrets: |
| 103 | https://developers.google.com/api-client-library/python/guide |
| 104 | /aaa_client_secrets |
| 105 | """ |
| 106 | with open(client_secrets_file, 'r') as json_file: |
| 107 | client_config = json.load(json_file) |
| 108 | |
| 109 | return session_from_client_config(client_config, scopes, **kwargs) |
| 110 | |
| 111 | |
| 112 | def credentials_from_session(session, client_config=None): |
| 113 | """Creates :class:`google.oauth2.credentials.Credentials` from a |
| 114 | :class:`requests_oauthlib.OAuth2Session`. |
| 115 | |
| 116 | :meth:`fetch_token` must be called on the session before before calling |
| 117 | this. This uses the session's auth token and the provided client |
| 118 | configuration to create :class:`google.oauth2.credentials.Credentials`. |
| 119 | This allows you to use the credentials from the session with Google |
| 120 | API client libraries. |
| 121 | |
| 122 | Args: |
| 123 | session (requests_oauthlib.OAuth2Session): The OAuth 2.0 session. |
| 124 | client_config (Mapping[str, Any]): The subset of the client |
| 125 | configuration to use. For example, if you have a web client |
| 126 | you would pass in `client_config['web']`. |
| 127 | |
| 128 | Returns: |
| 129 | google.oauth2.credentials.Credentials: The constructed credentials. |
| 130 | |
| 131 | Raises: |
| 132 | ValueError: If there is no access token in the session. |
| 133 | """ |
| 134 | client_config = client_config if client_config is not None else {} |
| 135 | |
| 136 | if not session.token: |
| 137 | raise ValueError( |
| 138 | 'There is no access token for this session, did you call ' |
| 139 | 'fetch_token?') |
| 140 | |
| 141 | return google.oauth2.credentials.Credentials( |
| 142 | session.token['access_token'], |
| 143 | refresh_token=session.token.get('refresh_token'), |
| 144 | token_uri=client_config.get('token_uri'), |
| 145 | client_id=client_config.get('client_id'), |
| 146 | client_secret=client_config.get('client_secret'), |
| 147 | scopes=session.scope) |