diff --git a/README.md b/README.md index a220aef..44f2da5 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,19 @@ for dc in datacenters: Note that you don't need to care about pagination, the client handles it internally for you. +### Using an OpenID Bearer access token + +If your platform uses OpenID and you have a Bearer access token, you can configure the client +as follows: + +```python +import json +from abiquo.client import Abiquo +from abiquo.auth import BearerTokenAuth + +api = Abiquo(API_URL, auth=BearerTokenAuth(token)) +``` + ### Using OAuth To use OAuth first you have to register your client application in the Abiquo API. To do that, you can diff --git a/abiquo/auth.py b/abiquo/auth.py new file mode 100644 index 0000000..228587a --- /dev/null +++ b/abiquo/auth.py @@ -0,0 +1,23 @@ +# Copyright (C) 2008 Abiquo Holdings S.L. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from requests.auth import AuthBase + +class BearerTokenAuth(AuthBase): + def __init__(self, token): + self.token = token + + def __call__(self, request): + request.headers['Authorization'] = "Bearer %s" % self.token + return request diff --git a/abiquo/client.py b/abiquo/client.py index a7ae15e..046a9f8 100644 --- a/abiquo/client.py +++ b/abiquo/client.py @@ -169,3 +169,14 @@ def _extract_link(self, rel): def _has_link(self, rel): return True if self._extract_link(rel) else False + + +def check_response(expected_code, code, errors): + if code != expected_code: + try: + first_error = errors.json['collection'][0] + except: + # If it is not an Abiquo controlled error, throw a generic error + raise Exception("HTTP(%s) Operation failed!" % code) + # If it is an Abiquo error, properly show the error code and error details + raise Exception("HTTP(%s) %s: %s" % (code, first_error['code'], first_error['message']))