blob: ac99aae969f17c9b71787cfb5bc4984f0b8055af [file] [log] [blame]
Joe Gregoriof08a4982011-10-07 13:11:16 -04001# 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
17A client_secrets.json file contains all the information needed to interact with
18an OAuth 2.0 protected service.
19"""
20
21__author__ = 'jcgregorio@google.com (Joe Gregorio)'
22
23
Joe Gregorio549230c2012-01-11 10:38:05 -050024from anyjson import simplejson
Joe Gregoriof08a4982011-10-07 13:11:16 -040025
26# Properties that make a client_secrets.json file valid.
27TYPE_WEB = 'web'
28TYPE_INSTALLED = 'installed'
29
30VALID_CLIENT = {
31 TYPE_WEB: {
32 'required': [
33 'client_id',
34 'client_secret',
35 'redirect_uris',
36 'auth_uri',
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080037 'token_uri',
38 ],
Joe Gregoriof08a4982011-10-07 13:11:16 -040039 'string': [
40 'client_id',
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080041 'client_secret',
42 ],
43 },
Joe Gregoriof08a4982011-10-07 13:11:16 -040044 TYPE_INSTALLED: {
45 'required': [
46 'client_id',
47 'client_secret',
48 'redirect_uris',
49 'auth_uri',
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080050 'token_uri',
51 ],
Joe Gregoriof08a4982011-10-07 13:11:16 -040052 'string': [
53 'client_id',
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080054 'client_secret',
55 ],
56 },
57}
58
Joe Gregoriof08a4982011-10-07 13:11:16 -040059
60class Error(Exception):
61 """Base error for this module."""
62 pass
63
64
65class InvalidClientSecretsError(Error):
66 """Format of ClientSecrets file is invalid."""
67 pass
68
69
70def _validate_clientsecrets(obj):
71 if obj is None or len(obj) != 1:
72 raise InvalidClientSecretsError('Invalid file format.')
73 client_type = obj.keys()[0]
74 if client_type not in VALID_CLIENT.keys():
75 raise InvalidClientSecretsError('Unknown client type: %s.' % client_type)
76 client_info = obj[client_type]
77 for prop_name in VALID_CLIENT[client_type]['required']:
78 if prop_name not in client_info:
79 raise InvalidClientSecretsError(
80 'Missing property "%s" in a client type of "%s".' % (prop_name,
81 client_type))
82 for prop_name in VALID_CLIENT[client_type]['string']:
83 if client_info[prop_name].startswith('[['):
84 raise InvalidClientSecretsError(
85 'Property "%s" is not configured.' % prop_name)
86 return client_type, client_info
87
88
89def load(fp):
90 obj = simplejson.load(fp)
91 return _validate_clientsecrets(obj)
92
93
94def loads(s):
95 obj = simplejson.loads(s)
96 return _validate_clientsecrets(obj)
97
98
Joe Gregorioc29aaa92012-07-16 16:16:31 -040099def _loadfile(filename):
Joe Gregoriof08a4982011-10-07 13:11:16 -0400100 try:
101 fp = file(filename, 'r')
102 try:
103 obj = simplejson.load(fp)
104 finally:
105 fp.close()
106 except IOError:
107 raise InvalidClientSecretsError('File not found: "%s"' % filename)
108 return _validate_clientsecrets(obj)
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400109
110
111def loadfile(filename, cache=None):
112 """Loading of client_secrets JSON file, optionally backed by a cache.
113
114 Typical cache storage would be App Engine memcache service,
115 but you can pass in any other cache client that implements
116 these methods:
117 - get(key, namespace=ns)
118 - set(key, value, namespace=ns)
119
120 Usage:
121 # without caching
122 client_type, client_info = loadfile('secrets.json')
123 # using App Engine memcache service
124 from google.appengine.api import memcache
125 client_type, client_info = loadfile('secrets.json', cache=memcache)
126
127 Args:
128 filename: string, Path to a client_secrets.json file on a filesystem.
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800129 cache: An optional cache service client that implements get() and set()
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400130 methods. If not specified, the file is always being loaded from
131 a filesystem.
132
133 Raises:
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800134 InvalidClientSecretsError: In case of a validation error or some
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400135 I/O failure. Can happen only on cache miss.
136
137 Returns:
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800138 (client_type, client_info) tuple, as _loadfile() normally would.
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400139 JSON contents is validated only during first load. Cache hits are not
140 validated.
141 """
142 _SECRET_NAMESPACE = 'oauth2client:secrets#ns'
143
144 if not cache:
145 return _loadfile(filename)
146
147 obj = cache.get(filename, namespace=_SECRET_NAMESPACE)
148 if obj is None:
149 client_type, client_info = _loadfile(filename)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800150 obj = {client_type: client_info}
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400151 cache.set(filename, obj, namespace=_SECRET_NAMESPACE)
152
153 return obj.iteritems().next()