blob: a0013508326ec1878dcc8aeacc7521e40f49404b [file] [log] [blame]
Joe Gregorio695fdc12011-01-16 16:46:55 -05001# Copyright (C) 2010 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 Google App Engine
16
Joe Gregorio7c22ab22011-02-16 15:32:39 -050017Utilities for making it easier to use OAuth 2.0 on Google App Engine.
Joe Gregorio695fdc12011-01-16 16:46:55 -050018"""
19
20__author__ = 'jcgregorio@google.com (Joe Gregorio)'
21
Joe Gregorio1daa71b2011-09-15 18:12:14 -040022import base64
Joe Gregorio77254c12012-08-27 14:13:22 -040023import cgi
Joe Gregorio432f17e2011-05-22 23:18:00 -040024import httplib2
Joe Gregorio1daa71b2011-09-15 18:12:14 -040025import logging
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040026import os
Joe Gregorio695fdc12011-01-16 16:46:55 -050027import pickle
Joe Gregoriob8b6fea2013-05-16 15:52:57 -040028import threading
JacobMoshenko8e905102011-06-20 09:53:10 -040029import time
JacobMoshenko8e905102011-06-20 09:53:10 -040030
Joe Gregoriod84d6b82012-02-28 14:53:00 -050031from google.appengine.api import app_identity
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040032from google.appengine.api import memcache
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040033from google.appengine.api import users
Joe Gregorio432f17e2011-05-22 23:18:00 -040034from google.appengine.ext import db
35from google.appengine.ext import webapp
36from google.appengine.ext.webapp.util import login_required
37from google.appengine.ext.webapp.util import run_wsgi_app
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080038from oauth2client import GOOGLE_AUTH_URI
39from oauth2client import GOOGLE_REVOKE_URI
40from oauth2client import GOOGLE_TOKEN_URI
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040041from oauth2client import clientsecrets
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040042from oauth2client import util
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040043from oauth2client import xsrfutil
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040044from oauth2client.anyjson import simplejson
45from oauth2client.client import AccessTokenRefreshError
46from oauth2client.client import AssertionCredentials
47from oauth2client.client import Credentials
48from oauth2client.client import Flow
49from oauth2client.client import OAuth2WebServerFlow
50from oauth2client.client import Storage
Joe Gregorioa19f3a72012-07-11 15:35:35 -040051
Joe Gregorio78787b62013-02-08 15:36:21 -050052# TODO(dhermes): Resolve import issue.
53# This is a temporary fix for a Google internal issue.
54try:
55 from google.appengine.ext import ndb
56except ImportError:
57 ndb = None
58
Joe Gregoriocda87522013-02-22 16:22:48 -050059
Joe Gregorioa19f3a72012-07-11 15:35:35 -040060logger = logging.getLogger(__name__)
61
Joe Gregorio432f17e2011-05-22 23:18:00 -040062OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns'
Joe Gregorio695fdc12011-01-16 16:46:55 -050063
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040064XSRF_MEMCACHE_ID = 'xsrf_secret_key'
65
JacobMoshenko8e905102011-06-20 09:53:10 -040066
Joe Gregorio77254c12012-08-27 14:13:22 -040067def _safe_html(s):
68 """Escape text to make it safe to display.
69
70 Args:
71 s: string, The text to escape.
72
73 Returns:
74 The escaped text as a string.
75 """
76 return cgi.escape(s, quote=1).replace("'", ''')
77
78
Joe Gregoriof08a4982011-10-07 13:11:16 -040079class InvalidClientSecretsError(Exception):
80 """The client_secrets.json file is malformed or missing required fields."""
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040081
82
83class InvalidXsrfTokenError(Exception):
84 """The XSRF token is invalid or expired."""
85
86
87class SiteXsrfSecretKey(db.Model):
88 """Storage for the sites XSRF secret key.
89
90 There will only be one instance stored of this model, the one used for the
dhermes@google.com47154822012-11-26 10:44:09 -080091 site.
92 """
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040093 secret = db.StringProperty()
94
Joe Gregorio78787b62013-02-08 15:36:21 -050095if ndb is not None:
96 class SiteXsrfSecretKeyNDB(ndb.Model):
97 """NDB Model for storage for the sites XSRF secret key.
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040098
Joe Gregorio78787b62013-02-08 15:36:21 -050099 Since this model uses the same kind as SiteXsrfSecretKey, it can be used
100 interchangeably. This simply provides an NDB model for interacting with the
101 same data the DB model interacts with.
dhermes@google.com47154822012-11-26 10:44:09 -0800102
Joe Gregorio78787b62013-02-08 15:36:21 -0500103 There should only be one instance stored of this model, the one used for the
104 site.
105 """
106 secret = ndb.StringProperty()
dhermes@google.com47154822012-11-26 10:44:09 -0800107
Joe Gregorio78787b62013-02-08 15:36:21 -0500108 @classmethod
109 def _get_kind(cls):
110 """Return the kind name for this class."""
111 return 'SiteXsrfSecretKey'
dhermes@google.com47154822012-11-26 10:44:09 -0800112
113
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400114def _generate_new_xsrf_secret_key():
115 """Returns a random XSRF secret key.
116 """
117 return os.urandom(16).encode("hex")
118
119
120def xsrf_secret_key():
121 """Return the secret key for use for XSRF protection.
122
123 If the Site entity does not have a secret key, this method will also create
124 one and persist it.
125
126 Returns:
127 The secret key.
128 """
129 secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE)
130 if not secret:
131 # Load the one and only instance of SiteXsrfSecretKey.
132 model = SiteXsrfSecretKey.get_or_insert(key_name='site')
133 if not model.secret:
134 model.secret = _generate_new_xsrf_secret_key()
135 model.put()
136 secret = model.secret
137 memcache.add(XSRF_MEMCACHE_ID, secret, namespace=OAUTH2CLIENT_NAMESPACE)
138
139 return str(secret)
Joe Gregoriof08a4982011-10-07 13:11:16 -0400140
141
JacobMoshenko8e905102011-06-20 09:53:10 -0400142class AppAssertionCredentials(AssertionCredentials):
143 """Credentials object for App Engine Assertion Grants
144
145 This object will allow an App Engine application to identify itself to Google
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400146 and other OAuth 2.0 servers that can verify assertions. It can be used for the
147 purpose of accessing data stored under an account assigned to the App Engine
148 application itself.
JacobMoshenko8e905102011-06-20 09:53:10 -0400149
150 This credential does not require a flow to instantiate because it represents
151 a two legged flow, and therefore has all of the required information to
152 generate and refresh its own access tokens.
JacobMoshenko8e905102011-06-20 09:53:10 -0400153 """
154
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400155 @util.positional(2)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500156 def __init__(self, scope, **kwargs):
JacobMoshenko8e905102011-06-20 09:53:10 -0400157 """Constructor for AppAssertionCredentials
158
159 Args:
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500160 scope: string or iterable of strings, scope(s) of the credentials being
Joe Gregoriofd08e432012-08-09 14:17:41 -0400161 requested.
JacobMoshenko8e905102011-06-20 09:53:10 -0400162 """
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500163 self.scope = util.scopes_to_string(scope)
JacobMoshenko8e905102011-06-20 09:53:10 -0400164
dhermes@google.com2cc09382013-02-11 08:42:18 -0800165 # Assertion type is no longer used, but still in the parent class signature.
166 super(AppAssertionCredentials, self).__init__(None)
JacobMoshenko8e905102011-06-20 09:53:10 -0400167
Joe Gregorio562b7312011-09-15 09:06:38 -0400168 @classmethod
169 def from_json(cls, json):
170 data = simplejson.loads(json)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500171 return AppAssertionCredentials(data['scope'])
Joe Gregorio562b7312011-09-15 09:06:38 -0400172
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500173 def _refresh(self, http_request):
174 """Refreshes the access_token.
JacobMoshenko8e905102011-06-20 09:53:10 -0400175
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500176 Since the underlying App Engine app_identity implementation does its own
177 caching we can skip all the storage hoops and just to a refresh using the
178 API.
JacobMoshenko8e905102011-06-20 09:53:10 -0400179
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500180 Args:
181 http_request: callable, a callable that matches the method signature of
182 httplib2.Http.request, used to make the refresh request.
JacobMoshenko8e905102011-06-20 09:53:10 -0400183
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500184 Raises:
185 AccessTokenRefreshError: When the refresh fails.
186 """
187 try:
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500188 scopes = self.scope.split()
189 (token, _) = app_identity.get_access_token(scopes)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500190 except app_identity.Error, e:
191 raise AccessTokenRefreshError(str(e))
192 self.access_token = token
JacobMoshenko8e905102011-06-20 09:53:10 -0400193
194
Joe Gregorio695fdc12011-01-16 16:46:55 -0500195class FlowProperty(db.Property):
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500196 """App Engine datastore Property for Flow.
197
dhermes@google.com47154822012-11-26 10:44:09 -0800198 Utility property that allows easy storage and retrieval of an
Joe Gregorio695fdc12011-01-16 16:46:55 -0500199 oauth2client.Flow"""
200
201 # Tell what the user type is.
202 data_type = Flow
203
204 # For writing to datastore.
205 def get_value_for_datastore(self, model_instance):
206 flow = super(FlowProperty,
207 self).get_value_for_datastore(model_instance)
208 return db.Blob(pickle.dumps(flow))
209
210 # For reading from datastore.
211 def make_value_from_datastore(self, value):
212 if value is None:
213 return None
214 return pickle.loads(value)
215
216 def validate(self, value):
217 if value is not None and not isinstance(value, Flow):
Joe Gregorio1daa71b2011-09-15 18:12:14 -0400218 raise db.BadValueError('Property %s must be convertible '
Joe Gregorio695fdc12011-01-16 16:46:55 -0500219 'to a FlowThreeLegged instance (%s)' %
220 (self.name, value))
221 return super(FlowProperty, self).validate(value)
222
223 def empty(self, value):
224 return not value
225
226
Joe Gregorio78787b62013-02-08 15:36:21 -0500227if ndb is not None:
228 class FlowNDBProperty(ndb.PickleProperty):
229 """App Engine NDB datastore Property for Flow.
dhermes@google.com47154822012-11-26 10:44:09 -0800230
Joe Gregorio78787b62013-02-08 15:36:21 -0500231 Serves the same purpose as the DB FlowProperty, but for NDB models. Since
232 PickleProperty inherits from BlobProperty, the underlying representation of
233 the data in the datastore will be the same as in the DB case.
dhermes@google.com47154822012-11-26 10:44:09 -0800234
Joe Gregorio78787b62013-02-08 15:36:21 -0500235 Utility property that allows easy storage and retrieval of an
236 oauth2client.Flow
dhermes@google.com47154822012-11-26 10:44:09 -0800237 """
Joe Gregorio78787b62013-02-08 15:36:21 -0500238
239 def _validate(self, value):
240 """Validates a value as a proper Flow object.
241
242 Args:
243 value: A value to be set on the property.
244
245 Raises:
246 TypeError if the value is not an instance of Flow.
247 """
248 logger.info('validate: Got type %s', type(value))
249 if value is not None and not isinstance(value, Flow):
250 raise TypeError('Property %s must be convertible to a flow '
251 'instance; received: %s.' % (self._name, value))
dhermes@google.com47154822012-11-26 10:44:09 -0800252
253
Joe Gregorio695fdc12011-01-16 16:46:55 -0500254class CredentialsProperty(db.Property):
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500255 """App Engine datastore Property for Credentials.
256
257 Utility property that allows easy storage and retrieval of
Joe Gregorio695fdc12011-01-16 16:46:55 -0500258 oath2client.Credentials
259 """
260
261 # Tell what the user type is.
262 data_type = Credentials
263
264 # For writing to datastore.
265 def get_value_for_datastore(self, model_instance):
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400266 logger.info("get: Got type " + str(type(model_instance)))
Joe Gregorio695fdc12011-01-16 16:46:55 -0500267 cred = super(CredentialsProperty,
268 self).get_value_for_datastore(model_instance)
Joe Gregorio562b7312011-09-15 09:06:38 -0400269 if cred is None:
270 cred = ''
271 else:
272 cred = cred.to_json()
273 return db.Blob(cred)
Joe Gregorio695fdc12011-01-16 16:46:55 -0500274
275 # For reading from datastore.
276 def make_value_from_datastore(self, value):
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400277 logger.info("make: Got type " + str(type(value)))
Joe Gregorio695fdc12011-01-16 16:46:55 -0500278 if value is None:
279 return None
Joe Gregorio562b7312011-09-15 09:06:38 -0400280 if len(value) == 0:
281 return None
Joe Gregorio562b7312011-09-15 09:06:38 -0400282 try:
283 credentials = Credentials.new_from_json(value)
284 except ValueError:
Joe Gregorioec555842011-10-27 11:10:39 -0400285 credentials = None
Joe Gregorio562b7312011-09-15 09:06:38 -0400286 return credentials
Joe Gregorio695fdc12011-01-16 16:46:55 -0500287
288 def validate(self, value):
Joe Gregorio1daa71b2011-09-15 18:12:14 -0400289 value = super(CredentialsProperty, self).validate(value)
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400290 logger.info("validate: Got type " + str(type(value)))
Joe Gregorio695fdc12011-01-16 16:46:55 -0500291 if value is not None and not isinstance(value, Credentials):
Joe Gregorio562b7312011-09-15 09:06:38 -0400292 raise db.BadValueError('Property %s must be convertible '
Joe Gregorio1daa71b2011-09-15 18:12:14 -0400293 'to a Credentials instance (%s)' %
294 (self.name, value))
295 #if value is not None and not isinstance(value, Credentials):
296 # return None
297 return value
Joe Gregorio695fdc12011-01-16 16:46:55 -0500298
299
Joe Gregorio78787b62013-02-08 15:36:21 -0500300if ndb is not None:
301 # TODO(dhermes): Turn this into a JsonProperty and overhaul the Credentials
302 # and subclass mechanics to use new_from_dict, to_dict,
303 # from_dict, etc.
304 class CredentialsNDBProperty(ndb.BlobProperty):
305 """App Engine NDB datastore Property for Credentials.
Joe Gregorio695fdc12011-01-16 16:46:55 -0500306
Joe Gregorio78787b62013-02-08 15:36:21 -0500307 Serves the same purpose as the DB CredentialsProperty, but for NDB models.
308 Since CredentialsProperty stores data as a blob and this inherits from
309 BlobProperty, the data in the datastore will be the same as in the DB case.
dhermes@google.com47154822012-11-26 10:44:09 -0800310
Joe Gregorio78787b62013-02-08 15:36:21 -0500311 Utility property that allows easy storage and retrieval of Credentials and
312 subclasses.
dhermes@google.com47154822012-11-26 10:44:09 -0800313 """
Joe Gregorio78787b62013-02-08 15:36:21 -0500314 def _validate(self, value):
315 """Validates a value as a proper credentials object.
dhermes@google.com47154822012-11-26 10:44:09 -0800316
Joe Gregorio78787b62013-02-08 15:36:21 -0500317 Args:
318 value: A value to be set on the property.
dhermes@google.com47154822012-11-26 10:44:09 -0800319
Joe Gregorio78787b62013-02-08 15:36:21 -0500320 Raises:
321 TypeError if the value is not an instance of Credentials.
322 """
323 logger.info('validate: Got type %s', type(value))
324 if value is not None and not isinstance(value, Credentials):
325 raise TypeError('Property %s must be convertible to a credentials '
326 'instance; received: %s.' % (self._name, value))
dhermes@google.com47154822012-11-26 10:44:09 -0800327
Joe Gregorio78787b62013-02-08 15:36:21 -0500328 def _to_base_type(self, value):
329 """Converts our validated value to a JSON serialized string.
dhermes@google.com47154822012-11-26 10:44:09 -0800330
Joe Gregorio78787b62013-02-08 15:36:21 -0500331 Args:
332 value: A value to be set in the datastore.
dhermes@google.com47154822012-11-26 10:44:09 -0800333
Joe Gregorio78787b62013-02-08 15:36:21 -0500334 Returns:
335 A JSON serialized version of the credential, else '' if value is None.
336 """
337 if value is None:
338 return ''
339 else:
340 return value.to_json()
dhermes@google.com47154822012-11-26 10:44:09 -0800341
Joe Gregorio78787b62013-02-08 15:36:21 -0500342 def _from_base_type(self, value):
343 """Converts our stored JSON string back to the desired type.
344
345 Args:
346 value: A value from the datastore to be converted to the desired type.
347
348 Returns:
349 A deserialized Credentials (or subclass) object, else None if the
350 value can't be parsed.
351 """
352 if not value:
353 return None
354 try:
355 # Uses the from_json method of the implied class of value
356 credentials = Credentials.new_from_json(value)
357 except ValueError:
358 credentials = None
359 return credentials
dhermes@google.com47154822012-11-26 10:44:09 -0800360
361
362class StorageByKeyName(Storage):
363 """Store and retrieve a credential to and from the App Engine datastore.
364
365 This Storage helper presumes the Credentials have been stored as a
366 CredentialsProperty or CredentialsNDBProperty on a datastore model class, and
367 that entities are stored by key_name.
Joe Gregorio695fdc12011-01-16 16:46:55 -0500368 """
369
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400370 @util.positional(4)
Daniel Hermes58341a02013-04-05 09:58:16 -0700371 def __init__(self, model, key_name, property_name, cache=None, user=None):
Joe Gregorio695fdc12011-01-16 16:46:55 -0500372 """Constructor for Storage.
373
374 Args:
dhermes@google.com47154822012-11-26 10:44:09 -0800375 model: db.Model or ndb.Model, model class
Joe Gregorio695fdc12011-01-16 16:46:55 -0500376 key_name: string, key name for the entity that has the credentials
JacobMoshenko8e905102011-06-20 09:53:10 -0400377 property_name: string, name of the property that is a CredentialsProperty
dhermes@google.com47154822012-11-26 10:44:09 -0800378 or CredentialsNDBProperty.
379 cache: memcache, a write-through cache to put in front of the datastore.
380 If the model you are using is an NDB model, using a cache will be
381 redundant since the model uses an instance cache and memcache for you.
Daniel Hermes58341a02013-04-05 09:58:16 -0700382 user: users.User object, optional. Can be used to grab user ID as a
383 key_name if no key name is specified.
Joe Gregorio695fdc12011-01-16 16:46:55 -0500384 """
Daniel Hermes58341a02013-04-05 09:58:16 -0700385 if key_name is None:
386 if user is None:
387 raise ValueError('StorageByKeyName called with no key name or user.')
388 key_name = user.user_id()
389
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500390 self._model = model
391 self._key_name = key_name
392 self._property_name = property_name
Joe Gregorio432f17e2011-05-22 23:18:00 -0400393 self._cache = cache
Joe Gregorio695fdc12011-01-16 16:46:55 -0500394
dhermes@google.com47154822012-11-26 10:44:09 -0800395 def _is_ndb(self):
396 """Determine whether the model of the instance is an NDB model.
397
398 Returns:
399 Boolean indicating whether or not the model is an NDB or DB model.
400 """
401 # issubclass will fail if one of the arguments is not a class, only need
402 # worry about new-style classes since ndb and db models are new-style
403 if isinstance(self._model, type):
Joe Gregorio78787b62013-02-08 15:36:21 -0500404 if ndb is not None and issubclass(self._model, ndb.Model):
dhermes@google.com47154822012-11-26 10:44:09 -0800405 return True
406 elif issubclass(self._model, db.Model):
407 return False
408
409 raise TypeError('Model class not an NDB or DB model: %s.' % (self._model,))
410
411 def _get_entity(self):
412 """Retrieve entity from datastore.
413
414 Uses a different model method for db or ndb models.
415
416 Returns:
417 Instance of the model corresponding to the current storage object
418 and stored using the key name of the storage object.
419 """
420 if self._is_ndb():
421 return self._model.get_by_id(self._key_name)
422 else:
423 return self._model.get_by_key_name(self._key_name)
424
425 def _delete_entity(self):
426 """Delete entity from datastore.
427
428 Attempts to delete using the key_name stored on the object, whether or not
429 the given key is in the datastore.
430 """
431 if self._is_ndb():
432 ndb.Key(self._model, self._key_name).delete()
433 else:
434 entity_key = db.Key.from_path(self._model.kind(), self._key_name)
435 db.delete(entity_key)
436
Joe Gregoriod2ee4d82011-09-15 14:32:45 -0400437 def locked_get(self):
Joe Gregorio695fdc12011-01-16 16:46:55 -0500438 """Retrieve Credential from datastore.
439
440 Returns:
441 oauth2client.Credentials
442 """
Joe Gregorioe912d182013-08-06 11:30:44 -0400443 credentials = None
Joe Gregorio432f17e2011-05-22 23:18:00 -0400444 if self._cache:
Joe Gregorio562b7312011-09-15 09:06:38 -0400445 json = self._cache.get(self._key_name)
446 if json:
Joe Gregorioe912d182013-08-06 11:30:44 -0400447 credentials = Credentials.new_from_json(json)
448 if credentials is None:
449 entity = self._get_entity()
450 if entity is not None:
451 credentials = getattr(entity, self._property_name)
Joe Gregorio9fa077c2011-11-18 08:16:52 -0500452 if self._cache:
dhermes@google.com47154822012-11-26 10:44:09 -0800453 self._cache.set(self._key_name, credentials.to_json())
Joe Gregorio432f17e2011-05-22 23:18:00 -0400454
Joe Gregorioe912d182013-08-06 11:30:44 -0400455 if credentials and hasattr(credentials, 'set_store'):
456 credentials.set_store(self)
dhermes@google.com47154822012-11-26 10:44:09 -0800457 return credentials
Joe Gregorio695fdc12011-01-16 16:46:55 -0500458
Joe Gregoriod2ee4d82011-09-15 14:32:45 -0400459 def locked_put(self, credentials):
Joe Gregorio695fdc12011-01-16 16:46:55 -0500460 """Write a Credentials to the datastore.
461
462 Args:
463 credentials: Credentials, the credentials to store.
464 """
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500465 entity = self._model.get_or_insert(self._key_name)
466 setattr(entity, self._property_name, credentials)
Joe Gregorio695fdc12011-01-16 16:46:55 -0500467 entity.put()
Joe Gregorio432f17e2011-05-22 23:18:00 -0400468 if self._cache:
Joe Gregorio562b7312011-09-15 09:06:38 -0400469 self._cache.set(self._key_name, credentials.to_json())
Joe Gregorio432f17e2011-05-22 23:18:00 -0400470
Joe Gregorioec75dc12012-02-06 13:40:42 -0500471 def locked_delete(self):
472 """Delete Credential from datastore."""
473
474 if self._cache:
475 self._cache.delete(self._key_name)
476
dhermes@google.com47154822012-11-26 10:44:09 -0800477 self._delete_entity()
Joe Gregorioec75dc12012-02-06 13:40:42 -0500478
Joe Gregorio432f17e2011-05-22 23:18:00 -0400479
480class CredentialsModel(db.Model):
481 """Storage for OAuth 2.0 Credentials
482
483 Storage of the model is keyed by the user.user_id().
484 """
485 credentials = CredentialsProperty()
486
487
Joe Gregorio78787b62013-02-08 15:36:21 -0500488if ndb is not None:
489 class CredentialsNDBModel(ndb.Model):
490 """NDB Model for storage of OAuth 2.0 Credentials
dhermes@google.com47154822012-11-26 10:44:09 -0800491
Joe Gregorio78787b62013-02-08 15:36:21 -0500492 Since this model uses the same kind as CredentialsModel and has a property
493 which can serialize and deserialize Credentials correctly, it can be used
494 interchangeably with a CredentialsModel to access, insert and delete the
495 same entities. This simply provides an NDB model for interacting with the
496 same data the DB model interacts with.
dhermes@google.com47154822012-11-26 10:44:09 -0800497
Joe Gregorio78787b62013-02-08 15:36:21 -0500498 Storage of the model is keyed by the user.user_id().
499 """
500 credentials = CredentialsNDBProperty()
dhermes@google.com47154822012-11-26 10:44:09 -0800501
Joe Gregorio78787b62013-02-08 15:36:21 -0500502 @classmethod
503 def _get_kind(cls):
504 """Return the kind name for this class."""
505 return 'CredentialsModel'
dhermes@google.com47154822012-11-26 10:44:09 -0800506
507
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400508def _build_state_value(request_handler, user):
509 """Composes the value for the 'state' parameter.
510
511 Packs the current request URI and an XSRF token into an opaque string that
512 can be passed to the authentication server via the 'state' parameter.
513
514 Args:
515 request_handler: webapp.RequestHandler, The request.
516 user: google.appengine.api.users.User, The current user.
517
518 Returns:
519 The state value as a string.
520 """
521 uri = request_handler.request.url
522 token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(),
523 action_id=str(uri))
524 return uri + ':' + token
525
526
527def _parse_state_value(state, user):
528 """Parse the value of the 'state' parameter.
529
530 Parses the value and validates the XSRF token in the state parameter.
531
532 Args:
533 state: string, The value of the state parameter.
534 user: google.appengine.api.users.User, The current user.
535
536 Raises:
537 InvalidXsrfTokenError: if the XSRF token is invalid.
538
539 Returns:
540 The redirect URI.
541 """
542 uri, token = state.rsplit(':', 1)
543 if not xsrfutil.validate_token(xsrf_secret_key(), token, user.user_id(),
544 action_id=uri):
545 raise InvalidXsrfTokenError()
546
547 return uri
548
549
Joe Gregorio432f17e2011-05-22 23:18:00 -0400550class OAuth2Decorator(object):
551 """Utility for making OAuth 2.0 easier.
552
553 Instantiate and then use with oauth_required or oauth_aware
554 as decorators on webapp.RequestHandler methods.
555
556 Example:
557
558 decorator = OAuth2Decorator(
559 client_id='837...ent.com',
560 client_secret='Qh...wwI',
Joe Gregorioc4fc0952011-11-09 12:21:11 -0500561 scope='https://www.googleapis.com/auth/plus')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400562
563
564 class MainHandler(webapp.RequestHandler):
565
566 @decorator.oauth_required
567 def get(self):
568 http = decorator.http()
569 # http is authorized with the user's Credentials and can be used
570 # in API calls
571
572 """
JacobMoshenko8e905102011-06-20 09:53:10 -0400573
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400574 def set_credentials(self, credentials):
575 self._tls.credentials = credentials
576
577 def get_credentials(self):
Joe Gregorioc211bec2013-08-06 12:06:54 -0400578 """A thread local Credentials object.
579
580 Returns:
581 A client.Credentials object, or None if credentials hasn't been set in
582 this thread yet, which may happen when calling has_credentials inside
583 oauth_aware.
584 """
585 return getattr(self._tls, 'credentials', None)
586
587 credentials = property(get_credentials, set_credentials)
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400588
589 def set_flow(self, flow):
590 self._tls.flow = flow
591
592 def get_flow(self):
Joe Gregorioc211bec2013-08-06 12:06:54 -0400593 """A thread local Flow object.
594
595 Returns:
596 A credentials.Flow object, or None if the flow hasn't been set in this
597 thread yet, which happens in _create_flow() since Flows are created
598 lazily.
599 """
600 return getattr(self._tls, 'flow', None)
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400601
602 flow = property(get_flow, set_flow)
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400603
604
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400605 @util.positional(4)
JacobMoshenkocb6d8912011-07-08 13:35:15 -0400606 def __init__(self, client_id, client_secret, scope,
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800607 auth_uri=GOOGLE_AUTH_URI,
608 token_uri=GOOGLE_TOKEN_URI,
609 revoke_uri=GOOGLE_REVOKE_URI,
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100610 user_agent=None,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400611 message=None,
612 callback_path='/oauth2callback',
Joe Gregoriocda87522013-02-22 16:22:48 -0500613 token_response_param=None,
Daniel Hermes58341a02013-04-05 09:58:16 -0700614 _storage_class=StorageByKeyName,
615 _credentials_class=CredentialsModel,
616 _credentials_property_name='credentials',
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400617 **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400618
619 """Constructor for OAuth2Decorator
620
621 Args:
622 client_id: string, client identifier.
623 client_secret: string client secret.
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500624 scope: string or iterable of strings, scope(s) of the credentials being
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400625 requested.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400626 auth_uri: string, URI for authorization endpoint. For convenience
627 defaults to Google's endpoints but any OAuth 2.0 provider can be used.
628 token_uri: string, URI for token endpoint. For convenience
629 defaults to Google's endpoints but any OAuth 2.0 provider can be used.
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800630 revoke_uri: string, URI for revoke endpoint. For convenience
631 defaults to Google's endpoints but any OAuth 2.0 provider can be used.
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100632 user_agent: string, User agent of your application, default to None.
Joe Gregoriof08a4982011-10-07 13:11:16 -0400633 message: Message to display if there are problems with the OAuth 2.0
634 configuration. The message may contain HTML and will be presented on the
635 web interface for any method that uses the decorator.
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400636 callback_path: string, The absolute path to use as the callback URI. Note
637 that this must match up with the URI given when registering the
638 application in the APIs Console.
Joe Gregoriocda87522013-02-22 16:22:48 -0500639 token_response_param: string. If provided, the full JSON response
640 to the access token request will be encoded and included in this query
641 parameter in the callback URI. This is useful with providers (e.g.
642 wordpress.com) that include extra fields that the client may want.
Daniel Hermes58341a02013-04-05 09:58:16 -0700643 _storage_class: "Protected" keyword argument not typically provided to
644 this constructor. A storage class to aid in storing a Credentials object
645 for a user in the datastore. Defaults to StorageByKeyName.
646 _credentials_class: "Protected" keyword argument not typically provided to
647 this constructor. A db or ndb Model class to hold credentials. Defaults
648 to CredentialsModel.
649 _credentials_property_name: "Protected" keyword argument not typically
650 provided to this constructor. A string indicating the name of the field
651 on the _credentials_class where a Credentials object will be stored.
652 Defaults to 'credentials'.
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500653 **kwargs: dict, Keyword arguments are be passed along as kwargs to the
654 OAuth2WebServerFlow constructor.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400655 """
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400656 self._tls = threading.local()
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400657 self.flow = None
Joe Gregorio432f17e2011-05-22 23:18:00 -0400658 self.credentials = None
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400659 self._client_id = client_id
660 self._client_secret = client_secret
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500661 self._scope = util.scopes_to_string(scope)
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400662 self._auth_uri = auth_uri
663 self._token_uri = token_uri
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800664 self._revoke_uri = revoke_uri
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400665 self._user_agent = user_agent
666 self._kwargs = kwargs
Joe Gregoriof08a4982011-10-07 13:11:16 -0400667 self._message = message
668 self._in_error = False
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400669 self._callback_path = callback_path
Joe Gregoriocda87522013-02-22 16:22:48 -0500670 self._token_response_param = token_response_param
Daniel Hermes58341a02013-04-05 09:58:16 -0700671 self._storage_class = _storage_class
672 self._credentials_class = _credentials_class
673 self._credentials_property_name = _credentials_property_name
Joe Gregoriof08a4982011-10-07 13:11:16 -0400674
675 def _display_error_message(self, request_handler):
676 request_handler.response.out.write('<html><body>')
Joe Gregorio77254c12012-08-27 14:13:22 -0400677 request_handler.response.out.write(_safe_html(self._message))
Joe Gregoriof08a4982011-10-07 13:11:16 -0400678 request_handler.response.out.write('</body></html>')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400679
680 def oauth_required(self, method):
681 """Decorator that starts the OAuth 2.0 dance.
682
683 Starts the OAuth dance for the logged in user if they haven't already
684 granted access for this application.
685
686 Args:
687 method: callable, to be decorated method of a webapp.RequestHandler
688 instance.
689 """
JacobMoshenko8e905102011-06-20 09:53:10 -0400690
Joe Gregorio17774972012-03-01 11:11:59 -0500691 def check_oauth(request_handler, *args, **kwargs):
Joe Gregoriof08a4982011-10-07 13:11:16 -0400692 if self._in_error:
693 self._display_error_message(request_handler)
694 return
695
Joe Gregoriof427c532011-06-13 09:35:26 -0400696 user = users.get_current_user()
697 # Don't use @login_decorator as this could be used in a POST request.
698 if not user:
699 request_handler.redirect(users.create_login_url(
700 request_handler.request.uri))
701 return
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400702
703 self._create_flow(request_handler)
704
Joe Gregorio432f17e2011-05-22 23:18:00 -0400705 # Store the request URI in 'state' so we can use it later
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400706 self.flow.params['state'] = _build_state_value(request_handler, user)
Daniel Hermes58341a02013-04-05 09:58:16 -0700707 self.credentials = self._storage_class(
708 self._credentials_class, None,
709 self._credentials_property_name, user=user).get()
Joe Gregorio432f17e2011-05-22 23:18:00 -0400710
711 if not self.has_credentials():
712 return request_handler.redirect(self.authorize_url())
713 try:
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400714 resp = method(request_handler, *args, **kwargs)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400715 except AccessTokenRefreshError:
716 return request_handler.redirect(self.authorize_url())
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400717 finally:
718 self.credentials = None
719 return resp
Joe Gregorio432f17e2011-05-22 23:18:00 -0400720
721 return check_oauth
722
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400723 def _create_flow(self, request_handler):
724 """Create the Flow object.
725
726 The Flow is calculated lazily since we don't know where this app is
727 running until it receives a request, at which point redirect_uri can be
728 calculated and then the Flow object can be constructed.
729
730 Args:
731 request_handler: webapp.RequestHandler, the request handler.
732 """
733 if self.flow is None:
734 redirect_uri = request_handler.request.relative_url(
735 self._callback_path) # Usually /oauth2callback
736 self.flow = OAuth2WebServerFlow(self._client_id, self._client_secret,
737 self._scope, redirect_uri=redirect_uri,
738 user_agent=self._user_agent,
739 auth_uri=self._auth_uri,
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800740 token_uri=self._token_uri,
741 revoke_uri=self._revoke_uri,
742 **self._kwargs)
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400743
Joe Gregorio432f17e2011-05-22 23:18:00 -0400744 def oauth_aware(self, method):
745 """Decorator that sets up for OAuth 2.0 dance, but doesn't do it.
746
747 Does all the setup for the OAuth dance, but doesn't initiate it.
748 This decorator is useful if you want to create a page that knows
749 whether or not the user has granted access to this application.
750 From within a method decorated with @oauth_aware the has_credentials()
751 and authorize_url() methods can be called.
752
753 Args:
754 method: callable, to be decorated method of a webapp.RequestHandler
755 instance.
756 """
JacobMoshenko8e905102011-06-20 09:53:10 -0400757
Joe Gregorio17774972012-03-01 11:11:59 -0500758 def setup_oauth(request_handler, *args, **kwargs):
Joe Gregoriof08a4982011-10-07 13:11:16 -0400759 if self._in_error:
760 self._display_error_message(request_handler)
761 return
762
Joe Gregoriof427c532011-06-13 09:35:26 -0400763 user = users.get_current_user()
764 # Don't use @login_decorator as this could be used in a POST request.
765 if not user:
766 request_handler.redirect(users.create_login_url(
767 request_handler.request.uri))
768 return
Joe Gregoriof08a4982011-10-07 13:11:16 -0400769
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400770 self._create_flow(request_handler)
Joe Gregoriof08a4982011-10-07 13:11:16 -0400771
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400772 self.flow.params['state'] = _build_state_value(request_handler, user)
Daniel Hermes58341a02013-04-05 09:58:16 -0700773 self.credentials = self._storage_class(
774 self._credentials_class, None,
775 self._credentials_property_name, user=user).get()
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400776 try:
777 resp = method(request_handler, *args, **kwargs)
778 finally:
779 self.credentials = None
780 return resp
Joe Gregorio432f17e2011-05-22 23:18:00 -0400781 return setup_oauth
782
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400783
Joe Gregorio432f17e2011-05-22 23:18:00 -0400784 def has_credentials(self):
785 """True if for the logged in user there are valid access Credentials.
786
787 Must only be called from with a webapp.RequestHandler subclassed method
788 that had been decorated with either @oauth_required or @oauth_aware.
789 """
790 return self.credentials is not None and not self.credentials.invalid
791
792 def authorize_url(self):
793 """Returns the URL to start the OAuth dance.
794
795 Must only be called from with a webapp.RequestHandler subclassed method
796 that had been decorated with either @oauth_required or @oauth_aware.
797 """
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400798 url = self.flow.step1_get_authorize_url()
Joe Gregorio853bcf32012-03-02 15:30:23 -0500799 return str(url)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400800
Joe Gregoriod8cc4582013-11-26 16:06:56 -0500801 def http(self, *args, **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400802 """Returns an authorized http instance.
803
804 Must only be called from within an @oauth_required decorated method, or
805 from within an @oauth_aware decorated method where has_credentials()
806 returns True.
Joe Gregoriod8cc4582013-11-26 16:06:56 -0500807
808 Args:
809 args: Positional arguments passed to httplib2.Http constructor.
810 kwargs: Positional arguments passed to httplib2.Http constructor.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400811 """
Joe Gregoriod8cc4582013-11-26 16:06:56 -0500812 return self.credentials.authorize(httplib2.Http(*args, **kwargs))
Joe Gregorio432f17e2011-05-22 23:18:00 -0400813
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400814 @property
815 def callback_path(self):
816 """The absolute path where the callback will occur.
817
818 Note this is the absolute path, not the absolute URI, that will be
819 calculated by the decorator at runtime. See callback_handler() for how this
820 should be used.
821
822 Returns:
823 The callback path as a string.
824 """
825 return self._callback_path
826
827
828 def callback_handler(self):
829 """RequestHandler for the OAuth 2.0 redirect callback.
830
831 Usage:
832 app = webapp.WSGIApplication([
833 ('/index', MyIndexHandler),
834 ...,
835 (decorator.callback_path, decorator.callback_handler())
836 ])
837
838 Returns:
839 A webapp.RequestHandler that handles the redirect back from the
840 server during the OAuth 2.0 dance.
841 """
842 decorator = self
843
844 class OAuth2Handler(webapp.RequestHandler):
845 """Handler for the redirect_uri of the OAuth 2.0 dance."""
846
847 @login_required
848 def get(self):
849 error = self.request.get('error')
850 if error:
851 errormsg = self.request.get('error_description', error)
852 self.response.out.write(
Joe Gregorio77254c12012-08-27 14:13:22 -0400853 'The authorization request failed: %s' % _safe_html(errormsg))
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400854 else:
855 user = users.get_current_user()
856 decorator._create_flow(self)
857 credentials = decorator.flow.step2_exchange(self.request.params)
Daniel Hermes58341a02013-04-05 09:58:16 -0700858 decorator._storage_class(
859 decorator._credentials_class, None,
860 decorator._credentials_property_name, user=user).put(credentials)
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400861 redirect_uri = _parse_state_value(str(self.request.get('state')),
862 user)
Joe Gregoriocda87522013-02-22 16:22:48 -0500863
864 if decorator._token_response_param and credentials.token_response:
865 resp_json = simplejson.dumps(credentials.token_response)
Joe Gregorio10244032013-03-06 09:48:04 -0500866 redirect_uri = util._add_query_parameter(
Daniel Hermesf7b648f2013-03-06 09:38:53 -0800867 redirect_uri, decorator._token_response_param, resp_json)
Joe Gregoriocda87522013-02-22 16:22:48 -0500868
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400869 self.redirect(redirect_uri)
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400870
871 return OAuth2Handler
872
873 def callback_application(self):
874 """WSGI application for handling the OAuth 2.0 redirect callback.
875
876 If you need finer grained control use `callback_handler` which returns just
877 the webapp.RequestHandler.
878
879 Returns:
880 A webapp.WSGIApplication that handles the redirect back from the
881 server during the OAuth 2.0 dance.
882 """
883 return webapp.WSGIApplication([
884 (self.callback_path, self.callback_handler())
885 ])
886
Joe Gregorio432f17e2011-05-22 23:18:00 -0400887
Joe Gregoriof08a4982011-10-07 13:11:16 -0400888class OAuth2DecoratorFromClientSecrets(OAuth2Decorator):
889 """An OAuth2Decorator that builds from a clientsecrets file.
890
891 Uses a clientsecrets file as the source for all the information when
892 constructing an OAuth2Decorator.
893
894 Example:
895
896 decorator = OAuth2DecoratorFromClientSecrets(
897 os.path.join(os.path.dirname(__file__), 'client_secrets.json')
Joe Gregorioc4fc0952011-11-09 12:21:11 -0500898 scope='https://www.googleapis.com/auth/plus')
Joe Gregoriof08a4982011-10-07 13:11:16 -0400899
900
901 class MainHandler(webapp.RequestHandler):
902
903 @decorator.oauth_required
904 def get(self):
905 http = decorator.http()
906 # http is authorized with the user's Credentials and can be used
907 # in API calls
908 """
909
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400910 @util.positional(3)
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400911 def __init__(self, filename, scope, message=None, cache=None):
Joe Gregoriof08a4982011-10-07 13:11:16 -0400912 """Constructor
913
914 Args:
915 filename: string, File name of client secrets.
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500916 scope: string or iterable of strings, scope(s) of the credentials being
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400917 requested.
Joe Gregoriof08a4982011-10-07 13:11:16 -0400918 message: string, A friendly string to display to the user if the
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400919 clientsecrets file is missing or invalid. The message may contain HTML
920 and will be presented on the web interface for any method that uses the
Joe Gregoriof08a4982011-10-07 13:11:16 -0400921 decorator.
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400922 cache: An optional cache service client that implements get() and set()
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400923 methods. See clientsecrets.loadfile() for details.
Joe Gregoriof08a4982011-10-07 13:11:16 -0400924 """
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400925 client_type, client_info = clientsecrets.loadfile(filename, cache=cache)
926 if client_type not in [
927 clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]:
928 raise InvalidClientSecretsError(
929 'OAuth2Decorator doesn\'t support this OAuth 2.0 flow.')
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800930 constructor_kwargs = {
931 'auth_uri': client_info['auth_uri'],
932 'token_uri': client_info['token_uri'],
933 'message': message,
934 }
935 revoke_uri = client_info.get('revoke_uri')
936 if revoke_uri is not None:
937 constructor_kwargs['revoke_uri'] = revoke_uri
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400938 super(OAuth2DecoratorFromClientSecrets, self).__init__(
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800939 client_info['client_id'], client_info['client_secret'],
940 scope, **constructor_kwargs)
Joe Gregoriof08a4982011-10-07 13:11:16 -0400941 if message is not None:
942 self._message = message
943 else:
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800944 self._message = 'Please configure your application for OAuth 2.0.'
Joe Gregoriof08a4982011-10-07 13:11:16 -0400945
946
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400947@util.positional(2)
948def oauth2decorator_from_clientsecrets(filename, scope,
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400949 message=None, cache=None):
Joe Gregoriof08a4982011-10-07 13:11:16 -0400950 """Creates an OAuth2Decorator populated from a clientsecrets file.
951
952 Args:
953 filename: string, File name of client secrets.
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400954 scope: string or list of strings, scope(s) of the credentials being
955 requested.
Joe Gregoriof08a4982011-10-07 13:11:16 -0400956 message: string, A friendly string to display to the user if the
957 clientsecrets file is missing or invalid. The message may contain HTML and
958 will be presented on the web interface for any method that uses the
959 decorator.
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400960 cache: An optional cache service client that implements get() and set()
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400961 methods. See clientsecrets.loadfile() for details.
Joe Gregoriof08a4982011-10-07 13:11:16 -0400962
963 Returns: An OAuth2Decorator
964
965 """
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400966 return OAuth2DecoratorFromClientSecrets(filename, scope,
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800967 message=message, cache=cache)