Joe Gregorio | 20a5aa9 | 2011-04-01 17:44:25 -0400 | [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. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 14 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 15 | """An OAuth 2.0 client. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 16 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 17 | Tools for interacting with OAuth 2.0 protected resources. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 18 | """ |
| 19 | |
| 20 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 21 | |
| 22 | import copy |
| 23 | import datetime |
| 24 | import httplib2 |
| 25 | import logging |
| 26 | import urllib |
| 27 | import urlparse |
| 28 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 29 | try: # pragma: no cover |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 30 | import simplejson |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 31 | except ImportError: # pragma: no cover |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 32 | try: |
| 33 | # Try to import from django, should work on App Engine |
| 34 | from django.utils import simplejson |
| 35 | except ImportError: |
| 36 | # Should work for Python2.6 and higher. |
| 37 | import json as simplejson |
| 38 | |
| 39 | try: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 40 | from urlparse import parse_qsl |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 41 | except ImportError: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 42 | from cgi import parse_qsl |
| 43 | |
| 44 | logger = logging.getLogger(__name__) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 45 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 46 | # Expiry is stored in RFC3339 UTC format |
Joe Gregorio | 1daa71b | 2011-09-15 18:12:14 -0400 | [diff] [blame] | 47 | EXPIRY_FORMAT = "%Y-%m-%dT%H:%M:%SZ" |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 48 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 49 | |
| 50 | class Error(Exception): |
| 51 | """Base error for this module.""" |
| 52 | pass |
| 53 | |
| 54 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 55 | class FlowExchangeError(Error): |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 56 | """Error trying to exchange an authorization grant for an access token.""" |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 57 | pass |
| 58 | |
| 59 | |
| 60 | class AccessTokenRefreshError(Error): |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 61 | """Error trying to refresh an expired access token.""" |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 62 | pass |
| 63 | |
| 64 | |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 65 | class AccessTokenCredentialsError(Error): |
| 66 | """Having only the access_token means no refresh is possible.""" |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 67 | pass |
| 68 | |
| 69 | |
| 70 | def _abstract(): |
| 71 | raise NotImplementedError('You need to override this function') |
| 72 | |
| 73 | |
| 74 | class Credentials(object): |
| 75 | """Base class for all Credentials objects. |
| 76 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 77 | Subclasses must define an authorize() method that applies the credentials to |
| 78 | an HTTP transport. |
| 79 | |
| 80 | Subclasses must also specify a classmethod named 'from_json' that takes a JSON |
| 81 | string as input and returns an instaniated Crentials object. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 82 | """ |
| 83 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 84 | NON_SERIALIZED_MEMBERS = ['store'] |
| 85 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 86 | def authorize(self, http): |
| 87 | """Take an httplib2.Http instance (or equivalent) and |
| 88 | authorizes it for the set of credentials, usually by |
| 89 | replacing http.request() with a method that adds in |
| 90 | the appropriate headers and then delegates to the original |
| 91 | Http.request() method. |
| 92 | """ |
| 93 | _abstract() |
| 94 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 95 | def _to_json(self, strip): |
| 96 | """Utility function for creating a JSON representation of an instance of Credentials. |
| 97 | |
| 98 | Args: |
| 99 | strip: array, An array of names of members to not include in the JSON. |
| 100 | |
| 101 | Returns: |
| 102 | string, a JSON representation of this instance, suitable to pass to |
| 103 | from_json(). |
| 104 | """ |
| 105 | t = type(self) |
| 106 | d = copy.copy(self.__dict__) |
| 107 | for member in strip: |
| 108 | del d[member] |
| 109 | if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime): |
| 110 | d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT) |
| 111 | # Add in information we will need later to reconsistitue this instance. |
| 112 | d['_class'] = t.__name__ |
| 113 | d['_module'] = t.__module__ |
| 114 | return simplejson.dumps(d) |
| 115 | |
| 116 | def to_json(self): |
| 117 | """Creating a JSON representation of an instance of Credentials. |
| 118 | |
| 119 | Returns: |
| 120 | string, a JSON representation of this instance, suitable to pass to |
| 121 | from_json(). |
| 122 | """ |
| 123 | return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) |
| 124 | |
| 125 | @classmethod |
| 126 | def new_from_json(cls, s): |
| 127 | """Utility class method to instantiate a Credentials subclass from a JSON |
| 128 | representation produced by to_json(). |
| 129 | |
| 130 | Args: |
| 131 | s: string, JSON from to_json(). |
| 132 | |
| 133 | Returns: |
| 134 | An instance of the subclass of Credentials that was serialized with |
| 135 | to_json(). |
| 136 | """ |
| 137 | data = simplejson.loads(s) |
| 138 | # Find and call the right classmethod from_json() to restore the object. |
| 139 | module = data['_module'] |
| 140 | m = __import__(module) |
| 141 | for sub_module in module.split('.')[1:]: |
| 142 | m = getattr(m, sub_module) |
| 143 | kls = getattr(m, data['_class']) |
| 144 | from_json = getattr(kls, 'from_json') |
| 145 | return from_json(s) |
| 146 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 147 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 148 | class Flow(object): |
| 149 | """Base class for all Flow objects.""" |
| 150 | pass |
| 151 | |
| 152 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 153 | class Storage(object): |
| 154 | """Base class for all Storage objects. |
| 155 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 156 | Store and retrieve a single credential. This class supports locking |
| 157 | such that multiple processes and threads can operate on a single |
| 158 | store. |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 159 | """ |
| 160 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 161 | def acquire_lock(self): |
| 162 | """Acquires any lock necessary to access this Storage. |
| 163 | |
| 164 | This lock is not reentrant.""" |
| 165 | pass |
| 166 | |
| 167 | def release_lock(self): |
| 168 | """Release the Storage lock. |
| 169 | |
| 170 | Trying to release a lock that isn't held will result in a |
| 171 | RuntimeError. |
| 172 | """ |
| 173 | pass |
| 174 | |
| 175 | def locked_get(self): |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 176 | """Retrieve credential. |
| 177 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 178 | The Storage lock must be held when this is called. |
| 179 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 180 | Returns: |
Joe Gregorio | 06d852b | 2011-03-25 15:03:10 -0400 | [diff] [blame] | 181 | oauth2client.client.Credentials |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 182 | """ |
| 183 | _abstract() |
| 184 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 185 | def locked_put(self, credentials): |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 186 | """Write a credential. |
| 187 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 188 | The Storage lock must be held when this is called. |
| 189 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 190 | Args: |
| 191 | credentials: Credentials, the credentials to store. |
| 192 | """ |
| 193 | _abstract() |
| 194 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 195 | def get(self): |
| 196 | """Retrieve credential. |
| 197 | |
| 198 | The Storage lock must *not* be held when this is called. |
| 199 | |
| 200 | Returns: |
| 201 | oauth2client.client.Credentials |
| 202 | """ |
| 203 | self.acquire_lock() |
| 204 | try: |
| 205 | return self.locked_get() |
| 206 | finally: |
| 207 | self.release_lock() |
| 208 | |
| 209 | def put(self, credentials): |
| 210 | """Write a credential. |
| 211 | |
| 212 | The Storage lock must be held when this is called. |
| 213 | |
| 214 | Args: |
| 215 | credentials: Credentials, the credentials to store. |
| 216 | """ |
| 217 | self.acquire_lock() |
| 218 | try: |
| 219 | self.locked_put(credentials) |
| 220 | finally: |
| 221 | self.release_lock() |
| 222 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 223 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 224 | class OAuth2Credentials(Credentials): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 225 | """Credentials object for OAuth 2.0. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 226 | |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 227 | Credentials can be applied to an httplib2.Http object using the authorize() |
| 228 | method, which then signs each request from that object with the OAuth 2.0 |
| 229 | access token. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 230 | |
| 231 | OAuth2Credentials objects may be safely pickled and unpickled. |
| 232 | """ |
| 233 | |
| 234 | def __init__(self, access_token, client_id, client_secret, refresh_token, |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 235 | token_expiry, token_uri, user_agent): |
| 236 | """Create an instance of OAuth2Credentials. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 237 | |
| 238 | This constructor is not usually called by the user, instead |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 239 | OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 240 | |
| 241 | Args: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 242 | access_token: string, access token. |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 243 | client_id: string, client identifier. |
| 244 | client_secret: string, client secret. |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 245 | refresh_token: string, refresh token. |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 246 | token_expiry: datetime, when the access_token expires. |
| 247 | token_uri: string, URI of token endpoint. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 248 | user_agent: string, The HTTP User-Agent to provide for this application. |
| 249 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 250 | Notes: |
| 251 | store: callable, a callable that when passed a Credential |
| 252 | will store the credential back to where it came from. |
| 253 | This is needed to store the latest access_token if it |
| 254 | has expired and been refreshed. |
| 255 | """ |
| 256 | self.access_token = access_token |
| 257 | self.client_id = client_id |
| 258 | self.client_secret = client_secret |
| 259 | self.refresh_token = refresh_token |
| 260 | self.store = None |
| 261 | self.token_expiry = token_expiry |
| 262 | self.token_uri = token_uri |
| 263 | self.user_agent = user_agent |
| 264 | |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 265 | # True if the credentials have been revoked or expired and can't be |
| 266 | # refreshed. |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 267 | self.invalid = False |
Joe Gregorio | 9ce4b62 | 2011-02-17 15:32:11 -0500 | [diff] [blame] | 268 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 269 | def to_json(self): |
| 270 | return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) |
| 271 | |
| 272 | @classmethod |
| 273 | def from_json(cls, s): |
| 274 | """Instantiate a Credentials object from a JSON description of it. The JSON |
| 275 | should have been produced by calling .to_json() on the object. |
| 276 | |
| 277 | Args: |
| 278 | data: dict, A deserialized JSON object. |
| 279 | |
| 280 | Returns: |
| 281 | An instance of a Credentials subclass. |
| 282 | """ |
| 283 | data = simplejson.loads(s) |
| 284 | if 'token_expiry' in data and not isinstance(data['token_expiry'], |
| 285 | datetime.datetime): |
Joe Gregorio | 1daa71b | 2011-09-15 18:12:14 -0400 | [diff] [blame] | 286 | try: |
| 287 | data['token_expiry'] = datetime.datetime.strptime( |
| 288 | data['token_expiry'], EXPIRY_FORMAT) |
| 289 | except: |
| 290 | data['token_expiry'] = None |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 291 | retval = OAuth2Credentials( |
| 292 | data['access_token'], |
| 293 | data['client_id'], |
| 294 | data['client_secret'], |
| 295 | data['refresh_token'], |
| 296 | data['token_expiry'], |
| 297 | data['token_uri'], |
| 298 | data['user_agent']) |
| 299 | retval.invalid = data['invalid'] |
| 300 | return retval |
| 301 | |
Joe Gregorio | 9ce4b62 | 2011-02-17 15:32:11 -0500 | [diff] [blame] | 302 | @property |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 303 | def access_token_expired(self): |
| 304 | """True if the credential is expired or invalid. |
| 305 | |
| 306 | If the token_expiry isn't set, we assume the token doesn't expire. |
| 307 | """ |
| 308 | if self.invalid: |
| 309 | return True |
| 310 | |
| 311 | if not self.token_expiry: |
| 312 | return False |
| 313 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 314 | now = datetime.datetime.utcnow() |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 315 | if now >= self.token_expiry: |
| 316 | logger.info('access_token is expired. Now: %s, token_expiry: %s', |
| 317 | now, self.token_expiry) |
| 318 | return True |
| 319 | return False |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 320 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 321 | def set_store(self, store): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 322 | """Set the Storage for the credential. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 323 | |
| 324 | Args: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 325 | store: Storage, an implementation of Stroage object. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 326 | This is needed to store the latest access_token if it |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 327 | has expired and been refreshed. This implementation uses |
| 328 | locking to check for updates before updating the |
| 329 | access_token. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 330 | """ |
| 331 | self.store = store |
| 332 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 333 | def _updateFromCredential(self, other): |
| 334 | """Update this Credential from another instance.""" |
| 335 | self.__dict__.update(other.__getstate__()) |
| 336 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 337 | def __getstate__(self): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 338 | """Trim the state down to something that can be pickled.""" |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 339 | d = copy.copy(self.__dict__) |
| 340 | del d['store'] |
| 341 | return d |
| 342 | |
| 343 | def __setstate__(self, state): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 344 | """Reconstitute the state of the object from being pickled.""" |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 345 | self.__dict__.update(state) |
| 346 | self.store = None |
| 347 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 348 | def _generate_refresh_request_body(self): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 349 | """Generate the body that will be used in the refresh request.""" |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 350 | body = urllib.urlencode({ |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 351 | 'grant_type': 'refresh_token', |
| 352 | 'client_id': self.client_id, |
| 353 | 'client_secret': self.client_secret, |
| 354 | 'refresh_token': self.refresh_token, |
| 355 | }) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 356 | return body |
| 357 | |
| 358 | def _generate_refresh_request_headers(self): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 359 | """Generate the headers that will be used in the refresh request.""" |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 360 | headers = { |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 361 | 'content-type': 'application/x-www-form-urlencoded', |
| 362 | } |
JacobMoshenko | cb6d891 | 2011-07-08 13:35:15 -0400 | [diff] [blame] | 363 | |
| 364 | if self.user_agent is not None: |
| 365 | headers['user-agent'] = self.user_agent |
| 366 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 367 | return headers |
| 368 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 369 | def _refresh(self, http_request): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 370 | """Refreshes the access_token. |
| 371 | |
| 372 | This method first checks by reading the Storage object if available. |
| 373 | If a refresh is still needed, it holds the Storage lock until the |
| 374 | refresh is completed. |
| 375 | """ |
| 376 | if not self.store: |
| 377 | self._do_refresh_request(http_request) |
| 378 | else: |
| 379 | self.store.acquire_lock() |
| 380 | try: |
| 381 | new_cred = self.store.locked_get() |
| 382 | if (new_cred and not new_cred.invalid and |
| 383 | new_cred.access_token != self.access_token): |
| 384 | logger.info('Updated access_token read from Storage') |
| 385 | self._updateFromCredential(new_cred) |
| 386 | else: |
| 387 | self._do_refresh_request(http_request) |
| 388 | finally: |
| 389 | self.store.release_lock() |
| 390 | |
| 391 | def _do_refresh_request(self, http_request): |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 392 | """Refresh the access_token using the refresh_token. |
| 393 | |
| 394 | Args: |
| 395 | http: An instance of httplib2.Http.request |
| 396 | or something that acts like it. |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 397 | |
| 398 | Raises: |
| 399 | AccessTokenRefreshError: When the refresh fails. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 400 | """ |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 401 | body = self._generate_refresh_request_body() |
| 402 | headers = self._generate_refresh_request_headers() |
| 403 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 404 | logger.info('Refresing access_token') |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 405 | resp, content = http_request( |
| 406 | self.token_uri, method='POST', body=body, headers=headers) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 407 | if resp.status == 200: |
| 408 | # TODO(jcgregorio) Raise an error if loads fails? |
| 409 | d = simplejson.loads(content) |
| 410 | self.access_token = d['access_token'] |
| 411 | self.refresh_token = d.get('refresh_token', self.refresh_token) |
| 412 | if 'expires_in' in d: |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 413 | self.token_expiry = datetime.timedelta( |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 414 | seconds=int(d['expires_in'])) + datetime.datetime.utcnow() |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 415 | else: |
| 416 | self.token_expiry = None |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 417 | if self.store: |
| 418 | self.store.locked_put(self) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 419 | else: |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 420 | # An {'error':...} response body means the token is expired or revoked, |
| 421 | # so we flag the credentials as such. |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 422 | logger.error('Failed to retrieve access token: %s' % content) |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 423 | error_msg = 'Invalid response %s.' % resp['status'] |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 424 | try: |
| 425 | d = simplejson.loads(content) |
| 426 | if 'error' in d: |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 427 | error_msg = d['error'] |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 428 | self.invalid = True |
| 429 | if self.store: |
| 430 | self.store.locked_put(self) |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 431 | except: |
| 432 | pass |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 433 | raise AccessTokenRefreshError(error_msg) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 434 | |
| 435 | def authorize(self, http): |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 436 | """Authorize an httplib2.Http instance with these credentials. |
| 437 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 438 | Args: |
| 439 | http: An instance of httplib2.Http |
| 440 | or something that acts like it. |
| 441 | |
| 442 | Returns: |
| 443 | A modified instance of http that was passed in. |
| 444 | |
| 445 | Example: |
| 446 | |
| 447 | h = httplib2.Http() |
| 448 | h = credentials.authorize(h) |
| 449 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 450 | You can't create a new OAuth subclass of httplib2.Authenication |
| 451 | because it never gets passed the absolute URI, which is needed for |
| 452 | signing. So instead we have to overload 'request' with a closure |
| 453 | that adds in the Authorization header and then calls the original |
| 454 | version of 'request()'. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 455 | """ |
| 456 | request_orig = http.request |
| 457 | |
| 458 | # The closure that will replace 'httplib2.Http.request'. |
| 459 | def new_request(uri, method='GET', body=None, headers=None, |
| 460 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 461 | connection_type=None): |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 462 | if not self.access_token: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 463 | logger.info('Attempting refresh to obtain initial access_token') |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 464 | self._refresh(request_orig) |
| 465 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 466 | # Modify the request headers to add the appropriate |
| 467 | # Authorization header. |
| 468 | if headers is None: |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 469 | headers = {} |
Joe Gregorio | 49e94d8 | 2011-01-28 16:36:13 -0500 | [diff] [blame] | 470 | headers['authorization'] = 'OAuth ' + self.access_token |
JacobMoshenko | cb6d891 | 2011-07-08 13:35:15 -0400 | [diff] [blame] | 471 | |
| 472 | if self.user_agent is not None: |
| 473 | if 'user-agent' in headers: |
| 474 | headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] |
| 475 | else: |
| 476 | headers['user-agent'] = self.user_agent |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 477 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 478 | resp, content = request_orig(uri, method, body, headers, |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 479 | redirections, connection_type) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 480 | |
Joe Gregorio | fd19cd3 | 2011-01-20 11:37:29 -0500 | [diff] [blame] | 481 | if resp.status == 401: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 482 | logger.info('Refreshing due to a 401') |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 483 | self._refresh(request_orig) |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 484 | headers['authorization'] = 'OAuth ' + self.access_token |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 485 | return request_orig(uri, method, body, headers, |
| 486 | redirections, connection_type) |
| 487 | else: |
| 488 | return (resp, content) |
| 489 | |
| 490 | http.request = new_request |
| 491 | return http |
| 492 | |
| 493 | |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 494 | class AccessTokenCredentials(OAuth2Credentials): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 495 | """Credentials object for OAuth 2.0. |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 496 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 497 | Credentials can be applied to an httplib2.Http object using the |
| 498 | authorize() method, which then signs each request from that object |
| 499 | with the OAuth 2.0 access token. This set of credentials is for the |
| 500 | use case where you have acquired an OAuth 2.0 access_token from |
| 501 | another place such as a JavaScript client or another web |
| 502 | application, and wish to use it from Python. Because only the |
| 503 | access_token is present it can not be refreshed and will in time |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 504 | expire. |
| 505 | |
Joe Gregorio | 9ce4b62 | 2011-02-17 15:32:11 -0500 | [diff] [blame] | 506 | AccessTokenCredentials objects may be safely pickled and unpickled. |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 507 | |
| 508 | Usage: |
| 509 | credentials = AccessTokenCredentials('<an access token>', |
| 510 | 'my-user-agent/1.0') |
| 511 | http = httplib2.Http() |
| 512 | http = credentials.authorize(http) |
| 513 | |
| 514 | Exceptions: |
| 515 | AccessTokenCredentialsExpired: raised when the access_token expires or is |
| 516 | revoked. |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 517 | """ |
| 518 | |
| 519 | def __init__(self, access_token, user_agent): |
| 520 | """Create an instance of OAuth2Credentials |
| 521 | |
| 522 | This is one of the few types if Credentials that you should contrust, |
| 523 | Credentials objects are usually instantiated by a Flow. |
| 524 | |
| 525 | Args: |
ade@google.com | 93a7f7c | 2011-02-23 16:00:37 +0000 | [diff] [blame] | 526 | access_token: string, access token. |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 527 | user_agent: string, The HTTP User-Agent to provide for this application. |
| 528 | |
| 529 | Notes: |
| 530 | store: callable, a callable that when passed a Credential |
| 531 | will store the credential back to where it came from. |
| 532 | """ |
| 533 | super(AccessTokenCredentials, self).__init__( |
| 534 | access_token, |
| 535 | None, |
| 536 | None, |
| 537 | None, |
| 538 | None, |
| 539 | None, |
| 540 | user_agent) |
| 541 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 542 | |
| 543 | @classmethod |
| 544 | def from_json(cls, s): |
| 545 | data = simplejson.loads(s) |
| 546 | retval = AccessTokenCredentials( |
| 547 | data['access_token'], |
| 548 | data['user_agent']) |
| 549 | return retval |
| 550 | |
Joe Gregorio | 3b79fa8 | 2011-02-17 11:47:17 -0500 | [diff] [blame] | 551 | def _refresh(self, http_request): |
| 552 | raise AccessTokenCredentialsError( |
| 553 | "The access_token is expired or invalid and can't be refreshed.") |
| 554 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 555 | |
| 556 | class AssertionCredentials(OAuth2Credentials): |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 557 | """Abstract Credentials object used for OAuth 2.0 assertion grants. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 558 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 559 | This credential does not require a flow to instantiate because it |
| 560 | represents a two legged flow, and therefore has all of the required |
| 561 | information to generate and refresh its own access tokens. It must |
| 562 | be subclassed to generate the appropriate assertion string. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 563 | |
| 564 | AssertionCredentials objects may be safely pickled and unpickled. |
| 565 | """ |
| 566 | |
| 567 | def __init__(self, assertion_type, user_agent, |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 568 | token_uri='https://accounts.google.com/o/oauth2/token', |
| 569 | **unused_kwargs): |
| 570 | """Constructor for AssertionFlowCredentials. |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 571 | |
| 572 | Args: |
| 573 | assertion_type: string, assertion type that will be declared to the auth |
| 574 | server |
| 575 | user_agent: string, The HTTP User-Agent to provide for this application. |
| 576 | token_uri: string, URI for token endpoint. For convenience |
| 577 | defaults to Google's endpoints but any OAuth 2.0 provider can be used. |
| 578 | """ |
| 579 | super(AssertionCredentials, self).__init__( |
| 580 | None, |
| 581 | None, |
| 582 | None, |
| 583 | None, |
| 584 | None, |
| 585 | token_uri, |
| 586 | user_agent) |
| 587 | self.assertion_type = assertion_type |
| 588 | |
| 589 | def _generate_refresh_request_body(self): |
| 590 | assertion = self._generate_assertion() |
| 591 | |
| 592 | body = urllib.urlencode({ |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 593 | 'assertion_type': self.assertion_type, |
| 594 | 'assertion': assertion, |
| 595 | 'grant_type': 'assertion', |
| 596 | }) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 597 | |
| 598 | return body |
| 599 | |
| 600 | def _generate_assertion(self): |
| 601 | """Generate the assertion string that will be used in the access token |
| 602 | request. |
| 603 | """ |
| 604 | _abstract() |
| 605 | |
| 606 | |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 607 | class OAuth2WebServerFlow(Flow): |
| 608 | """Does the Web Server Flow for OAuth 2.0. |
| 609 | |
| 610 | OAuth2Credentials objects may be safely pickled and unpickled. |
| 611 | """ |
| 612 | |
| 613 | def __init__(self, client_id, client_secret, scope, user_agent, |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 614 | auth_uri='https://accounts.google.com/o/oauth2/auth', |
| 615 | token_uri='https://accounts.google.com/o/oauth2/token', |
| 616 | **kwargs): |
| 617 | """Constructor for OAuth2WebServerFlow. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 618 | |
| 619 | Args: |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 620 | client_id: string, client identifier. |
| 621 | client_secret: string client secret. |
| 622 | scope: string, scope of the credentials being requested. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 623 | user_agent: string, HTTP User-Agent to provide for this application. |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 624 | auth_uri: string, URI for authorization endpoint. For convenience |
| 625 | defaults to Google's endpoints but any OAuth 2.0 provider can be used. |
| 626 | token_uri: string, URI for token endpoint. For convenience |
| 627 | defaults to Google's endpoints but any OAuth 2.0 provider can be used. |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 628 | **kwargs: dict, The keyword arguments are all optional and required |
| 629 | parameters for the OAuth calls. |
| 630 | """ |
| 631 | self.client_id = client_id |
| 632 | self.client_secret = client_secret |
| 633 | self.scope = scope |
| 634 | self.user_agent = user_agent |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 635 | self.auth_uri = auth_uri |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 636 | self.token_uri = token_uri |
| 637 | self.params = kwargs |
| 638 | self.redirect_uri = None |
| 639 | |
| 640 | def step1_get_authorize_url(self, redirect_uri='oob'): |
| 641 | """Returns a URI to redirect to the provider. |
| 642 | |
| 643 | Args: |
| 644 | redirect_uri: string, Either the string 'oob' for a non-web-based |
| 645 | application, or a URI that handles the callback from |
| 646 | the authorization server. |
| 647 | |
| 648 | If redirect_uri is 'oob' then pass in the |
| 649 | generated verification code to step2_exchange, |
| 650 | otherwise pass in the query parameters received |
| 651 | at the callback uri to step2_exchange. |
| 652 | """ |
| 653 | |
| 654 | self.redirect_uri = redirect_uri |
| 655 | query = { |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 656 | 'response_type': 'code', |
| 657 | 'client_id': self.client_id, |
| 658 | 'redirect_uri': redirect_uri, |
| 659 | 'scope': self.scope, |
| 660 | } |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 661 | query.update(self.params) |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 662 | parts = list(urlparse.urlparse(self.auth_uri)) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 663 | query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part |
| 664 | parts[4] = urllib.urlencode(query) |
| 665 | return urlparse.urlunparse(parts) |
| 666 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 667 | def step2_exchange(self, code, http=None): |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 668 | """Exhanges a code for OAuth2Credentials. |
| 669 | |
| 670 | Args: |
| 671 | code: string or dict, either the code as a string, or a dictionary |
| 672 | of the query parameters to the redirect_uri, which contains |
| 673 | the code. |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 674 | http: httplib2.Http, optional http instance to use to do the fetch |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 675 | """ |
| 676 | |
| 677 | if not (isinstance(code, str) or isinstance(code, unicode)): |
| 678 | code = code['code'] |
| 679 | |
| 680 | body = urllib.urlencode({ |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 681 | 'grant_type': 'authorization_code', |
| 682 | 'client_id': self.client_id, |
| 683 | 'client_secret': self.client_secret, |
| 684 | 'code': code, |
| 685 | 'redirect_uri': self.redirect_uri, |
| 686 | 'scope': self.scope, |
| 687 | }) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 688 | headers = { |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 689 | 'content-type': 'application/x-www-form-urlencoded', |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 690 | } |
JacobMoshenko | cb6d891 | 2011-07-08 13:35:15 -0400 | [diff] [blame] | 691 | |
| 692 | if self.user_agent is not None: |
| 693 | headers['user-agent'] = self.user_agent |
| 694 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 695 | if http is None: |
| 696 | http = httplib2.Http() |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 697 | resp, content = http.request(self.token_uri, method='POST', body=body, |
| 698 | headers=headers) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 699 | if resp.status == 200: |
| 700 | # TODO(jcgregorio) Raise an error if simplejson.loads fails? |
| 701 | d = simplejson.loads(content) |
| 702 | access_token = d['access_token'] |
| 703 | refresh_token = d.get('refresh_token', None) |
| 704 | token_expiry = None |
| 705 | if 'expires_in' in d: |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 706 | token_expiry = datetime.datetime.utcnow() + datetime.timedelta( |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 707 | seconds=int(d['expires_in'])) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 708 | |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 709 | logger.info('Successfully retrieved access token: %s' % content) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 710 | return OAuth2Credentials(access_token, self.client_id, |
| 711 | self.client_secret, refresh_token, token_expiry, |
| 712 | self.token_uri, self.user_agent) |
Joe Gregorio | 695fdc1 | 2011-01-16 16:46:55 -0500 | [diff] [blame] | 713 | else: |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 714 | logger.error('Failed to retrieve access token: %s' % content) |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 715 | error_msg = 'Invalid response %s.' % resp['status'] |
| 716 | try: |
| 717 | d = simplejson.loads(content) |
| 718 | if 'error' in d: |
| 719 | error_msg = d['error'] |
| 720 | except: |
| 721 | pass |
| 722 | |
| 723 | raise FlowExchangeError(error_msg) |