Statistics
| Branch: | Tag: | Revision:

root / snf-common / synnefo / lib / astakos.py @ cd5033bd

History | View | Annotate | Download (5.6 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 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 or Not Found return directly
62
                        if status == 401 or status == 404:
63
                            raise e
64
                    attempts += 1
65
        return f
66
    return execute
67

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

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

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

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

    
91
    return json.loads(data)
92

    
93

    
94
def authenticate(token, authentication_url='http://127.0.0.1:8000/im/authenticate'):
95
    return call(token, authentication_url)
96

    
97
@retry(3)
98
def get_username(token, uuid, url='http://127.0.0.1:8000/im/service/api/v2.0/users'):
99
    try:
100
        data = call(token, url, {'X-User-Uuid': uuid})
101
    except Exception, e:
102
        raise e
103
    else:
104
        return data.get('username')
105

    
106

    
107
@retry(3)
108
def get_user_uuid(token, username, url='http://127.0.0.1:8000/im/service/api/v2.0/users'):
109
    try:
110
        data = call(token, url, {'X-User-Username': username})
111
    except Exception, e:
112
        raise e
113
    else:
114
        return data.get('uuid')
115

    
116

    
117
def user_for_token(token, authentication_url, override_users):
118
    if not token:
119
        return None
120

    
121
    if override_users:
122
        try:
123
            return {'uniq': override_users[token].decode('utf8')}
124
        except:
125
            return None
126

    
127
    try:
128
        return authenticate(token, authentication_url)
129
    except Exception, e:
130
        # In case of Unauthorized response return None
131
        if e.args and e.args[-1] == 401:
132
            return None
133
        raise e
134

    
135
def get_user(request, authentication_url='http://127.0.0.1:8000/im/authenticate', override_users={}, fallback_token=None):
136
    request.user = None
137
    request.user_uniq = None
138

    
139
    # Try to find token in a parameter or in a request header.
140
    user = user_for_token(request.GET.get('X-Auth-Token'), authentication_url, override_users)
141
    if not user:
142
        user = user_for_token(request.META.get('HTTP_X_AUTH_TOKEN'), authentication_url, override_users)
143
    if not user:
144
        user = user_for_token(fallback_token, authentication_url, override_users)
145
    if not user:
146
        logger.warning("Cannot retrieve user details from %s",
147
                       authentication_url)
148
        return
149

    
150
    # use user uuid, instead of email, keep email/username reference to user_id
151
    request.user_uniq = user['uuid']
152
    request.user = user
153
    request.user_id = user['username']
154
    return user
155

    
156

    
157
def get_token_from_cookie(request, cookiename):
158
    """
159
    Extract token from the cookie name provided. Cookie should be in the same
160
    form as astakos service sets its cookie contents::
161

162
        <user_uniq>|<user_token>
163
    """
164
    try:
165
        cookie_content = unquote(request.COOKIES.get(cookiename, None))
166
        return cookie_content.split("|")[1]
167
    except AttributeError:
168
        pass
169

    
170
    return None