root / snf-django-lib / snf_django / lib / api / __init__.py @ d0d9a3f5
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, 'json')
|
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 |
logger=logger) |
110 |
user_info = astakos.get_user_info(token) |
111 |
request.user_uniq = user_info["uuid"]
|
112 |
request.user = user_info |
113 |
|
114 |
# Get the response object
|
115 |
response = func(request, *args, **kwargs) |
116 |
|
117 |
# Fill in response variables
|
118 |
update_response_headers(request, response) |
119 |
return response
|
120 |
except faults.Fault, fault:
|
121 |
if fault.code >= 500: |
122 |
logger.exception("API ERROR")
|
123 |
return render_fault(request, fault)
|
124 |
except AstakosClientException as err: |
125 |
fault = faults.Fault(message=err.message, |
126 |
details=err.details, |
127 |
code=err.status) |
128 |
if fault.code >= 500: |
129 |
logger.exception("Astakos ERROR")
|
130 |
return render_fault(request, fault)
|
131 |
except:
|
132 |
logger.exception("Unexpected ERROR")
|
133 |
fault = faults.InternalServerError("Unexpected error")
|
134 |
return render_fault(request, fault)
|
135 |
return csrf.csrf_exempt(wrapper)
|
136 |
return decorator
|
137 |
|
138 |
|
139 |
def get_serialization(request, format_allowed=True, default_serialization="json"): |
140 |
"""Return the serialization format requested.
|
141 |
|
142 |
Valid formats are 'json' and 'xml' and 'text'
|
143 |
"""
|
144 |
|
145 |
if not format_allowed: |
146 |
return "text" |
147 |
|
148 |
# Try to get serialization from 'format' parameter
|
149 |
_format = request.GET.get("format")
|
150 |
if _format:
|
151 |
if _format == "json": |
152 |
return "json" |
153 |
elif _format == "xml": |
154 |
return "xml" |
155 |
|
156 |
# Try to get serialization from path
|
157 |
path = request.path |
158 |
if path.endswith(".json"): |
159 |
return "json" |
160 |
elif path.endswith(".xml"): |
161 |
return "xml" |
162 |
|
163 |
for item in request.META.get("HTTP_ACCEPT", "").split(","): |
164 |
accept, sep, rest = item.strip().partition(";")
|
165 |
if accept == "application/json": |
166 |
return "json" |
167 |
elif accept == "application/xml": |
168 |
return "xml" |
169 |
|
170 |
return default_serialization
|
171 |
|
172 |
|
173 |
def update_response_headers(request, response): |
174 |
if not getattr(response, "override_serialization", False): |
175 |
serialization = request.serialization |
176 |
if serialization == "xml": |
177 |
response["Content-Type"] = "application/xml; charset=UTF-8" |
178 |
elif serialization == "json": |
179 |
response["Content-Type"] = "application/json; charset=UTF-8" |
180 |
elif serialization == "text": |
181 |
response["Content-Type"] = "text/plain; charset=UTF-8" |
182 |
else:
|
183 |
raise ValueError("Unknown serialization format '%s'" % |
184 |
serialization) |
185 |
|
186 |
if settings.DEBUG or getattr(settings, "TEST", False): |
187 |
response["Date"] = format_date_time(time())
|
188 |
|
189 |
if not response.has_header("Content-Length"): |
190 |
response["Content-Length"] = len(response.content) |
191 |
|
192 |
cache.add_never_cache_headers(response) |
193 |
# Fix Vary and Cache-Control Headers. Issue: #3448
|
194 |
cache.patch_vary_headers(response, ('X-Auth-Token',))
|
195 |
cache.patch_cache_control(response, no_cache=True, no_store=True, |
196 |
must_revalidate=True)
|
197 |
|
198 |
|
199 |
def render_fault(request, fault): |
200 |
"""Render an API fault to an HTTP response."""
|
201 |
# If running in debug mode add exception information to fault details
|
202 |
if settings.DEBUG or getattr(settings, "TEST", False): |
203 |
fault.details = format_exc() |
204 |
|
205 |
try:
|
206 |
serialization = request.serialization |
207 |
except AttributeError: |
208 |
request.serialization = "json"
|
209 |
serialization = "json"
|
210 |
|
211 |
# Serialize the fault data to xml or json
|
212 |
if serialization == "xml": |
213 |
data = render_to_string("fault.xml", {"fault": fault}) |
214 |
else:
|
215 |
d = {fault.name: {"code": fault.code,
|
216 |
"message": fault.message,
|
217 |
"details": fault.details}}
|
218 |
data = json.dumps(d) |
219 |
|
220 |
response = HttpResponse(data, status=fault.code) |
221 |
update_response_headers(request, response) |
222 |
return response
|
223 |
|
224 |
|
225 |
@api_method(token_required=False, user_required=False) |
226 |
def api_endpoint_not_found(request): |
227 |
raise faults.BadRequest("API endpoint not found") |
228 |
|
229 |
|
230 |
@api_method(token_required=False, user_required=False) |
231 |
def api_method_not_allowed(request): |
232 |
raise faults.BadRequest('Method not allowed') |
233 |
|
234 |
|
235 |
def allow_jsonp(key='callback'): |
236 |
"""
|
237 |
Wrapper to enable jsonp responses.
|
238 |
"""
|
239 |
def wrapper(func): |
240 |
def view_wrapper(request, *args, **kwargs): |
241 |
response = func(request, *args, **kwargs) |
242 |
if 'content-type' in response._headers and \ |
243 |
response._headers['content-type'][1] == 'application/json': |
244 |
callback_name = request.GET.get(key, None)
|
245 |
if callback_name:
|
246 |
response.content = "%s(%s)" % (callback_name,
|
247 |
response.content) |
248 |
response._headers['content-type'] = ('Content-Type', |
249 |
'text/javascript')
|
250 |
return response
|
251 |
return view_wrapper
|
252 |
return wrapper
|