blob: 8f5c10575c34f28dc0f065f611b0130cd477f0a1 [file] [log] [blame]
Jon Wayne Parrott3ff4d552017-02-08 14:43:38 -08001# 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
21This module provides helpers for integrating with `requests-oauthlib`_.
22Typically, 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
28import json
29
30import requests_oauthlib
31
32import google.oauth2.credentials
33
34_REQUIRED_CONFIG_KEYS = frozenset(('auth_uri', 'token_uri', 'client_id'))
35
36
37def session_from_client_config(client_config, scopes, **kwargs):
38 """Creates a :class:`requests_oauthlib.OAuth2Session` from client
39 configuration loaded from a Google-format client secrets file.
40
41 Args:
42 client_config (Mapping[str, Any]): The client
43 configuration in the Google `client secrets`_ format.
44 scopes (Sequence[str]): The list of scopes to request during the
45 flow.
46 kwargs: Any additional parameters passed to
47 :class:`requests_oauthlib.OAuth2Session`
48
49 Raises:
50 ValueError: If the client configuration is not in the correct
51 format.
52
53 Returns:
54 Tuple[requests_oauthlib.OAuth2Session, Mapping[str, Any]]: The new
55 oauthlib session and the validated client configuration.
56
57 .. _client secrets:
58 https://developers.google.com/api-client-library/python/guide
59 /aaa_client_secrets
60 """
61
62 if 'web' in client_config:
63 config = client_config['web']
64 elif 'installed' in client_config:
65 config = client_config['installed']
66 else:
67 raise ValueError(
68 'Client secrets must be for a web or installed app.')
69
70 if not _REQUIRED_CONFIG_KEYS.issubset(config.keys()):
71 raise ValueError('Client secrets is not in the correct format.')
72
73 session = requests_oauthlib.OAuth2Session(
74 client_id=config['client_id'],
75 scope=scopes,
76 **kwargs)
77
78 return session, client_config
79
80
81def session_from_client_secrets_file(client_secrets_file, scopes, **kwargs):
82 """Creates a :class:`requests_oauthlib.OAuth2Session` instance from a
83 Google-format client secrets file.
84
85 Args:
86 client_secrets_file (str): The path to the `client secrets`_ .json
87 file.
88 scopes (Sequence[str]): The list of scopes to request during the
89 flow.
90 kwargs: Any additional parameters passed to
91 :class:`requests_oauthlib.OAuth2Session`
92
93 Returns:
94 Tuple[requests_oauthlib.OAuth2Session, Mapping[str, Any]]: The new
95 oauthlib session and the validated client configuration.
96
97 .. _client secrets:
98 https://developers.google.com/api-client-library/python/guide
99 /aaa_client_secrets
100 """
101 with open(client_secrets_file, 'r') as json_file:
102 client_config = json.load(json_file)
103
104 return session_from_client_config(client_config, scopes, **kwargs)
105
106
107def credentials_from_session(session, client_config=None):
108 """Creates :class:`google.oauth2.credentials.Credentials` from a
109 :class:`requests_oauthlib.OAuth2Session`.
110
111 :meth:`fetch_token` must be called on the session before before calling
112 this. This uses the session's auth token and the provided client
113 configuration to create :class:`google.oauth2.credentials.Credentials`.
114 This allows you to use the credentials from the session with Google
115 API client libraries.
116
117 Args:
118 session (requests_oauthlib.OAuth2Session): The OAuth 2.0 session.
119 client_config (Mapping[str, Any]): The subset of the client
120 configuration to use. For example, if you have a web client
121 you would pass in `client_config['web']`.
122
123 Returns:
124 google.oauth2.credentials.Credentials: The constructed credentials.
125
126 Raises:
127 ValueError: If there is no access token in the session.
128 """
129 client_config = client_config if client_config is not None else {}
130
131 if not session.token:
132 raise ValueError(
133 'There is no access token for this session, did you call '
134 'fetch_token?')
135
136 return google.oauth2.credentials.Credentials(
137 session.token['access_token'],
138 refresh_token=session.token.get('refresh_token'),
139 token_uri=client_config.get('token_uri'),
140 client_id=client_config.get('client_id'),
141 client_secret=client_config.get('client_secret'),
142 scopes=session.scope)