Statistics
| Branch: | Tag: | Revision:

root / snf-django-lib / snf_django / lib / api / __init__.py @ fced411d

History | View | Annotate | Download (8.9 kB)

1
# Copyright 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
from functools import wraps
35
from traceback import format_exc
36
from time import time
37
from logging import getLogger
38
from wsgiref.handlers import format_date_time
39

    
40
from django.http import HttpResponse
41
from django.utils import cache
42
from django.utils import simplejson as json
43
from django.template.loader import render_to_string
44
from django.views.decorators import csrf
45

    
46
from astakosclient import AstakosClient
47
from astakosclient.errors import AstakosClientException
48
from django.conf import settings
49
from snf_django.lib.api import faults
50

    
51

    
52
log = getLogger(__name__)
53

    
54

    
55
def get_token(request):
56
    """Get the Authentication Token of a request."""
57
    token = request.GET.get("X-Auth-Token", None)
58
    if not token:
59
        token = request.META.get("HTTP_X_AUTH_TOKEN", None)
60
    return token
61

    
62

    
63
def api_method(http_method=None, token_required=True, user_required=True,
64
               logger=None, format_allowed=True, astakos_url=None,
65
               default_serialization="json"):
66
    """Decorator function for views that implement an API method."""
67
    if not logger:
68
        logger = log
69

    
70
    def decorator(func):
71
        @wraps(func)
72
        def wrapper(request, *args, **kwargs):
73
            try:
74
                # Get the requested serialization format
75
                request.serialization = get_serialization(
76
                    request, format_allowed, default_serialization)
77

    
78
                # Check HTTP method
79
                if http_method and request.method != http_method:
80
                    raise faults.BadRequest("Method not allowed")
81

    
82
                # Get authentication token
83
                request.x_auth_token = None
84
                if token_required or user_required:
85
                    token = get_token(request)
86
                    if not token:
87
                        msg = "Access denied. No authentication token"
88
                        raise faults.Unauthorized(msg)
89
                    request.x_auth_token = token
90

    
91
                # Authenticate
92
                if user_required:
93
                    assert(token_required), "Can not get user without token"
94
                    astakos = astakos_url or settings.ASTAKOS_BASE_URL
95
                    astakos = AstakosClient(astakos,
96
                                            use_pool=True,
97
                                            logger=logger)
98
                    user_info = astakos.get_user_info(token)
99
                    request.user_uniq = user_info["uuid"]
100
                    request.user = user_info
101

    
102
                # Get the response object
103
                response = func(request, *args, **kwargs)
104

    
105
                # Fill in response variables
106
                update_response_headers(request, response)
107
                return response
108
            except faults.Fault, fault:
109
                if fault.code >= 500:
110
                    logger.exception("API ERROR")
111
                return render_fault(request, fault)
112
            except AstakosClientException as err:
113
                fault = faults.Fault(message=err.message,
114
                                     details=err.details,
115
                                     code=err.status)
116
                if fault.code >= 500:
117
                    logger.exception("Astakos ERROR")
118
                return render_fault(request, fault)
119
            except:
120
                logger.exception("Unexpected ERROR")
121
                fault = faults.InternalServerError("Unexpected error")
122
                return render_fault(request, fault)
123
        return csrf.csrf_exempt(wrapper)
124
    return decorator
125

    
126

    
127
def get_serialization(request, format_allowed=True, default_serialization="json"):
128
    """Return the serialization format requested.
129

130
    Valid formats are 'json' and 'xml' and 'text'
131
    """
132

    
133
    if not format_allowed:
134
        return "text"
135

    
136
    # Try to get serialization from 'format' parameter
137
    _format = request.GET.get("format")
138
    if _format:
139
        if _format == "json":
140
            return "json"
141
        elif _format == "xml":
142
            return "xml"
143

    
144
    # Try to get serialization from path
145
    path = request.path
146
    if path.endswith(".json"):
147
        return "json"
148
    elif path.endswith(".xml"):
149
        return "xml"
150

    
151
    for item in request.META.get("HTTP_ACCEPT", "").split(","):
152
        accept, sep, rest = item.strip().partition(";")
153
        if accept == "application/json":
154
            return "json"
155
        elif accept == "application/xml":
156
            return "xml"
157

    
158
    return default_serialization
159

    
160

    
161
def update_response_headers(request, response):
162
    if not getattr(response, "override_serialization", False):
163
        serialization = request.serialization
164
        if serialization == "xml":
165
            response["Content-Type"] = "application/xml; charset=UTF-8"
166
        elif serialization == "json":
167
            response["Content-Type"] = "application/json; charset=UTF-8"
168
        elif serialization == "text":
169
            response["Content-Type"] = "text/plain; charset=UTF-8"
170
        else:
171
            raise ValueError("Unknown serialization format '%s'" %
172
                             serialization)
173

    
174
    if settings.DEBUG or getattr(settings, "TEST", False):
175
        response["Date"] = format_date_time(time())
176

    
177
    if not response.has_header("Content-Length"):
178
        response["Content-Length"] = len(response.content)
179

    
180
    cache.add_never_cache_headers(response)
181
    # Fix Vary and Cache-Control Headers. Issue: #3448
182
    cache.patch_vary_headers(response, ('X-Auth-Token',))
183
    cache.patch_cache_control(response, no_cache=True, no_store=True,
184
                              must_revalidate=True)
185

    
186

    
187
def render_fault(request, fault):
188
    """Render an API fault to an HTTP response."""
189
    # If running in debug mode add exception information to fault details
190
    if settings.DEBUG or getattr(settings, "TEST", False):
191
        fault.details = format_exc()
192

    
193
    try:
194
        serialization = request.serialization
195
    except AttributeError:
196
        request.serialization = "json"
197
        serialization = "json"
198

    
199
    # Serialize the fault data to xml or json
200
    if serialization == "xml":
201
        data = render_to_string("fault.xml", {"fault": fault})
202
    else:
203
        d = {fault.name: {"code": fault.code,
204
                          "message": fault.message,
205
                          "details": fault.details}}
206
        data = json.dumps(d)
207

    
208
    response = HttpResponse(data, status=fault.code)
209
    update_response_headers(request, response)
210
    return response
211

    
212

    
213
@api_method(token_required=False, user_required=False)
214
def api_endpoint_not_found(request):
215
    raise faults.BadRequest("API endpoint not found")
216

    
217

    
218
@api_method(token_required=False, user_required=False)
219
def api_method_not_allowed(request):
220
    raise faults.BadRequest('Method not allowed')
221

    
222

    
223
def allow_jsonp(key='callback'):
224
    """
225
    Wrapper to enable jsonp responses.
226
    """
227
    def wrapper(func):
228
        def view_wrapper(request, *args, **kwargs):
229
            response = func(request, *args, **kwargs)
230
            if 'content-type' in response._headers and \
231
               response._headers['content-type'][1] == 'application/json':
232
                callback_name = request.GET.get(key, None)
233
                if callback_name:
234
                    response.content = "%s(%s)" % (callback_name,
235
                                                   response.content)
236
                    response._headers['content-type'] = ('Content-Type',
237
                                                         'text/javascript')
238
            return response
239
        return view_wrapper
240
    return wrapper