Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.8 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
                # Get the response object
101
                response = func(request, *args, **kwargs)
102

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

    
124

    
125
def get_serialization(request, format_allowed=True):
126
    """Return the serialization format requested.
127

128
    Valid formats are 'json' and 'xml' and 'text'
129
    """
130

    
131
    if not format_allowed:
132
        return "text"
133

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

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

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

    
156
    return "json"
157

    
158

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

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

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

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

    
184

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

    
191
    try:
192
        serialization = request.serialization
193
    except AttributeError:
194
        request.serialization = "json"
195
        serialization = "json"
196

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

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

    
210

    
211
def not_found(request):
212
    raise faults.BadRequest('Not found.')
213

    
214

    
215
def method_not_allowed(request):
216
    raise faults.BadRequest('Method not allowed')