Statistics
| Branch: | Tag: | Revision:

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

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
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
    """Decorator function for views that implement an API method."""
66
    if not logger:
67
        logger = log
68

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

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

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

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

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

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

    
125

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

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

    
132
    if not format_allowed:
133
        return "text"
134

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

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

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

    
157
    return "json"
158

    
159

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

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

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

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

    
185

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

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

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

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

    
211

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

    
215

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