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 17A client_secrets.json file contains all the information needed to interact with 18an OAuth 2.0 protected service. 19""" 20 21import json 22 23import six 24 25__author__ = 'jcgregorio@google.com (Joe Gregorio)' 26 27# Properties that make a client_secrets.json file valid. 28TYPE_WEB = 'web' 29TYPE_INSTALLED = 'installed' 30 31VALID_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 61class Error(Exception): 62 """Base error for this module.""" 63 64 65class InvalidClientSecretsError(Error): 66 """Format of ClientSecrets file is invalid.""" 67 68 69def _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: {0}.'.format(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 "{0}" in a client type of "{1}".'.format( 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 "{0}" is not configured.'.format(prop_name)) 107 return client_type, client_info 108 109 110def load(fp): 111 obj = json.load(fp) 112 return _validate_clientsecrets(obj) 113 114 115def loads(s): 116 obj = json.loads(s) 117 return _validate_clientsecrets(obj) 118 119 120def _loadfile(filename): 121 try: 122 with open(filename, 'r') as fp: 123 obj = json.load(fp) 124 except IOError as exc: 125 raise InvalidClientSecretsError('Error opening file', exc.filename, 126 exc.strerror, exc.errno) 127 return _validate_clientsecrets(obj) 128 129 130def loadfile(filename, cache=None): 131 """Loading of client_secrets JSON file, optionally backed by a cache. 132 133 Typical cache storage would be App Engine memcache service, 134 but you can pass in any other cache client that implements 135 these methods: 136 137 * ``get(key, namespace=ns)`` 138 * ``set(key, value, namespace=ns)`` 139 140 Usage:: 141 142 # without caching 143 client_type, client_info = loadfile('secrets.json') 144 # using App Engine memcache service 145 from google.appengine.api import memcache 146 client_type, client_info = loadfile('secrets.json', cache=memcache) 147 148 Args: 149 filename: string, Path to a client_secrets.json file on a filesystem. 150 cache: An optional cache service client that implements get() and set() 151 methods. If not specified, the file is always being loaded from 152 a filesystem. 153 154 Raises: 155 InvalidClientSecretsError: In case of a validation error or some 156 I/O failure. Can happen only on cache miss. 157 158 Returns: 159 (client_type, client_info) tuple, as _loadfile() normally would. 160 JSON contents is validated only during first load. Cache hits are not 161 validated. 162 """ 163 _SECRET_NAMESPACE = 'oauth2client:secrets#ns' 164 165 if not cache: 166 return _loadfile(filename) 167 168 obj = cache.get(filename, namespace=_SECRET_NAMESPACE) 169 if obj is None: 170 client_type, client_info = _loadfile(filename) 171 obj = {client_type: client_info} 172 cache.set(filename, obj, namespace=_SECRET_NAMESPACE) 173 174 return next(six.iteritems(obj)) 175