root / snf-common / synnefo / lib / astakos.py @ c700f742
History | View | Annotate | Download (5.5 kB)
1 |
# Copyright 2011-2012 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 |
|
36 |
from time import time, mktime |
37 |
from urlparse import urlparse, urlsplit, urlunsplit |
38 |
from urllib import quote, unquote |
39 |
|
40 |
from django.conf import settings |
41 |
from django.utils import simplejson as json |
42 |
from django.utils.http import urlencode |
43 |
|
44 |
from synnefo.lib.pool.http import get_http_connection |
45 |
|
46 |
logger = logging.getLogger(__name__) |
47 |
|
48 |
def retry(howmany): |
49 |
def execute(func): |
50 |
def f(*args, **kwargs): |
51 |
attempts = 0
|
52 |
while attempts < howmany:
|
53 |
try:
|
54 |
return func(*args, **kwargs)
|
55 |
except Exception, e: |
56 |
if e.args:
|
57 |
status = e.args[-1]
|
58 |
# In case of Unauthorized response or Not Found return directly
|
59 |
if status == 401 or status == 404: |
60 |
raise e
|
61 |
attempts += 1
|
62 |
return f
|
63 |
return execute
|
64 |
|
65 |
def call(token, url, headers={}): |
66 |
p = urlparse(url) |
67 |
|
68 |
kwargs = {} |
69 |
kwargs['headers'] = headers
|
70 |
kwargs['headers']['X-Auth-Token'] = token |
71 |
kwargs['headers']['Content-Length'] = 0 |
72 |
|
73 |
conn = get_http_connection(p.netloc, p.scheme) |
74 |
try:
|
75 |
conn.request('GET', p.path, **kwargs)
|
76 |
response = conn.getresponse() |
77 |
headers = response.getheaders() |
78 |
headers = dict((unquote(h), unquote(v)) for h,v in headers) |
79 |
length = response.getheader('content-length', None) |
80 |
data = response.read(length) |
81 |
status = int(response.status)
|
82 |
finally:
|
83 |
conn.close() |
84 |
|
85 |
if status < 200 or status >= 300: |
86 |
raise Exception(data, status) |
87 |
|
88 |
return json.loads(data)
|
89 |
|
90 |
|
91 |
def authenticate(token, authentication_url='http://127.0.0.1:8000/im/authenticate'): |
92 |
return call(token, authentication_url)
|
93 |
|
94 |
@retry(3) |
95 |
def get_username(token, uuid, url='http://127.0.0.1:8000/im/service/api/v2.0/users'): |
96 |
try:
|
97 |
data = call(token, url, {'X-User-Uuid': uuid})
|
98 |
except Exception, e: |
99 |
raise e
|
100 |
else:
|
101 |
return data.get('username') |
102 |
|
103 |
|
104 |
@retry(3) |
105 |
def get_user_uuid(token, username, url='http://127.0.0.1:8000/im/service/api/v2.0/users'): |
106 |
try:
|
107 |
data = call(token, url, {'X-User-Username': username})
|
108 |
except Exception, e: |
109 |
raise e
|
110 |
else:
|
111 |
return data.get('uuid') |
112 |
|
113 |
|
114 |
def user_for_token(token, authentication_url, override_users): |
115 |
if not token: |
116 |
return None |
117 |
|
118 |
if override_users:
|
119 |
try:
|
120 |
return {'uniq': override_users[token].decode('utf8')} |
121 |
except:
|
122 |
return None |
123 |
|
124 |
try:
|
125 |
return authenticate(token, authentication_url)
|
126 |
except Exception, e: |
127 |
# In case of Unauthorized response return None
|
128 |
if e.args and e.args[-1] == 401: |
129 |
return None |
130 |
raise e
|
131 |
|
132 |
def get_user(request, authentication_url='http://127.0.0.1:8000/im/authenticate', override_users={}, fallback_token=None): |
133 |
request.user = None
|
134 |
request.user_uniq = None
|
135 |
|
136 |
# Try to find token in a parameter or in a request header.
|
137 |
user = user_for_token(request.GET.get('X-Auth-Token'), authentication_url, override_users)
|
138 |
if not user: |
139 |
user = user_for_token(request.META.get('HTTP_X_AUTH_TOKEN'), authentication_url, override_users)
|
140 |
if not user: |
141 |
user = user_for_token(fallback_token, authentication_url, override_users) |
142 |
if not user: |
143 |
logger.warning("Cannot retrieve user details from %s",
|
144 |
authentication_url) |
145 |
return
|
146 |
|
147 |
# use user uuid, instead of email, keep email/username reference to user_id
|
148 |
request.user_uniq = user['uuid']
|
149 |
request.user = user |
150 |
request.user_id = user['username']
|
151 |
return user
|
152 |
|
153 |
|
154 |
def get_token_from_cookie(request, cookiename): |
155 |
"""
|
156 |
Extract token from the cookie name provided. Cookie should be in the same
|
157 |
form as astakos service sets its cookie contents::
|
158 |
|
159 |
<user_uniq>|<user_token>
|
160 |
"""
|
161 |
try:
|
162 |
cookie_content = unquote(request.COOKIES.get(cookiename, None))
|
163 |
return cookie_content.split("|")[1] |
164 |
except AttributeError: |
165 |
pass
|
166 |
|
167 |
return None |