root / snf-django-lib / snf_django / lib / api / __init__.py @ f089ffca
History | View | Annotate | Download (9.5 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 |
serializations=None, strict_serlization=False): |
66 |
"""Decorator function for views that implement an API method."""
|
67 |
if not logger: |
68 |
logger = log |
69 |
|
70 |
serializations = serializations or ['json', 'xml'] |
71 |
|
72 |
def decorator(func): |
73 |
@wraps(func)
|
74 |
def wrapper(request, *args, **kwargs): |
75 |
try:
|
76 |
# Get the requested serialization format
|
77 |
serialization = get_serialization( |
78 |
request, format_allowed, serializations[0])
|
79 |
|
80 |
# If guessed serialization is not supported, fallback to
|
81 |
# the default serialization or return an API error in case
|
82 |
# strict serialization flag is set.
|
83 |
if not serialization in serializations: |
84 |
if strict_serlization:
|
85 |
raise faults.BadRequest(("%s serialization not " |
86 |
"supported") % serialization)
|
87 |
serialization = serializations[0]
|
88 |
request.serialization = serialization |
89 |
|
90 |
# Check HTTP method
|
91 |
if http_method and request.method != http_method: |
92 |
raise faults.BadRequest("Method not allowed") |
93 |
|
94 |
# Get authentication token
|
95 |
request.x_auth_token = None
|
96 |
if token_required or user_required: |
97 |
token = get_token(request) |
98 |
if not token: |
99 |
msg = "Access denied. No authentication token"
|
100 |
raise faults.Unauthorized(msg)
|
101 |
request.x_auth_token = token |
102 |
|
103 |
# Authenticate
|
104 |
if user_required:
|
105 |
assert(token_required), "Can not get user without token" |
106 |
astakos = astakos_url or settings.ASTAKOS_BASE_URL
|
107 |
astakos = AstakosClient(astakos, |
108 |
use_pool=True,
|
109 |
retry=2,
|
110 |
logger=logger) |
111 |
user_info = astakos.get_user_info(token) |
112 |
request.user_uniq = user_info["uuid"]
|
113 |
request.user = user_info |
114 |
|
115 |
# Get the response object
|
116 |
response = func(request, *args, **kwargs) |
117 |
|
118 |
# Fill in response variables
|
119 |
update_response_headers(request, response) |
120 |
return response
|
121 |
except faults.Fault, fault:
|
122 |
if fault.code >= 500: |
123 |
logger.exception("API ERROR")
|
124 |
return render_fault(request, fault)
|
125 |
except AstakosClientException as err: |
126 |
fault = faults.Fault(message=err.message, |
127 |
details=err.details, |
128 |
code=err.status) |
129 |
if fault.code >= 500: |
130 |
logger.exception("Astakos ERROR")
|
131 |
return render_fault(request, fault)
|
132 |
except:
|
133 |
logger.exception("Unexpected ERROR")
|
134 |
fault = faults.InternalServerError("Unexpected error")
|
135 |
return render_fault(request, fault)
|
136 |
return csrf.csrf_exempt(wrapper)
|
137 |
return decorator
|
138 |
|
139 |
|
140 |
def get_serialization(request, format_allowed=True, default_serialization="json"): |
141 |
"""Return the serialization format requested.
|
142 |
|
143 |
Valid formats are 'json' and 'xml' and 'text'
|
144 |
"""
|
145 |
|
146 |
if not format_allowed: |
147 |
return "text" |
148 |
|
149 |
# Try to get serialization from 'format' parameter
|
150 |
_format = request.GET.get("format")
|
151 |
if _format:
|
152 |
if _format == "json": |
153 |
return "json" |
154 |
elif _format == "xml": |
155 |
return "xml" |
156 |
|
157 |
# Try to get serialization from path
|
158 |
path = request.path |
159 |
if path.endswith(".json"): |
160 |
return "json" |
161 |
elif path.endswith(".xml"): |
162 |
return "xml" |
163 |
|
164 |
for item in request.META.get("HTTP_ACCEPT", "").split(","): |
165 |
accept, sep, rest = item.strip().partition(";")
|
166 |
if accept == "application/json": |
167 |
return "json" |
168 |
elif accept == "application/xml": |
169 |
return "xml" |
170 |
|
171 |
return default_serialization
|
172 |
|
173 |
|
174 |
def update_response_headers(request, response): |
175 |
if not getattr(response, "override_serialization", False): |
176 |
serialization = request.serialization |
177 |
if serialization == "xml": |
178 |
response["Content-Type"] = "application/xml; charset=UTF-8" |
179 |
elif serialization == "json": |
180 |
response["Content-Type"] = "application/json; charset=UTF-8" |
181 |
elif serialization == "text": |
182 |
response["Content-Type"] = "text/plain; charset=UTF-8" |
183 |
else:
|
184 |
raise ValueError("Unknown serialization format '%s'" % |
185 |
serialization) |
186 |
|
187 |
if settings.DEBUG or getattr(settings, "TEST", False): |
188 |
response["Date"] = format_date_time(time())
|
189 |
|
190 |
if not response.has_header("Content-Length"): |
191 |
response["Content-Length"] = len(response.content) |
192 |
|
193 |
cache.add_never_cache_headers(response) |
194 |
# Fix Vary and Cache-Control Headers. Issue: #3448
|
195 |
cache.patch_vary_headers(response, ('X-Auth-Token',))
|
196 |
cache.patch_cache_control(response, no_cache=True, no_store=True, |
197 |
must_revalidate=True)
|
198 |
|
199 |
|
200 |
def render_fault(request, fault): |
201 |
"""Render an API fault to an HTTP response."""
|
202 |
# If running in debug mode add exception information to fault details
|
203 |
if settings.DEBUG or getattr(settings, "TEST", False): |
204 |
fault.details = format_exc() |
205 |
|
206 |
try:
|
207 |
serialization = request.serialization |
208 |
except AttributeError: |
209 |
request.serialization = "json"
|
210 |
serialization = "json"
|
211 |
|
212 |
# Serialize the fault data to xml or json
|
213 |
if serialization == "xml": |
214 |
data = render_to_string("fault.xml", {"fault": fault}) |
215 |
else:
|
216 |
d = {fault.name: {"code": fault.code,
|
217 |
"message": fault.message,
|
218 |
"details": fault.details}}
|
219 |
data = json.dumps(d) |
220 |
|
221 |
response = HttpResponse(data, status=fault.code) |
222 |
update_response_headers(request, response) |
223 |
return response
|
224 |
|
225 |
|
226 |
@api_method(token_required=False, user_required=False) |
227 |
def api_endpoint_not_found(request): |
228 |
raise faults.BadRequest("API endpoint not found") |
229 |
|
230 |
|
231 |
@api_method(token_required=False, user_required=False) |
232 |
def api_method_not_allowed(request): |
233 |
raise faults.BadRequest('Method not allowed') |
234 |
|
235 |
|
236 |
def allow_jsonp(key='callback'): |
237 |
"""
|
238 |
Wrapper to enable jsonp responses.
|
239 |
"""
|
240 |
def wrapper(func): |
241 |
def view_wrapper(request, *args, **kwargs): |
242 |
response = func(request, *args, **kwargs) |
243 |
if 'content-type' in response._headers and \ |
244 |
response._headers['content-type'][1] == 'application/json': |
245 |
callback_name = request.GET.get(key, None)
|
246 |
if callback_name:
|
247 |
response.content = "%s(%s)" % (callback_name,
|
248 |
response.content) |
249 |
response._headers['content-type'] = ('Content-Type', |
250 |
'text/javascript')
|
251 |
return response
|
252 |
return view_wrapper
|
253 |
return wrapper
|