Package oauth2client :: Module clientsecrets
[hide private]
[frames] | no frames]

Source Code for Module oauth2client.clientsecrets

  1  # Copyright (C) 2011 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  """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  __author__ = 'jcgregorio@google.com (Joe Gregorio)' 
 22   
 23   
 24  from anyjson import simplejson 
 25   
 26  # Properties that make a client_secrets.json file valid. 
 27  TYPE_WEB = 'web' 
 28  TYPE_INSTALLED = 'installed' 
 29   
 30  VALID_CLIENT = { 
 31      TYPE_WEB: { 
 32          'required': [ 
 33              'client_id', 
 34              'client_secret', 
 35              'redirect_uris', 
 36              'auth_uri', 
 37              'token_uri'], 
 38          'string': [ 
 39              'client_id', 
 40              'client_secret' 
 41              ] 
 42          }, 
 43      TYPE_INSTALLED: { 
 44          'required': [ 
 45              'client_id', 
 46              'client_secret', 
 47              'redirect_uris', 
 48              'auth_uri', 
 49              'token_uri'], 
 50          'string': [ 
 51              'client_id', 
 52              'client_secret' 
 53              ] 
 54        } 
 55      } 
 56   
57 -class Error(Exception):
58 """Base error for this module.""" 59 pass
60 61
62 -class InvalidClientSecretsError(Error):
63 """Format of ClientSecrets file is invalid.""" 64 pass
65 66
67 -def _validate_clientsecrets(obj):
68 if obj is None or len(obj) != 1: 69 raise InvalidClientSecretsError('Invalid file format.') 70 client_type = obj.keys()[0] 71 if client_type not in VALID_CLIENT.keys(): 72 raise InvalidClientSecretsError('Unknown client type: %s.' % client_type) 73 client_info = obj[client_type] 74 for prop_name in VALID_CLIENT[client_type]['required']: 75 if prop_name not in client_info: 76 raise InvalidClientSecretsError( 77 'Missing property "%s" in a client type of "%s".' % (prop_name, 78 client_type)) 79 for prop_name in VALID_CLIENT[client_type]['string']: 80 if client_info[prop_name].startswith('[['): 81 raise InvalidClientSecretsError( 82 'Property "%s" is not configured.' % prop_name) 83 return client_type, client_info
84 85
86 -def load(fp):
87 obj = simplejson.load(fp) 88 return _validate_clientsecrets(obj)
89 90
91 -def loads(s):
92 obj = simplejson.loads(s) 93 return _validate_clientsecrets(obj)
94 95
96 -def _loadfile(filename):
97 try: 98 fp = file(filename, 'r') 99 try: 100 obj = simplejson.load(fp) 101 finally: 102 fp.close() 103 except IOError: 104 raise InvalidClientSecretsError('File not found: "%s"' % filename) 105 return _validate_clientsecrets(obj)
106 107
108 -def loadfile(filename, cache=None):
109 """Loading of client_secrets JSON file, optionally backed by a cache. 110 111 Typical cache storage would be App Engine memcache service, 112 but you can pass in any other cache client that implements 113 these methods: 114 - get(key, namespace=ns) 115 - set(key, value, namespace=ns) 116 117 Usage: 118 # without caching 119 client_type, client_info = loadfile('secrets.json') 120 # using App Engine memcache service 121 from google.appengine.api import memcache 122 client_type, client_info = loadfile('secrets.json', cache=memcache) 123 124 Args: 125 filename: string, Path to a client_secrets.json file on a filesystem. 126 cache: An optional cache service client that implements get() and set() 127 methods. If not specified, the file is always being loaded from 128 a filesystem. 129 130 Raises: 131 InvalidClientSecretsError: In case of a validation error or some 132 I/O failure. Can happen only on cache miss. 133 134 Returns: 135 (client_type, client_info) tuple, as _loadfile() normally would. 136 JSON contents is validated only during first load. Cache hits are not 137 validated. 138 """ 139 _SECRET_NAMESPACE = 'oauth2client:secrets#ns' 140 141 if not cache: 142 return _loadfile(filename) 143 144 obj = cache.get(filename, namespace=_SECRET_NAMESPACE) 145 if obj is None: 146 client_type, client_info = _loadfile(filename) 147 obj = { client_type: client_info } 148 cache.set(filename, obj, namespace=_SECRET_NAMESPACE) 149 150 return obj.iteritems().next()
151