Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 1 | # 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 Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 17 | Utilities for making it easier to use OAuth 2.0 on Google App Engine. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 18 | """ |
| 19 | |
| 20 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 21 | |
Joe Gregorio | 1daa71b | 2011-09-15 18:12:14 -0400 | [diff] [blame] | 22 | import base64 |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 23 | import httplib2 |
Joe Gregorio | 1daa71b | 2011-09-15 18:12:14 -0400 | [diff] [blame] | 24 | import logging |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 25 | import pickle |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 26 | import time |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 27 | |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 28 | import clientsecrets |
| 29 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 30 | from google.appengine.api import app_identity |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 31 | from google.appengine.api import users |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 32 | from google.appengine.ext import db |
| 33 | from google.appengine.ext import webapp |
| 34 | from google.appengine.ext.webapp.util import login_required |
| 35 | from google.appengine.ext.webapp.util import run_wsgi_app |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 36 | from oauth2client import util |
| 37 | from oauth2client.anyjson import simplejson |
| 38 | from oauth2client.client import AccessTokenRefreshError |
| 39 | from oauth2client.client import AssertionCredentials |
| 40 | from oauth2client.client import Credentials |
| 41 | from oauth2client.client import Flow |
| 42 | from oauth2client.client import OAuth2WebServerFlow |
| 43 | from oauth2client.client import Storage |
Joe Gregorio | a19f3a7 | 2012-07-11 15:35:35 -0400 | [diff] [blame] | 44 | |
| 45 | logger = logging.getLogger(__name__) |
| 46 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 47 | OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns' |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 48 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 49 | |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 50 | class InvalidClientSecretsError(Exception): |
| 51 | """The client_secrets.json file is malformed or missing required fields.""" |
| 52 | pass |
| 53 | |
| 54 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 55 | class AppAssertionCredentials(AssertionCredentials): |
| 56 | """Credentials object for App Engine Assertion Grants |
| 57 | |
| 58 | This object will allow an App Engine application to identify itself to Google |
| 59 | and other OAuth 2.0 servers that can verify assertions. It can be used for |
| 60 | the purpose of accessing data stored under an account assigned to the App |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 61 | Engine application itself. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 62 | |
| 63 | This credential does not require a flow to instantiate because it represents |
| 64 | a two legged flow, and therefore has all of the required information to |
| 65 | generate and refresh its own access tokens. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 66 | """ |
| 67 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 68 | @util.positional(2) |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 69 | def __init__(self, scope, **kwargs): |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 70 | """Constructor for AppAssertionCredentials |
| 71 | |
| 72 | Args: |
Joe Gregorio | fd08e43 | 2012-08-09 14:17:41 -0400 | [diff] [blame] | 73 | scope: string or list of strings, scope(s) of the credentials being |
| 74 | requested. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 75 | """ |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 76 | if type(scope) is list: |
| 77 | scope = ' '.join(scope) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 78 | self.scope = scope |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 79 | |
| 80 | super(AppAssertionCredentials, self).__init__( |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 81 | 'ignored' # assertion_type is ignore in this subclass. |
| 82 | ) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 83 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 84 | @classmethod |
| 85 | def from_json(cls, json): |
| 86 | data = simplejson.loads(json) |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 87 | return AppAssertionCredentials(data['scope']) |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 88 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 89 | def _refresh(self, http_request): |
| 90 | """Refreshes the access_token. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 91 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 92 | Since the underlying App Engine app_identity implementation does its own |
| 93 | caching we can skip all the storage hoops and just to a refresh using the |
| 94 | API. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 95 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 96 | Args: |
| 97 | http_request: callable, a callable that matches the method signature of |
| 98 | httplib2.Http.request, used to make the refresh request. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 99 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 100 | Raises: |
| 101 | AccessTokenRefreshError: When the refresh fails. |
| 102 | """ |
| 103 | try: |
| 104 | (token, _) = app_identity.get_access_token(self.scope) |
| 105 | except app_identity.Error, e: |
| 106 | raise AccessTokenRefreshError(str(e)) |
| 107 | self.access_token = token |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 108 | |
| 109 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 110 | class FlowProperty(db.Property): |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 111 | """App Engine datastore Property for Flow. |
| 112 | |
| 113 | Utility property that allows easy storage and retreival of an |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 114 | oauth2client.Flow""" |
| 115 | |
| 116 | # Tell what the user type is. |
| 117 | data_type = Flow |
| 118 | |
| 119 | # For writing to datastore. |
| 120 | def get_value_for_datastore(self, model_instance): |
| 121 | flow = super(FlowProperty, |
| 122 | self).get_value_for_datastore(model_instance) |
| 123 | return db.Blob(pickle.dumps(flow)) |
| 124 | |
| 125 | # For reading from datastore. |
| 126 | def make_value_from_datastore(self, value): |
| 127 | if value is None: |
| 128 | return None |
| 129 | return pickle.loads(value) |
| 130 | |
| 131 | def validate(self, value): |
| 132 | if value is not None and not isinstance(value, Flow): |
Joe Gregorio | 1daa71b | 2011-09-15 18:12:14 -0400 | [diff] [blame] | 133 | raise db.BadValueError('Property %s must be convertible ' |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 134 | 'to a FlowThreeLegged instance (%s)' % |
| 135 | (self.name, value)) |
| 136 | return super(FlowProperty, self).validate(value) |
| 137 | |
| 138 | def empty(self, value): |
| 139 | return not value |
| 140 | |
| 141 | |
| 142 | class CredentialsProperty(db.Property): |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 143 | """App Engine datastore Property for Credentials. |
| 144 | |
| 145 | Utility property that allows easy storage and retrieval of |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 146 | oath2client.Credentials |
| 147 | """ |
| 148 | |
| 149 | # Tell what the user type is. |
| 150 | data_type = Credentials |
| 151 | |
| 152 | # For writing to datastore. |
| 153 | def get_value_for_datastore(self, model_instance): |
Joe Gregorio | a19f3a7 | 2012-07-11 15:35:35 -0400 | [diff] [blame] | 154 | logger.info("get: Got type " + str(type(model_instance))) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 155 | cred = super(CredentialsProperty, |
| 156 | self).get_value_for_datastore(model_instance) |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 157 | if cred is None: |
| 158 | cred = '' |
| 159 | else: |
| 160 | cred = cred.to_json() |
| 161 | return db.Blob(cred) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 162 | |
| 163 | # For reading from datastore. |
| 164 | def make_value_from_datastore(self, value): |
Joe Gregorio | a19f3a7 | 2012-07-11 15:35:35 -0400 | [diff] [blame] | 165 | logger.info("make: Got type " + str(type(value))) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 166 | if value is None: |
| 167 | return None |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 168 | if len(value) == 0: |
| 169 | return None |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 170 | try: |
| 171 | credentials = Credentials.new_from_json(value) |
| 172 | except ValueError: |
Joe Gregorio | ec55584 | 2011-10-27 11:10:39 -0400 | [diff] [blame] | 173 | credentials = None |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 174 | return credentials |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 175 | |
| 176 | def validate(self, value): |
Joe Gregorio | 1daa71b | 2011-09-15 18:12:14 -0400 | [diff] [blame] | 177 | value = super(CredentialsProperty, self).validate(value) |
Joe Gregorio | a19f3a7 | 2012-07-11 15:35:35 -0400 | [diff] [blame] | 178 | logger.info("validate: Got type " + str(type(value))) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 179 | if value is not None and not isinstance(value, Credentials): |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 180 | raise db.BadValueError('Property %s must be convertible ' |
Joe Gregorio | 1daa71b | 2011-09-15 18:12:14 -0400 | [diff] [blame] | 181 | 'to a Credentials instance (%s)' % |
| 182 | (self.name, value)) |
| 183 | #if value is not None and not isinstance(value, Credentials): |
| 184 | # return None |
| 185 | return value |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 186 | |
| 187 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 188 | class StorageByKeyName(Storage): |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 189 | """Store and retrieve a single credential to and from |
| 190 | the App Engine datastore. |
| 191 | |
| 192 | This Storage helper presumes the Credentials |
| 193 | have been stored as a CredenialsProperty |
| 194 | on a datastore model class, and that entities |
| 195 | are stored by key_name. |
| 196 | """ |
| 197 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 198 | @util.positional(4) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 199 | def __init__(self, model, key_name, property_name, cache=None): |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 200 | """Constructor for Storage. |
| 201 | |
| 202 | Args: |
| 203 | model: db.Model, model class |
| 204 | key_name: string, key name for the entity that has the credentials |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 205 | property_name: string, name of the property that is a CredentialsProperty |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 206 | cache: memcache, a write-through cache to put in front of the datastore |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 207 | """ |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 208 | self._model = model |
| 209 | self._key_name = key_name |
| 210 | self._property_name = property_name |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 211 | self._cache = cache |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 212 | |
Joe Gregorio | d2ee4d8 | 2011-09-15 14:32:45 -0400 | [diff] [blame] | 213 | def locked_get(self): |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 214 | """Retrieve Credential from datastore. |
| 215 | |
| 216 | Returns: |
| 217 | oauth2client.Credentials |
| 218 | """ |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 219 | if self._cache: |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 220 | json = self._cache.get(self._key_name) |
| 221 | if json: |
| 222 | return Credentials.new_from_json(json) |
Joe Gregorio | 9fa077c | 2011-11-18 08:16:52 -0500 | [diff] [blame] | 223 | |
| 224 | credential = None |
| 225 | entity = self._model.get_by_key_name(self._key_name) |
| 226 | if entity is not None: |
| 227 | credential = getattr(entity, self._property_name) |
| 228 | if credential and hasattr(credential, 'set_store'): |
| 229 | credential.set_store(self) |
| 230 | if self._cache: |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 231 | self._cache.set(self._key_name, credential.to_json()) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 232 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 233 | return credential |
| 234 | |
Joe Gregorio | d2ee4d8 | 2011-09-15 14:32:45 -0400 | [diff] [blame] | 235 | def locked_put(self, credentials): |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 236 | """Write a Credentials to the datastore. |
| 237 | |
| 238 | Args: |
| 239 | credentials: Credentials, the credentials to store. |
| 240 | """ |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 241 | entity = self._model.get_or_insert(self._key_name) |
| 242 | setattr(entity, self._property_name, credentials) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 243 | entity.put() |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 244 | if self._cache: |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 245 | self._cache.set(self._key_name, credentials.to_json()) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 246 | |
Joe Gregorio | ec75dc1 | 2012-02-06 13:40:42 -0500 | [diff] [blame] | 247 | def locked_delete(self): |
| 248 | """Delete Credential from datastore.""" |
| 249 | |
| 250 | if self._cache: |
| 251 | self._cache.delete(self._key_name) |
| 252 | |
| 253 | entity = self._model.get_by_key_name(self._key_name) |
| 254 | if entity is not None: |
| 255 | entity.delete() |
| 256 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 257 | |
| 258 | class CredentialsModel(db.Model): |
| 259 | """Storage for OAuth 2.0 Credentials |
| 260 | |
| 261 | Storage of the model is keyed by the user.user_id(). |
| 262 | """ |
| 263 | credentials = CredentialsProperty() |
| 264 | |
| 265 | |
| 266 | class OAuth2Decorator(object): |
| 267 | """Utility for making OAuth 2.0 easier. |
| 268 | |
| 269 | Instantiate and then use with oauth_required or oauth_aware |
| 270 | as decorators on webapp.RequestHandler methods. |
| 271 | |
| 272 | Example: |
| 273 | |
| 274 | decorator = OAuth2Decorator( |
| 275 | client_id='837...ent.com', |
| 276 | client_secret='Qh...wwI', |
Joe Gregorio | c4fc095 | 2011-11-09 12:21:11 -0500 | [diff] [blame] | 277 | scope='https://www.googleapis.com/auth/plus') |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 278 | |
| 279 | |
| 280 | class MainHandler(webapp.RequestHandler): |
| 281 | |
| 282 | @decorator.oauth_required |
| 283 | def get(self): |
| 284 | http = decorator.http() |
| 285 | # http is authorized with the user's Credentials and can be used |
| 286 | # in API calls |
| 287 | |
| 288 | """ |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 289 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 290 | @util.positional(4) |
JacobMoshenko | cb6d891 | 2011-07-08 13:35:15 -0400 | [diff] [blame] | 291 | def __init__(self, client_id, client_secret, scope, |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 292 | auth_uri='https://accounts.google.com/o/oauth2/auth', |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 293 | token_uri='https://accounts.google.com/o/oauth2/token', |
Johan Euphrosine | acf517f | 2012-02-13 21:08:33 +0100 | [diff] [blame] | 294 | user_agent=None, |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 295 | message=None, |
| 296 | callback_path='/oauth2callback', |
| 297 | **kwargs): |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 298 | |
| 299 | """Constructor for OAuth2Decorator |
| 300 | |
| 301 | Args: |
| 302 | client_id: string, client identifier. |
| 303 | client_secret: string client secret. |
Joe Gregorio | f2f8a5a | 2011-10-14 15:11:29 -0400 | [diff] [blame] | 304 | scope: string or list of strings, scope(s) of the credentials being |
| 305 | requested. |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 306 | auth_uri: string, URI for authorization endpoint. For convenience |
| 307 | defaults to Google's endpoints but any OAuth 2.0 provider can be used. |
| 308 | token_uri: string, URI for token endpoint. For convenience |
| 309 | defaults to Google's endpoints but any OAuth 2.0 provider can be used. |
Johan Euphrosine | acf517f | 2012-02-13 21:08:33 +0100 | [diff] [blame] | 310 | user_agent: string, User agent of your application, default to None. |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 311 | message: Message to display if there are problems with the OAuth 2.0 |
| 312 | configuration. The message may contain HTML and will be presented on the |
| 313 | web interface for any method that uses the decorator. |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 314 | callback_path: string, The absolute path to use as the callback URI. Note |
| 315 | that this must match up with the URI given when registering the |
| 316 | application in the APIs Console. |
Joe Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 317 | **kwargs: dict, Keyword arguments are be passed along as kwargs to the |
| 318 | OAuth2WebServerFlow constructor. |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 319 | """ |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 320 | self.flow = None |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 321 | self.credentials = None |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 322 | self._client_id = client_id |
| 323 | self._client_secret = client_secret |
| 324 | self._scope = scope |
| 325 | self._auth_uri = auth_uri |
| 326 | self._token_uri = token_uri |
| 327 | self._user_agent = user_agent |
| 328 | self._kwargs = kwargs |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 329 | self._message = message |
| 330 | self._in_error = False |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 331 | self._callback_path = callback_path |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 332 | |
| 333 | def _display_error_message(self, request_handler): |
| 334 | request_handler.response.out.write('<html><body>') |
| 335 | request_handler.response.out.write(self._message) |
| 336 | request_handler.response.out.write('</body></html>') |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 337 | |
| 338 | def oauth_required(self, method): |
| 339 | """Decorator that starts the OAuth 2.0 dance. |
| 340 | |
| 341 | Starts the OAuth dance for the logged in user if they haven't already |
| 342 | granted access for this application. |
| 343 | |
| 344 | Args: |
| 345 | method: callable, to be decorated method of a webapp.RequestHandler |
| 346 | instance. |
| 347 | """ |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 348 | |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 349 | def check_oauth(request_handler, *args, **kwargs): |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 350 | if self._in_error: |
| 351 | self._display_error_message(request_handler) |
| 352 | return |
| 353 | |
Joe Gregorio | f427c53 | 2011-06-13 09:35:26 -0400 | [diff] [blame] | 354 | user = users.get_current_user() |
| 355 | # Don't use @login_decorator as this could be used in a POST request. |
| 356 | if not user: |
| 357 | request_handler.redirect(users.create_login_url( |
| 358 | request_handler.request.uri)) |
| 359 | return |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 360 | |
| 361 | self._create_flow(request_handler) |
| 362 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 363 | # Store the request URI in 'state' so we can use it later |
| 364 | self.flow.params['state'] = request_handler.request.url |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 365 | self.credentials = StorageByKeyName( |
| 366 | CredentialsModel, user.user_id(), 'credentials').get() |
| 367 | |
| 368 | if not self.has_credentials(): |
| 369 | return request_handler.redirect(self.authorize_url()) |
| 370 | try: |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 371 | method(request_handler, *args, **kwargs) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 372 | except AccessTokenRefreshError: |
| 373 | return request_handler.redirect(self.authorize_url()) |
| 374 | |
| 375 | return check_oauth |
| 376 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 377 | def _create_flow(self, request_handler): |
| 378 | """Create the Flow object. |
| 379 | |
| 380 | The Flow is calculated lazily since we don't know where this app is |
| 381 | running until it receives a request, at which point redirect_uri can be |
| 382 | calculated and then the Flow object can be constructed. |
| 383 | |
| 384 | Args: |
| 385 | request_handler: webapp.RequestHandler, the request handler. |
| 386 | """ |
| 387 | if self.flow is None: |
| 388 | redirect_uri = request_handler.request.relative_url( |
| 389 | self._callback_path) # Usually /oauth2callback |
| 390 | self.flow = OAuth2WebServerFlow(self._client_id, self._client_secret, |
| 391 | self._scope, redirect_uri=redirect_uri, |
| 392 | user_agent=self._user_agent, |
| 393 | auth_uri=self._auth_uri, |
| 394 | token_uri=self._token_uri, **self._kwargs) |
| 395 | |
| 396 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 397 | def oauth_aware(self, method): |
| 398 | """Decorator that sets up for OAuth 2.0 dance, but doesn't do it. |
| 399 | |
| 400 | Does all the setup for the OAuth dance, but doesn't initiate it. |
| 401 | This decorator is useful if you want to create a page that knows |
| 402 | whether or not the user has granted access to this application. |
| 403 | From within a method decorated with @oauth_aware the has_credentials() |
| 404 | and authorize_url() methods can be called. |
| 405 | |
| 406 | Args: |
| 407 | method: callable, to be decorated method of a webapp.RequestHandler |
| 408 | instance. |
| 409 | """ |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 410 | |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 411 | def setup_oauth(request_handler, *args, **kwargs): |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 412 | if self._in_error: |
| 413 | self._display_error_message(request_handler) |
| 414 | return |
| 415 | |
Joe Gregorio | f427c53 | 2011-06-13 09:35:26 -0400 | [diff] [blame] | 416 | user = users.get_current_user() |
| 417 | # Don't use @login_decorator as this could be used in a POST request. |
| 418 | if not user: |
| 419 | request_handler.redirect(users.create_login_url( |
| 420 | request_handler.request.uri)) |
| 421 | return |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 422 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 423 | self._create_flow(request_handler) |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 424 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 425 | self.flow.params['state'] = request_handler.request.url |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 426 | self.credentials = StorageByKeyName( |
| 427 | CredentialsModel, user.user_id(), 'credentials').get() |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 428 | method(request_handler, *args, **kwargs) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 429 | return setup_oauth |
| 430 | |
| 431 | def has_credentials(self): |
| 432 | """True if for the logged in user there are valid access Credentials. |
| 433 | |
| 434 | Must only be called from with a webapp.RequestHandler subclassed method |
| 435 | that had been decorated with either @oauth_required or @oauth_aware. |
| 436 | """ |
| 437 | return self.credentials is not None and not self.credentials.invalid |
| 438 | |
| 439 | def authorize_url(self): |
| 440 | """Returns the URL to start the OAuth dance. |
| 441 | |
| 442 | Must only be called from with a webapp.RequestHandler subclassed method |
| 443 | that had been decorated with either @oauth_required or @oauth_aware. |
| 444 | """ |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 445 | url = self.flow.step1_get_authorize_url() |
Joe Gregorio | 853bcf3 | 2012-03-02 15:30:23 -0500 | [diff] [blame] | 446 | return str(url) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 447 | |
| 448 | def http(self): |
| 449 | """Returns an authorized http instance. |
| 450 | |
| 451 | Must only be called from within an @oauth_required decorated method, or |
| 452 | from within an @oauth_aware decorated method where has_credentials() |
| 453 | returns True. |
| 454 | """ |
| 455 | return self.credentials.authorize(httplib2.Http()) |
| 456 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 457 | @property |
| 458 | def callback_path(self): |
| 459 | """The absolute path where the callback will occur. |
| 460 | |
| 461 | Note this is the absolute path, not the absolute URI, that will be |
| 462 | calculated by the decorator at runtime. See callback_handler() for how this |
| 463 | should be used. |
| 464 | |
| 465 | Returns: |
| 466 | The callback path as a string. |
| 467 | """ |
| 468 | return self._callback_path |
| 469 | |
| 470 | |
| 471 | def callback_handler(self): |
| 472 | """RequestHandler for the OAuth 2.0 redirect callback. |
| 473 | |
| 474 | Usage: |
| 475 | app = webapp.WSGIApplication([ |
| 476 | ('/index', MyIndexHandler), |
| 477 | ..., |
| 478 | (decorator.callback_path, decorator.callback_handler()) |
| 479 | ]) |
| 480 | |
| 481 | Returns: |
| 482 | A webapp.RequestHandler that handles the redirect back from the |
| 483 | server during the OAuth 2.0 dance. |
| 484 | """ |
| 485 | decorator = self |
| 486 | |
| 487 | class OAuth2Handler(webapp.RequestHandler): |
| 488 | """Handler for the redirect_uri of the OAuth 2.0 dance.""" |
| 489 | |
| 490 | @login_required |
| 491 | def get(self): |
| 492 | error = self.request.get('error') |
| 493 | if error: |
| 494 | errormsg = self.request.get('error_description', error) |
| 495 | self.response.out.write( |
| 496 | 'The authorization request failed: %s' % errormsg) |
| 497 | else: |
| 498 | user = users.get_current_user() |
| 499 | decorator._create_flow(self) |
| 500 | credentials = decorator.flow.step2_exchange(self.request.params) |
| 501 | StorageByKeyName( |
| 502 | CredentialsModel, user.user_id(), 'credentials').put(credentials) |
| 503 | self.redirect(str(self.request.get('state'))) |
| 504 | |
| 505 | return OAuth2Handler |
| 506 | |
| 507 | def callback_application(self): |
| 508 | """WSGI application for handling the OAuth 2.0 redirect callback. |
| 509 | |
| 510 | If you need finer grained control use `callback_handler` which returns just |
| 511 | the webapp.RequestHandler. |
| 512 | |
| 513 | Returns: |
| 514 | A webapp.WSGIApplication that handles the redirect back from the |
| 515 | server during the OAuth 2.0 dance. |
| 516 | """ |
| 517 | return webapp.WSGIApplication([ |
| 518 | (self.callback_path, self.callback_handler()) |
| 519 | ]) |
| 520 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 521 | |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 522 | class OAuth2DecoratorFromClientSecrets(OAuth2Decorator): |
| 523 | """An OAuth2Decorator that builds from a clientsecrets file. |
| 524 | |
| 525 | Uses a clientsecrets file as the source for all the information when |
| 526 | constructing an OAuth2Decorator. |
| 527 | |
| 528 | Example: |
| 529 | |
| 530 | decorator = OAuth2DecoratorFromClientSecrets( |
| 531 | os.path.join(os.path.dirname(__file__), 'client_secrets.json') |
Joe Gregorio | c4fc095 | 2011-11-09 12:21:11 -0500 | [diff] [blame] | 532 | scope='https://www.googleapis.com/auth/plus') |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 533 | |
| 534 | |
| 535 | class MainHandler(webapp.RequestHandler): |
| 536 | |
| 537 | @decorator.oauth_required |
| 538 | def get(self): |
| 539 | http = decorator.http() |
| 540 | # http is authorized with the user's Credentials and can be used |
| 541 | # in API calls |
| 542 | """ |
| 543 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 544 | @util.positional(3) |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 545 | def __init__(self, filename, scope, message=None, cache=None): |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 546 | """Constructor |
| 547 | |
| 548 | Args: |
| 549 | filename: string, File name of client secrets. |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 550 | scope: string or list of strings, scope(s) of the credentials being |
| 551 | requested. |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 552 | message: string, A friendly string to display to the user if the |
| 553 | clientsecrets file is missing or invalid. The message may contain HTML and |
| 554 | will be presented on the web interface for any method that uses the |
| 555 | decorator. |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 556 | cache: An optional cache service client that implements get() and set() |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 557 | methods. See clientsecrets.loadfile() for details. |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 558 | """ |
| 559 | try: |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 560 | client_type, client_info = clientsecrets.loadfile(filename, cache=cache) |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 561 | if client_type not in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: |
| 562 | raise InvalidClientSecretsError('OAuth2Decorator doesn\'t support this OAuth 2.0 flow.') |
| 563 | super(OAuth2DecoratorFromClientSecrets, |
| 564 | self).__init__( |
| 565 | client_info['client_id'], |
| 566 | client_info['client_secret'], |
| 567 | scope, |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 568 | auth_uri=client_info['auth_uri'], |
| 569 | token_uri=client_info['token_uri'], |
| 570 | message=message) |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 571 | except clientsecrets.InvalidClientSecretsError: |
| 572 | self._in_error = True |
| 573 | if message is not None: |
| 574 | self._message = message |
| 575 | else: |
| 576 | self._message = "Please configure your application for OAuth 2.0" |
| 577 | |
| 578 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 579 | @util.positional(2) |
| 580 | def oauth2decorator_from_clientsecrets(filename, scope, |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 581 | message=None, cache=None): |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 582 | """Creates an OAuth2Decorator populated from a clientsecrets file. |
| 583 | |
| 584 | Args: |
| 585 | filename: string, File name of client secrets. |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 586 | scope: string or list of strings, scope(s) of the credentials being |
| 587 | requested. |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 588 | message: string, A friendly string to display to the user if the |
| 589 | clientsecrets file is missing or invalid. The message may contain HTML and |
| 590 | will be presented on the web interface for any method that uses the |
| 591 | decorator. |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 592 | cache: An optional cache service client that implements get() and set() |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 593 | methods. See clientsecrets.loadfile() for details. |
Joe Gregorio | f08a498 | 2011-10-07 13:11:16 -0400 | [diff] [blame] | 594 | |
| 595 | Returns: An OAuth2Decorator |
| 596 | |
| 597 | """ |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 598 | return OAuth2DecoratorFromClientSecrets(filename, scope, |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 599 | message=message, cache=cache) |