Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.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

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

    
50

    
51
log = getLogger(__name__)
52

    
53

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

    
61

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

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

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

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

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

    
100
                # Mark request as api call
101
                request.api_call = True
102

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

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

    
127

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

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

    
134
    if not format_allowed:
135
        return "text"
136

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

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

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

    
159
    return "json"
160

    
161

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

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

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

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

    
187

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

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

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

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

    
213

    
214
def not_found(request):
215
    raise faults.BadRequest('Not found.')
216

    
217

    
218
def method_not_allowed(request):
219
    raise faults.BadRequest('Method not allowed')