OLD | NEW |
(Empty) | |
| 1 # Copyright 2014 Google Inc. All rights reserved. |
| 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 """Utilities for reading OAuth 2.0 client secret files. |
| 16 |
| 17 A client_secrets.json file contains all the information needed to interact with |
| 18 an OAuth 2.0 protected service. |
| 19 """ |
| 20 |
| 21 import json |
| 22 import six |
| 23 |
| 24 |
| 25 __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 26 |
| 27 # Properties that make a client_secrets.json file valid. |
| 28 TYPE_WEB = 'web' |
| 29 TYPE_INSTALLED = 'installed' |
| 30 |
| 31 VALID_CLIENT = { |
| 32 TYPE_WEB: { |
| 33 'required': [ |
| 34 'client_id', |
| 35 'client_secret', |
| 36 'redirect_uris', |
| 37 'auth_uri', |
| 38 'token_uri', |
| 39 ], |
| 40 'string': [ |
| 41 'client_id', |
| 42 'client_secret', |
| 43 ], |
| 44 }, |
| 45 TYPE_INSTALLED: { |
| 46 'required': [ |
| 47 'client_id', |
| 48 'client_secret', |
| 49 'redirect_uris', |
| 50 'auth_uri', |
| 51 'token_uri', |
| 52 ], |
| 53 'string': [ |
| 54 'client_id', |
| 55 'client_secret', |
| 56 ], |
| 57 }, |
| 58 } |
| 59 |
| 60 |
| 61 class Error(Exception): |
| 62 """Base error for this module.""" |
| 63 |
| 64 |
| 65 class InvalidClientSecretsError(Error): |
| 66 """Format of ClientSecrets file is invalid.""" |
| 67 |
| 68 |
| 69 def _validate_clientsecrets(clientsecrets_dict): |
| 70 """Validate parsed client secrets from a file. |
| 71 |
| 72 Args: |
| 73 clientsecrets_dict: dict, a dictionary holding the client secrets. |
| 74 |
| 75 Returns: |
| 76 tuple, a string of the client type and the information parsed |
| 77 from the file. |
| 78 """ |
| 79 _INVALID_FILE_FORMAT_MSG = ( |
| 80 'Invalid file format. See ' |
| 81 'https://developers.google.com/api-client-library/' |
| 82 'python/guide/aaa_client_secrets') |
| 83 |
| 84 if clientsecrets_dict is None: |
| 85 raise InvalidClientSecretsError(_INVALID_FILE_FORMAT_MSG) |
| 86 try: |
| 87 (client_type, client_info), = clientsecrets_dict.items() |
| 88 except (ValueError, AttributeError): |
| 89 raise InvalidClientSecretsError( |
| 90 _INVALID_FILE_FORMAT_MSG + ' ' |
| 91 'Expected a JSON object with a single property for a "web" or ' |
| 92 '"installed" application') |
| 93 |
| 94 if client_type not in VALID_CLIENT: |
| 95 raise InvalidClientSecretsError( |
| 96 'Unknown client type: %s.' % (client_type,)) |
| 97 |
| 98 for prop_name in VALID_CLIENT[client_type]['required']: |
| 99 if prop_name not in client_info: |
| 100 raise InvalidClientSecretsError( |
| 101 'Missing property "%s" in a client type of "%s".' % |
| 102 (prop_name, client_type)) |
| 103 for prop_name in VALID_CLIENT[client_type]['string']: |
| 104 if client_info[prop_name].startswith('[['): |
| 105 raise InvalidClientSecretsError( |
| 106 'Property "%s" is not configured.' % prop_name) |
| 107 return client_type, client_info |
| 108 |
| 109 |
| 110 def load(fp): |
| 111 obj = json.load(fp) |
| 112 return _validate_clientsecrets(obj) |
| 113 |
| 114 |
| 115 def loads(s): |
| 116 obj = json.loads(s) |
| 117 return _validate_clientsecrets(obj) |
| 118 |
| 119 |
| 120 def _loadfile(filename): |
| 121 try: |
| 122 with open(filename, 'r') as fp: |
| 123 obj = json.load(fp) |
| 124 except IOError: |
| 125 raise InvalidClientSecretsError('File not found: "%s"' % filename) |
| 126 return _validate_clientsecrets(obj) |
| 127 |
| 128 |
| 129 def loadfile(filename, cache=None): |
| 130 """Loading of client_secrets JSON file, optionally backed by a cache. |
| 131 |
| 132 Typical cache storage would be App Engine memcache service, |
| 133 but you can pass in any other cache client that implements |
| 134 these methods: |
| 135 |
| 136 * ``get(key, namespace=ns)`` |
| 137 * ``set(key, value, namespace=ns)`` |
| 138 |
| 139 Usage:: |
| 140 |
| 141 # without caching |
| 142 client_type, client_info = loadfile('secrets.json') |
| 143 # using App Engine memcache service |
| 144 from google.appengine.api import memcache |
| 145 client_type, client_info = loadfile('secrets.json', cache=memcache) |
| 146 |
| 147 Args: |
| 148 filename: string, Path to a client_secrets.json file on a filesystem. |
| 149 cache: An optional cache service client that implements get() and set() |
| 150 methods. If not specified, the file is always being loaded from |
| 151 a filesystem. |
| 152 |
| 153 Raises: |
| 154 InvalidClientSecretsError: In case of a validation error or some |
| 155 I/O failure. Can happen only on cache miss. |
| 156 |
| 157 Returns: |
| 158 (client_type, client_info) tuple, as _loadfile() normally would. |
| 159 JSON contents is validated only during first load. Cache hits are not |
| 160 validated. |
| 161 """ |
| 162 _SECRET_NAMESPACE = 'oauth2client:secrets#ns' |
| 163 |
| 164 if not cache: |
| 165 return _loadfile(filename) |
| 166 |
| 167 obj = cache.get(filename, namespace=_SECRET_NAMESPACE) |
| 168 if obj is None: |
| 169 client_type, client_info = _loadfile(filename) |
| 170 obj = {client_type: client_info} |
| 171 cache.set(filename, obj, namespace=_SECRET_NAMESPACE) |
| 172 |
| 173 return next(six.iteritems(obj)) |
OLD | NEW |