Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.7 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
                    try:
94
                        astakos = AstakosClient(astakos,
95
                                                use_pool=True,
96
                                                logger=logger)
97
                        user_info = astakos.get_user_info(token)
98
                    except AstakosClientException as err:
99
                        raise faults.Fault(message=err.message,
100
                                           details=err.details,
101
                                           code=err.status)
102
                    request.user_uniq = user_info["uuid"]
103
                    request.user = user_info
104

    
105
                # Get the response object
106
                response = func(request, *args, **kwargs)
107

    
108
                # Fill in response variables
109
                update_response_headers(request, response)
110
                return response
111
            except faults.Fault, fault:
112
                if fault.code >= 500:
113
                    logger.exception("API ERROR")
114
                return render_fault(request, fault)
115
            except:
116
                logger.exception("Unexpected ERROR")
117
                fault = faults.InternalServerError("Unexpected ERROR")
118
                return render_fault(request, fault)
119
        return wrapper
120
    return decorator
121

    
122

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

126
    Valid formats are 'json' and 'xml' and 'text'
127
    """
128

    
129
    if not format_allowed:
130
        return "text"
131

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

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

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

    
154
    return "json"
155

    
156

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

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

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

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

    
182

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

    
189
    try:
190
        serialization = request.serialization
191
    except AttributeError:
192
        request.serialization = "json"
193
        serialization = "json"
194

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

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

    
208

    
209
def not_found(request):
210
    raise faults.BadRequest('Not found.')
211

    
212

    
213
def method_not_allowed(request):
214
    raise faults.BadRequest('Method not allowed')