Statistics
| Branch: | Tag: | Revision:

root / snf-common / synnefo / lib / astakos.py @ 4ab1af1a

History | View | Annotate | Download (7 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 urlparse import urlparse
37
from urllib import unquote
38
from django.utils import simplejson as json
39

    
40
from synnefo.lib.pool.http import PooledHTTPConnection
41

    
42
logger = logging.getLogger(__name__)
43

    
44

    
45
def retry(howmany):
46
    def execute(func):
47
        def f(*args, **kwargs):
48
            attempts = 0
49
            while True:
50
                try:
51
                    return func(*args, **kwargs)
52
                except Exception, e:
53
                    is_last_attempt = attempts == howmany - 1
54
                    if is_last_attempt:
55
                        raise e
56
                    if e.args:
57
                        status = e.args[-1]
58
                        # In case of Unauthorized response
59
                        # or Not Found return directly
60
                        if status == 401 or status == 404:
61
                            raise e
62
                    attempts += 1
63
        return f
64
    return execute
65

    
66

    
67
def call(token, url, headers=None, body=None, method='GET'):
68
    p = urlparse(url)
69

    
70
    kwargs = {}
71
    if headers is None:
72
        headers = {}
73
    kwargs["headers"] = headers
74
    kwargs['headers']['X-Auth-Token'] = token
75
    if body:
76
        kwargs['body'] = body
77
        kwargs['headers'].setdefault('content-type',
78
                                     'application/octet-stream')
79
    kwargs['headers'].setdefault('content-length', len(body) if body else 0)
80

    
81
    with PooledHTTPConnection(p.netloc, p.scheme) as conn:
82
        conn.request(method, p.path + '?' + p.query, **kwargs)
83
        response = conn.getresponse()
84
        headers = response.getheaders()
85
        headers = dict((unquote(h), unquote(v)) for h, v in headers)
86
        length = response.getheader('content-length', None)
87
        data = response.read(length)
88
        status = int(response.status)
89

    
90
    if status < 200 or status >= 300:
91
        raise Exception(data, status)
92

    
93
    return json.loads(data)
94

    
95

    
96
def authenticate(
97
        token, authentication_url='http://127.0.0.1:8000/im/authenticate',
98
        usage=False):
99

    
100
    if usage:
101
        authentication_url += "?usage=1"
102

    
103
    return call(token, authentication_url)
104

    
105

    
106
@retry(3)
107
def get_displaynames(
108
        token,
109
        uuids,
110
        url='http://127.0.0.1:8000/user_catalogs',
111
        override_users={}):
112

    
113
    if override_users:
114
        return dict((u, u) for u in uuids)
115

    
116
    try:
117
        data = call(
118
            token, url,  headers={'content-type': 'application/json'},
119
            body=json.dumps({'uuids': uuids}), method='POST')
120
    except:
121
        raise
122
    else:
123
        return data.get('uuid_catalog')
124

    
125

    
126
@retry(3)
127
def get_uuids(
128
        token,
129
        displaynames,
130
        url='http://127.0.0.1:8000/user_catalogs',
131
        override_users={}):
132

    
133
    if override_users:
134
        return dict((u, u) for u in displaynames)
135

    
136
    try:
137
        data = call(
138
            token, url, headers={'content-type': 'application/json'},
139
            body=json.dumps({'displaynames': displaynames}), method='POST')
140
    except:
141
        raise
142
    else:
143
        return data.get('displayname_catalog')
144

    
145

    
146
def get_user_uuid(
147
        token,
148
        displayname,
149
        url='http://127.0.0.1:8000/user_catalogs',
150
        override_users={}):
151

    
152
    if not displayname:
153
        return
154

    
155
    displayname_dict = get_uuids(token, [displayname], url, override_users)
156
    return displayname_dict.get(displayname)
157

    
158

    
159
def get_displayname(
160
        token,
161
        uuid,
162
        url='http://127.0.0.1:8000/user_catalogs',
163
        override_users={}):
164

    
165
    if not uuid:
166
        return
167

    
168
    uuid_dict = get_displaynames(token, [uuid], url, override_users)
169
    return uuid_dict.get(uuid)
170

    
171

    
172
def user_for_token(token, authentication_url, override_users, usage=False):
173
    if not token:
174
        return None
175

    
176
    if override_users:
177
        try:
178
            return {'uuid': override_users[token].decode('utf8')}
179
        except:
180
            return None
181

    
182
    try:
183
        return authenticate(token, authentication_url, usage=usage)
184
    except Exception, e:
185
        # In case of Unauthorized response return None
186
        if e.args and e.args[-1] == 401:
187
            return None
188
        raise e
189

    
190

    
191
def get_user(
192
        request,
193
        authentication_url='http://127.0.0.1:8000/im/authenticate',
194
        override_users={},
195
        fallback_token=None,
196
        usage=False):
197
    request.user = None
198
    request.user_uniq = None
199

    
200
    # Try to find token in a parameter or in a request header.
201
    user = user_for_token(
202
        request.GET.get('X-Auth-Token'), authentication_url, override_users,
203
        usage=usage)
204
    if not user:
205
        user = user_for_token(
206
            request.META.get('HTTP_X_AUTH_TOKEN'),
207
            authentication_url,
208
            override_users,
209
            usage=usage)
210
    if not user:
211
        user = user_for_token(
212
            fallback_token, authentication_url, override_users,
213
            usage=usage)
214
    if not user:
215
        logger.warning("Cannot retrieve user details from %s",
216
                       authentication_url)
217
        return None
218

    
219
    # use user uuid, instead of email, keep email/displayname reference
220
    # to user_id
221
    request.user_uniq = user['uuid']
222
    request.user = user
223
    request.user_id = user.get('displayname')
224
    return user
225

    
226

    
227
def get_token_from_cookie(request, cookiename):
228
    """
229
    Extract token from the cookie name provided. Cookie should be in the same
230
    form as astakos service sets its cookie contents::
231

232
        <user_uniq>|<user_token>
233
    """
234
    try:
235
        cookie_content = unquote(request.COOKIES.get(cookiename, None))
236
        return cookie_content.split("|")[1]
237
    except AttributeError:
238
        pass
239

    
240
    return None