root / snf-astakos-client / astakosclient / __init__.py @ 8fe6475a
History | View | Annotate | Download (12.7 kB)
1 |
# Copyright (C) 2012, 2013 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
import logging |
35 |
import urlparse |
36 |
import httplib |
37 |
import urllib |
38 |
import hashlib |
39 |
from copy import copy |
40 |
|
41 |
import simplejson |
42 |
import objpool.http |
43 |
|
44 |
|
45 |
# --------------------------------------------------------------------
|
46 |
# Astakos Client Exception
|
47 |
class AstakosClientException(Exception): |
48 |
def __init__(self, message, status=0): |
49 |
self.message = message
|
50 |
self.status = status
|
51 |
|
52 |
def __str__(self): |
53 |
return repr(self.message) |
54 |
|
55 |
|
56 |
class AstakosClientEInvalid(AstakosClientException): |
57 |
def __init__(self, message): |
58 |
"""Invalid X-Auth-Token"""
|
59 |
super(AstakosClientEInvalid, self).__init__(message, 401) |
60 |
|
61 |
|
62 |
class AstakosClientEMethod(AstakosClientException): |
63 |
def __init__(self, message): |
64 |
"""Method not allowed"""
|
65 |
super(AstakosClientEMethod, self).__init__(message, 400) |
66 |
|
67 |
|
68 |
class AstakosClientENotFound(AstakosClientException): |
69 |
def __init__(self, message): |
70 |
"""404 Not Found"""
|
71 |
super(AstakosClientENotFound, self).__init__(message, 404) |
72 |
|
73 |
|
74 |
# --------------------------------------------------------------------
|
75 |
# Astakos Client Class
|
76 |
|
77 |
def getTokenFromCookie(request, cookie_name): |
78 |
"""Extract token from the cookie name provided
|
79 |
|
80 |
Cookie should be in the same form as astakos
|
81 |
service sets its cookie contents:
|
82 |
<user_uniq>|<user_token>
|
83 |
|
84 |
"""
|
85 |
try:
|
86 |
cookie_content = urllib.unquote(request.COOKIE.get(cookie_name, None))
|
87 |
return cookie_content.split("|")[1] |
88 |
except:
|
89 |
return None |
90 |
|
91 |
|
92 |
class AstakosClient(): |
93 |
"""AstakosClient Class Implementation"""
|
94 |
|
95 |
# ----------------------------------
|
96 |
def __init__(self, astakos_url, use_pool=False, retry=0, logger=None): |
97 |
"""Intialize AstakosClient Class
|
98 |
|
99 |
Keyword arguments:
|
100 |
astakos_url -- i.e https://accounts.example.com (string)
|
101 |
use_pool -- use objpool for http requests (boolean)
|
102 |
retry -- how many time to retry (integer)
|
103 |
logger -- pass a different logger
|
104 |
|
105 |
"""
|
106 |
if logger is None: |
107 |
logging.basicConfig( |
108 |
format='%(asctime)s [%(levelname)s] %(name)s %(message)s',
|
109 |
datefmt='%Y-%m-%d %H:%M:%S',
|
110 |
level=logging.INFO) |
111 |
logger = logging.getLogger("astakosclient")
|
112 |
logger.debug("Intialize AstakosClient: astakos_url = %s, "
|
113 |
"use_pool = %s" % (astakos_url, use_pool))
|
114 |
|
115 |
if not astakos_url: |
116 |
m = "Astakos url not given"
|
117 |
logger.error(m) |
118 |
raise ValueError(m) |
119 |
|
120 |
# Check for supported scheme
|
121 |
p = urlparse.urlparse(astakos_url) |
122 |
conn_class = _scheme_to_class(p.scheme, use_pool) |
123 |
if conn_class is None: |
124 |
m = "Unsupported scheme: %s" % p.scheme
|
125 |
logger.error(m) |
126 |
raise ValueError(m) |
127 |
|
128 |
# Save astakos_url etc. in our class
|
129 |
self.retry = retry
|
130 |
self.logger = logger
|
131 |
self.netloc = p.netloc
|
132 |
self.scheme = p.scheme
|
133 |
self.conn_class = conn_class
|
134 |
|
135 |
# ----------------------------------
|
136 |
def retry(func): |
137 |
def decorator(self, *args, **kwargs): |
138 |
attemps = 0
|
139 |
while True: |
140 |
try:
|
141 |
return func(self, *args, **kwargs) |
142 |
except AstakosClientException as err: |
143 |
is_last_attempt = attemps == self.retry
|
144 |
if is_last_attempt:
|
145 |
raise err
|
146 |
if err.status == 401 or err.status == 404: |
147 |
# In case of Unauthorized response
|
148 |
# or Not Found return immediately
|
149 |
raise err
|
150 |
self.logger.info("AstakosClient request failed..retrying") |
151 |
attemps += 1
|
152 |
return decorator
|
153 |
|
154 |
# ----------------------------------
|
155 |
@retry
|
156 |
def _callAstakos(self, token, request_path, |
157 |
headers=None, body=None, method="GET"): |
158 |
"""Make the actual call to Astakos Service"""
|
159 |
hashed_token = hashlib.sha1() |
160 |
hashed_token.update(token) |
161 |
self.logger.debug(
|
162 |
"Make a %s request to %s using token %s "
|
163 |
"with headers %s and body %s"
|
164 |
% (method, request_path, hashed_token.hexdigest(), headers, body)) |
165 |
|
166 |
# Check Input
|
167 |
if not token: |
168 |
m = "Token not given"
|
169 |
self.logger.error(m)
|
170 |
raise ValueError(m) |
171 |
if headers is None: |
172 |
headers = {} |
173 |
if body is None: |
174 |
body = {} |
175 |
if request_path[0] != '/': |
176 |
request_path = "/" + request_path
|
177 |
|
178 |
# Build request's header and body
|
179 |
kwargs = {} |
180 |
kwargs['headers'] = copy(headers)
|
181 |
kwargs['headers']['X-Auth-Token'] = token |
182 |
if body:
|
183 |
kwargs['body'] = copy(body)
|
184 |
kwargs['headers'].setdefault(
|
185 |
'content-type', 'application/octet-stream') |
186 |
kwargs['headers'].setdefault('content-length', |
187 |
len(body) if body else 0) |
188 |
|
189 |
# Get the connection object
|
190 |
conn = self.conn_class(self.netloc) |
191 |
|
192 |
# Send request
|
193 |
try:
|
194 |
(data, status) = _doRequest(conn, method, request_path, **kwargs) |
195 |
except Exception as err: |
196 |
self.logger.error("Failed to send request: %s" % err) |
197 |
raise AstakosClientException(str(err)) |
198 |
finally:
|
199 |
conn.close() |
200 |
|
201 |
# Return
|
202 |
self.logger.debug("Request returned with status %s" % status) |
203 |
if status == 400: |
204 |
raise AstakosClientEMethod(data)
|
205 |
if status == 401: |
206 |
raise AstakosClientEInvalid(data)
|
207 |
if status == 404: |
208 |
raise AstakosClientENotFound(data)
|
209 |
if status < 200 or status >= 300: |
210 |
raise AstakosClientException(data, status)
|
211 |
return simplejson.loads(unicode(data)) |
212 |
|
213 |
# ------------------------
|
214 |
def authenticate(self, token, usage=False): |
215 |
"""Check if user is authenticated Astakos user
|
216 |
|
217 |
Keyword arguments:
|
218 |
token -- user's token (string)
|
219 |
usage -- return usage information for user (boolean)
|
220 |
|
221 |
In case of success return user information (json parsed format).
|
222 |
Otherwise raise an AstakosClientException.
|
223 |
|
224 |
"""
|
225 |
# Send request
|
226 |
auth_path = "/im/authenticate"
|
227 |
if usage:
|
228 |
auth_path += "?usage=1"
|
229 |
return self._callAstakos(token, auth_path) |
230 |
|
231 |
# ----------------------------------
|
232 |
def _uuidCatalog(self, token, uuids, req_path): |
233 |
req_headers = {'content-type': 'application/json'} |
234 |
req_body = simplejson.dumps({'uuids': uuids})
|
235 |
data = self._callAstakos(
|
236 |
token, req_path, req_headers, req_body, "POST")
|
237 |
# XXX: check if exists
|
238 |
return data.get("uuid_catalog") |
239 |
|
240 |
def getDisplayNames(self, token, uuids): |
241 |
"""Return a uuid_catalog dictionary for the given uuids
|
242 |
|
243 |
Keyword arguments:
|
244 |
token -- user's token (string)
|
245 |
uuids -- list of user ids (list of strings)
|
246 |
|
247 |
The returned uuid_catalog is a dictionary with uuids as
|
248 |
keys and the corresponding user names as values
|
249 |
|
250 |
"""
|
251 |
req_path = "/user_catalogs"
|
252 |
return self._uuidCatalog(token, uuids, req_path) |
253 |
|
254 |
def getDisplayName(self, token, uuid): |
255 |
"""Return the displayName of a uuid (see getDisplayNames)"""
|
256 |
if not uuid: |
257 |
m = "No uuid was given"
|
258 |
self.logger.error(m)
|
259 |
raise ValueError(m) |
260 |
uuid_dict = self.getDisplayNames(token, [uuid])
|
261 |
# XXX: check if exists
|
262 |
return uuid_dict.get(uuid)
|
263 |
|
264 |
def getServiceDisplayNames(self, token, uuids): |
265 |
"""Return a uuid_catalog dict using a service's token"""
|
266 |
req_path = "/service/api/user_catalogs"
|
267 |
return self._uuidCatalog(token, uuids, req_path) |
268 |
|
269 |
def getServiceDisplayName(self, token, uuid): |
270 |
"""Return the displayName of a uuid using a service's token"""
|
271 |
if not uuid: |
272 |
m = "No uuid was given"
|
273 |
self.logger.error(m)
|
274 |
raise ValueError(m) |
275 |
uuid_dict = self.getServiceDisplayNames(token, [uuid])
|
276 |
# XXX: check if exists
|
277 |
return uuid_dict.get(uuid)
|
278 |
|
279 |
# ----------------------------------
|
280 |
def _displayNameCatalog(self, token, display_names, req_path): |
281 |
req_headers = {'content-type': 'application/json'} |
282 |
req_body = simplejson.dumps({'displaynames': display_names})
|
283 |
data = self._callAstakos(
|
284 |
token, req_path, req_headers, req_body, "POST")
|
285 |
# XXX: check if exists
|
286 |
return data.get("displayname_catalog") |
287 |
|
288 |
def getUUIDs(self, token, display_names): |
289 |
"""Return a displayname_catalog for the given names
|
290 |
|
291 |
Keyword arguments:
|
292 |
token -- user's token (string)
|
293 |
display_names -- list of user names (list of strings)
|
294 |
|
295 |
The returned displayname_catalog is a dictionary with
|
296 |
the names as keys and the corresponding uuids as values
|
297 |
|
298 |
"""
|
299 |
req_path = "/user_catalogs"
|
300 |
return self._displayNameCatalog(token, display_names, req_path) |
301 |
|
302 |
def getUUID(self, token, display_name): |
303 |
"""Return the uuid of a name (see getUUIDs)"""
|
304 |
if not display_name: |
305 |
m = "No display_name was given"
|
306 |
self.logger.error(m)
|
307 |
raise ValueError(m) |
308 |
name_dict = self.getUUIDs(token, [display_name])
|
309 |
# XXX: check if exists
|
310 |
return name_dict.get(display_name)
|
311 |
|
312 |
def getServiceUUIDs(self, token, display_names): |
313 |
"""Return a display_name catalog using a service's token"""
|
314 |
req_path = "/service/api/user_catalogs"
|
315 |
return self._displayNameCatalog(token, display_names, req_path) |
316 |
|
317 |
def getServiceUUID(self, token, display_name): |
318 |
"""Return the uuid of a name using a service's token"""
|
319 |
if not display_name: |
320 |
m = "No display_name was given"
|
321 |
self.logger.error(m)
|
322 |
raise ValueError(m) |
323 |
name_dict = self.getServiceUUIDs(token, [display_name])
|
324 |
# XXX: check if exists
|
325 |
return name_dict.get(display_name)
|
326 |
|
327 |
# ----------------------------------
|
328 |
def getServices(self): |
329 |
"""Return a list of dicts with the registered services"""
|
330 |
return self._callAstakos("dummy token", "/im/get_services") |
331 |
|
332 |
|
333 |
# --------------------------------------------------------------------
|
334 |
# Private functions
|
335 |
def _scheme_to_class(scheme, use_pool): |
336 |
"""Return the appropriate conn class for given scheme"""
|
337 |
if scheme == "http": |
338 |
if use_pool:
|
339 |
return _objpoolHttpScheme
|
340 |
else:
|
341 |
return httplib.HTTPConnection
|
342 |
elif scheme == "https": |
343 |
if use_pool:
|
344 |
return _objpoolHttpsScheme
|
345 |
else:
|
346 |
return httplib.HTTPSConnection
|
347 |
else:
|
348 |
return None |
349 |
|
350 |
|
351 |
def _objpoolHttpScheme(netloc): |
352 |
"""Intialize the appropriate objpool.http class"""
|
353 |
return objpool.http.get_http_connection(netloc, "http") |
354 |
|
355 |
|
356 |
def _objpoolHttpsScheme(netloc): |
357 |
"""Intialize the appropriate objpool.http class"""
|
358 |
return objpool.http.get_http_connection(netloc, "https") |
359 |
|
360 |
|
361 |
def _doRequest(conn, method, url, **kwargs): |
362 |
"""The actual request. This function can easily be mocked"""
|
363 |
conn.request(method, url, **kwargs) |
364 |
response = conn.getresponse() |
365 |
length = response.getheader('content-length', None) |
366 |
data = response.read(length) |
367 |
status = int(response.status)
|
368 |
return (data, status)
|