Statistics
| Branch: | Tag: | Revision:

root / snf-common / synnefo / lib / astakos.py @ 0308f3a7

History | View | Annotate | Download (6.2 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, urlencode
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 True:
53
                try:
54
                    return func(*args, **kwargs)
55
                except Exception, e:
56
                    is_last_attempt = attempts == howmany - 1
57
                    if is_last_attempt:
58
                        raise e
59
                    if e.args:
60
                        status = e.args[-1]
61
                        # In case of Unauthorized response
62
                        # or Not Found return directly
63
                        if status == 401 or status == 404:
64
                            raise e
65
                    attempts += 1
66
        return f
67
    return execute
68

    
69
def call(token, url, headers={}):
70
    p = urlparse(url)
71

    
72
    kwargs = {}
73
    kwargs['headers'] = headers
74
    kwargs['headers']['X-Auth-Token'] = token
75
    kwargs['headers']['Content-Length'] = 0
76

    
77
    conn = get_http_connection(p.netloc, p.scheme)
78
    try:
79
        conn.request('GET', p.path + '?' + p.query, **kwargs)
80
        response = conn.getresponse()
81
        headers = response.getheaders()
82
        headers = dict((unquote(h), unquote(v)) for h,v in headers)
83
        length = response.getheader('content-length', None)
84
        data = response.read(length)
85
        status = int(response.status)
86
    finally:
87
        conn.close()
88

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

    
92
    return json.loads(data)
93

    
94

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

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

    
102
    return call(token, authentication_url)
103

    
104

    
105
@retry(3)
106
def get_username(
107
        token,
108
        uuid,
109
        url='http://127.0.0.1:8000/im/service/api/v2.0/users',
110
        override_users={}):
111
    if override_users:
112
        return uuid
113

    
114
    headers = {}
115
    if uuid:
116
        headers['X-User-Uuid'] = uuid
117

    
118
    try:
119
        data = call(token, url, headers)
120
    except Exception, e:
121
        raise e
122
    else:
123
        return data.get('username')
124

    
125

    
126
@retry(3)
127
def get_user_uuid(
128
        token,
129
        username,
130
        url='http://127.0.0.1:8000/im/service/api/v2.0/users',
131
        override_users={}):
132
    if override_users:
133
        return username
134

    
135
    headers = {}
136
    if username:
137
        headers['X-User-Username'] = username
138
    try:
139
        data = call(token, url, headers)
140
    except Exception, e:
141
        raise e
142
    else:
143
        return data.get('uuid')
144

    
145

    
146
def user_for_token(token, authentication_url, override_users, usage=False):
147
    if not token:
148
        return None
149

    
150
    if override_users:
151
        try:
152
            return {'uuid': override_users[token].decode('utf8')}
153
        except:
154
            return None
155

    
156
    try:
157
        return authenticate(token, authentication_url, usage=usage)
158
    except Exception, e:
159
        # In case of Unauthorized response return None
160
        if e.args and e.args[-1] == 401:
161
            return None
162
        raise e
163

    
164
def get_user(
165
        request,
166
        authentication_url='http://127.0.0.1:8000/im/authenticate',
167
        override_users={},
168
        fallback_token=None,
169
        usage=False):
170
    request.user = None
171
    request.user_uniq = None
172

    
173
    # Try to find token in a parameter or in a request header.
174
    user = user_for_token(
175
        request.GET.get('X-Auth-Token'), authentication_url, override_users,
176
        usage=usage)
177
    if not user:
178
        user = user_for_token(
179
            request.META.get('HTTP_X_AUTH_TOKEN'),
180
            authentication_url,
181
            override_users,
182
            usage=usage)
183
    if not user:
184
        user = user_for_token(
185
            fallback_token, authentication_url, override_users,
186
            usage=usage)
187
    if not user:
188
        logger.warning("Cannot retrieve user details from %s",
189
                       authentication_url)
190
        return None
191

    
192
    # use user uuid, instead of email, keep email/username reference to user_id
193
    request.user_uniq = user['uuid']
194
    request.user = user
195
    request.user_id = user.get('username')
196
    return user
197

    
198

    
199
def get_token_from_cookie(request, cookiename):
200
    """
201
    Extract token from the cookie name provided. Cookie should be in the same
202
    form as astakos service sets its cookie contents::
203

204
        <user_uniq>|<user_token>
205
    """
206
    try:
207
        cookie_content = unquote(request.COOKIES.get(cookiename, None))
208
        return cookie_content.split("|")[1]
209
    except AttributeError:
210
        pass
211

    
212
    return None