Commit 2857c5e0 authored by CAMPION Sebastien's avatar CAMPION Sebastien
Browse files

Merge branch 'json-http-errors' into 'django'

return API django-generated http errors in the JSON format

See merge request !139
parents 8f01d79f b761d29e
Pipeline #44095 failed with stage
in 1 minute and 4 seconds
from django.conf import settings
from django.contrib.auth.mixins import UserPassesTestMixin
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.http import HttpResponse, JsonResponse
from .models import Job
from .helpers import get_request_user
......@@ -34,3 +34,9 @@ class JobAuthMixin(UserPassesTestMixin):
self.raise_exception = True # to return a 403
job = Job.objects.filter(pk=self.kwargs['pk']).first()
return user.is_superuser or user == getattr(job, "user", ())
def handle_no_permission(self):
if not self.raise_exception and self.request.path_info.startswith("/api/"):
return JsonResponse({"error": "401 Unauthorized"}, status=401)
return super().handle_no_permission()
......@@ -36,8 +36,11 @@ See also:
This url file depends on the main `urls.py` file located in the `config`
folder at the root of the Django application.
"""
from functools import partial
# Third party import
from django.conf.urls import url, include
import django.conf.urls
import django.views.defaults
# Local import
from . import views
......@@ -84,3 +87,15 @@ urlpatterns = [
url(r'^webapps/(?P<pk>\d+)/?$', views.LegacyWebappDetail.as_view()),
url(r'^app/(?P<slug>[\w-]+)/?$', views.LegacyWebappDetail.as_view()),
]
# error handlers
# NOTE: the 404 and 500 handlers are ignored when settings.DEBUG is enabled
django.conf.urls.handler400 = partial(views.error_handler,
400, "Bad Request", django.views.defaults.bad_request)
django.conf.urls.handler403 = partial(views.error_handler,
403, "Forbidden", django.views.defaults.permission_denied)
django.conf.urls.handler404 = partial(views.error_handler,
404, "Not Found", django.views.defaults.page_not_found)
django.conf.urls.handler500 = partial(views.error_handler,
500, "Server Error", django.views.defaults.server_error)
......@@ -87,6 +87,21 @@ from .templatetags.converters import status_icon
# Start logger
log = logging.getLogger('allgo')
def error_handler(status, reason, default, request, exception=None):
"""Generic error handler
Since django is unable to handle per-app error handlers, we have to define
global ones.
The behaviour of this view is to generate a json-formatted message
{"error": "something"} when the url starts with /api/, otherwise it just
uses django's default error handler.
"""
if request.path_info.startswith("/api/"):
return JsonResponse({"error": "%d %s" % (status, reason)}, status=status)
else:
return default(request, exception)
class IndexDetail(TemplateView):
"""Home view
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment