Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.3 kB)

1 72bf812d Christos Stavrakakis
# Copyright 2012, 2013 GRNET S.A. All rights reserved.
2 72bf812d Christos Stavrakakis
#
3 72bf812d Christos Stavrakakis
# Redistribution and use in source and binary forms, with or
4 72bf812d Christos Stavrakakis
# without modification, are permitted provided that the following
5 72bf812d Christos Stavrakakis
# conditions are met:
6 72bf812d Christos Stavrakakis
#
7 72bf812d Christos Stavrakakis
#   1. Redistributions of source code must retain the above
8 72bf812d Christos Stavrakakis
#      copyright notice, this list of conditions and the following
9 72bf812d Christos Stavrakakis
#      disclaimer.
10 72bf812d Christos Stavrakakis
#
11 72bf812d Christos Stavrakakis
#   2. Redistributions in binary form must reproduce the above
12 72bf812d Christos Stavrakakis
#      copyright notice, this list of conditions and the following
13 72bf812d Christos Stavrakakis
#      disclaimer in the documentation and/or other materials
14 72bf812d Christos Stavrakakis
#      provided with the distribution.
15 72bf812d Christos Stavrakakis
#
16 72bf812d Christos Stavrakakis
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 72bf812d Christos Stavrakakis
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 72bf812d Christos Stavrakakis
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 72bf812d Christos Stavrakakis
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 72bf812d Christos Stavrakakis
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 72bf812d Christos Stavrakakis
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 72bf812d Christos Stavrakakis
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 72bf812d Christos Stavrakakis
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 72bf812d Christos Stavrakakis
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 72bf812d Christos Stavrakakis
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 72bf812d Christos Stavrakakis
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 72bf812d Christos Stavrakakis
# POSSIBILITY OF SUCH DAMAGE.
28 72bf812d Christos Stavrakakis
#
29 72bf812d Christos Stavrakakis
# The views and conclusions contained in the software and
30 72bf812d Christos Stavrakakis
# documentation are those of the authors and should not be
31 72bf812d Christos Stavrakakis
# interpreted as representing official policies, either expressed
32 72bf812d Christos Stavrakakis
# or implied, of GRNET S.A.
33 72bf812d Christos Stavrakakis
34 72bf812d Christos Stavrakakis
from functools import wraps
35 72bf812d Christos Stavrakakis
from traceback import format_exc
36 72bf812d Christos Stavrakakis
from time import time
37 72bf812d Christos Stavrakakis
from logging import getLogger
38 72bf812d Christos Stavrakakis
from wsgiref.handlers import format_date_time
39 72bf812d Christos Stavrakakis
40 72bf812d Christos Stavrakakis
from django.http import HttpResponse
41 72bf812d Christos Stavrakakis
from django.utils import cache
42 72bf812d Christos Stavrakakis
from django.utils import simplejson as json
43 72bf812d Christos Stavrakakis
from django.template.loader import render_to_string
44 72bf812d Christos Stavrakakis
45 72bf812d Christos Stavrakakis
from astakosclient import AstakosClient
46 72bf812d Christos Stavrakakis
from django.conf import settings
47 72bf812d Christos Stavrakakis
from snf_django.lib.api import faults
48 72bf812d Christos Stavrakakis
49 72bf812d Christos Stavrakakis
50 72bf812d Christos Stavrakakis
log = getLogger(__name__)
51 72bf812d Christos Stavrakakis
52 72bf812d Christos Stavrakakis
53 72bf812d Christos Stavrakakis
def get_token(request):
54 72bf812d Christos Stavrakakis
    """Get the Authentication Token of a request."""
55 72bf812d Christos Stavrakakis
    token = request.GET.get("X-Auth-Token", None)
56 72bf812d Christos Stavrakakis
    if not token:
57 72bf812d Christos Stavrakakis
        token = request.META.get("HTTP_X_AUTH_TOKEN", None)
58 72bf812d Christos Stavrakakis
    return token
59 72bf812d Christos Stavrakakis
60 72bf812d Christos Stavrakakis
61 72bf812d Christos Stavrakakis
def api_method(http_method=None, token_required=True, user_required=True,
62 72bf812d Christos Stavrakakis
               logger=None, format_allowed=True):
63 72bf812d Christos Stavrakakis
    """Decorator function for views that implement an API method."""
64 72bf812d Christos Stavrakakis
    if not logger:
65 72bf812d Christos Stavrakakis
        logger = log
66 72bf812d Christos Stavrakakis
67 72bf812d Christos Stavrakakis
    def decorator(func):
68 72bf812d Christos Stavrakakis
        @wraps(func)
69 72bf812d Christos Stavrakakis
        def wrapper(request, *args, **kwargs):
70 72bf812d Christos Stavrakakis
            try:
71 72bf812d Christos Stavrakakis
                # Get the requested serialization format
72 72bf812d Christos Stavrakakis
                request.serialization = get_serialization(request,
73 72bf812d Christos Stavrakakis
                                                          format_allowed)
74 72bf812d Christos Stavrakakis
75 72bf812d Christos Stavrakakis
                # Check HTTP method
76 72bf812d Christos Stavrakakis
                if http_method and request.method != http_method:
77 72bf812d Christos Stavrakakis
                    raise faults.BadRequest("Method not allowed")
78 72bf812d Christos Stavrakakis
79 72bf812d Christos Stavrakakis
                # Get authentication token
80 72bf812d Christos Stavrakakis
                request.x_auth_token = None
81 72bf812d Christos Stavrakakis
                if token_required or user_required:
82 72bf812d Christos Stavrakakis
                    token = get_token(request)
83 72bf812d Christos Stavrakakis
                    if not token:
84 72bf812d Christos Stavrakakis
                        msg = "Access denied. No authentication token"
85 72bf812d Christos Stavrakakis
                        raise faults.Unauthorized(msg)
86 72bf812d Christos Stavrakakis
                    request.x_auth_token = token
87 72bf812d Christos Stavrakakis
88 72bf812d Christos Stavrakakis
                # Authenticate
89 72bf812d Christos Stavrakakis
                if user_required:
90 72bf812d Christos Stavrakakis
                    assert(token_required), "Can not get user without token"
91 72bf812d Christos Stavrakakis
                    astakos = AstakosClient(settings.ASTAKOS_URL,
92 72bf812d Christos Stavrakakis
                                            use_pool=True,
93 72bf812d Christos Stavrakakis
                                            logger=logger)
94 72bf812d Christos Stavrakakis
                    user_info = astakos.get_user_info(token)
95 72bf812d Christos Stavrakakis
                    request.user_uniq = user_info["uuid"]
96 72bf812d Christos Stavrakakis
                    request.user = user_info
97 72bf812d Christos Stavrakakis
98 72bf812d Christos Stavrakakis
                # Get the response object
99 72bf812d Christos Stavrakakis
                response = func(request, *args, **kwargs)
100 72bf812d Christos Stavrakakis
101 72bf812d Christos Stavrakakis
                # Fill in response variables
102 72bf812d Christos Stavrakakis
                update_response_headers(request, response)
103 72bf812d Christos Stavrakakis
                return response
104 72bf812d Christos Stavrakakis
            except faults.Fault, fault:
105 72bf812d Christos Stavrakakis
                if fault.code >= 500:
106 72bf812d Christos Stavrakakis
                    logger.exception("API ERROR")
107 72bf812d Christos Stavrakakis
                return render_fault(request, fault)
108 72bf812d Christos Stavrakakis
            except:
109 72bf812d Christos Stavrakakis
                logger.exception("Unexpected ERROR")
110 72bf812d Christos Stavrakakis
                fault = faults.InternalServerError("Unexpected ERROR")
111 72bf812d Christos Stavrakakis
                return render_fault(request, fault)
112 72bf812d Christos Stavrakakis
        return wrapper
113 72bf812d Christos Stavrakakis
    return decorator
114 72bf812d Christos Stavrakakis
115 72bf812d Christos Stavrakakis
116 72bf812d Christos Stavrakakis
def get_serialization(request, format_allowed=True):
117 72bf812d Christos Stavrakakis
    """Return the serialization format requested.
118 72bf812d Christos Stavrakakis

119 72bf812d Christos Stavrakakis
    Valid formats are 'json' and 'xml' and 'text'
120 72bf812d Christos Stavrakakis
    """
121 72bf812d Christos Stavrakakis
122 72bf812d Christos Stavrakakis
    if not format_allowed:
123 72bf812d Christos Stavrakakis
        return "text"
124 72bf812d Christos Stavrakakis
125 72bf812d Christos Stavrakakis
    # Try to get serialization from 'format' parameter
126 72bf812d Christos Stavrakakis
    _format = request.GET.get("format")
127 72bf812d Christos Stavrakakis
    if _format:
128 72bf812d Christos Stavrakakis
        if _format == "json":
129 72bf812d Christos Stavrakakis
            return "json"
130 72bf812d Christos Stavrakakis
        elif _format == "xml":
131 72bf812d Christos Stavrakakis
            return "xml"
132 72bf812d Christos Stavrakakis
133 72bf812d Christos Stavrakakis
    # Try to get serialization from path
134 72bf812d Christos Stavrakakis
    path = request.path
135 72bf812d Christos Stavrakakis
    if path.endswith(".json"):
136 72bf812d Christos Stavrakakis
        return "json"
137 72bf812d Christos Stavrakakis
    elif path.endswith(".xml"):
138 72bf812d Christos Stavrakakis
        return "xml"
139 72bf812d Christos Stavrakakis
140 72bf812d Christos Stavrakakis
    for item in request.META.get("HTTP_ACCEPT", "").split(","):
141 72bf812d Christos Stavrakakis
        accept, sep, rest = item.strip().partition(";")
142 72bf812d Christos Stavrakakis
        if accept == "application/json":
143 72bf812d Christos Stavrakakis
            return "json"
144 72bf812d Christos Stavrakakis
        elif accept == "applcation/xml":
145 72bf812d Christos Stavrakakis
            return "xml"
146 72bf812d Christos Stavrakakis
147 72bf812d Christos Stavrakakis
    return "json"
148 72bf812d Christos Stavrakakis
149 72bf812d Christos Stavrakakis
150 72bf812d Christos Stavrakakis
def update_response_headers(request, response):
151 72bf812d Christos Stavrakakis
    if not response.has_header("Content-Type"):
152 72bf812d Christos Stavrakakis
        serialization = request.serialization
153 72bf812d Christos Stavrakakis
        if serialization == "xml":
154 72bf812d Christos Stavrakakis
            response["Content-Type"] = "application/xml; charset=UTF-8"
155 72bf812d Christos Stavrakakis
        elif serialization == "json":
156 72bf812d Christos Stavrakakis
            response["Content-Type"] = "application/json; charset=UTF-8"
157 72bf812d Christos Stavrakakis
        elif serialization == "text":
158 72bf812d Christos Stavrakakis
            response["Content-Type"] = "text/plain; charset=UTF-8"
159 72bf812d Christos Stavrakakis
        else:
160 72bf812d Christos Stavrakakis
            raise ValueError("Unknown serialization format '%s'" %
161 72bf812d Christos Stavrakakis
                             serialization)
162 72bf812d Christos Stavrakakis
163 72bf812d Christos Stavrakakis
    if settings.DEBUG or settings.TEST:
164 72bf812d Christos Stavrakakis
        response["Date"] = format_date_time(time())
165 72bf812d Christos Stavrakakis
166 72bf812d Christos Stavrakakis
    if not response.has_header("Content-Length"):
167 72bf812d Christos Stavrakakis
        response["Content-Length"] = len(response.content)
168 72bf812d Christos Stavrakakis
169 72bf812d Christos Stavrakakis
    cache.add_never_cache_headers(response)
170 72bf812d Christos Stavrakakis
    # Fix Vary and Cache-Control Headers. Issue: #3448
171 72bf812d Christos Stavrakakis
    cache.patch_vary_headers(response, ('X-Auth-Token',))
172 72bf812d Christos Stavrakakis
    cache.patch_cache_control(response, no_cache=True, no_store=True,
173 72bf812d Christos Stavrakakis
                              must_revalidate=True)
174 72bf812d Christos Stavrakakis
175 72bf812d Christos Stavrakakis
176 72bf812d Christos Stavrakakis
def render_fault(request, fault):
177 72bf812d Christos Stavrakakis
    """Render an API fault to an HTTP response."""
178 72bf812d Christos Stavrakakis
    # If running in debug mode add exception information to fault details
179 72bf812d Christos Stavrakakis
    if settings.DEBUG or settings.TEST:
180 72bf812d Christos Stavrakakis
        fault.details = format_exc()
181 72bf812d Christos Stavrakakis
182 72bf812d Christos Stavrakakis
    try:
183 72bf812d Christos Stavrakakis
        serialization = request.serialization
184 72bf812d Christos Stavrakakis
    except AttributeError:
185 72bf812d Christos Stavrakakis
        request.serialization = "json"
186 72bf812d Christos Stavrakakis
        serialization = "json"
187 72bf812d Christos Stavrakakis
188 72bf812d Christos Stavrakakis
    # Serialize the fault data to xml or json
189 72bf812d Christos Stavrakakis
    if serialization == "xml":
190 72bf812d Christos Stavrakakis
        data = render_to_string("fault.xml", {"fault": fault})
191 72bf812d Christos Stavrakakis
    else:
192 72bf812d Christos Stavrakakis
        d = {fault.name: {"code": fault.code,
193 72bf812d Christos Stavrakakis
                          "message": fault.message,
194 72bf812d Christos Stavrakakis
                          "details": fault.details}
195 72bf812d Christos Stavrakakis
            }
196 72bf812d Christos Stavrakakis
        data = json.dumps(d)
197 72bf812d Christos Stavrakakis
198 72bf812d Christos Stavrakakis
    response = HttpResponse(data, status=fault.code)
199 72bf812d Christos Stavrakakis
    update_response_headers(request, response)
200 72bf812d Christos Stavrakakis
    return response
201 72bf812d Christos Stavrakakis
202 72bf812d Christos Stavrakakis
203 72bf812d Christos Stavrakakis
def not_found(request):
204 72bf812d Christos Stavrakakis
    raise faults.BadRequest('Not found.')
205 72bf812d Christos Stavrakakis
206 72bf812d Christos Stavrakakis
207 72bf812d Christos Stavrakakis
def method_not_allowed(request):
208 72bf812d Christos Stavrakakis
    raise faults.BadRequest('Method not allowed')