1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from datetime import datetime
5 from functools import wraps
7 from django import http
9 from django.utils.functional import Promise
12 class ExtendedEncoder(json.JSONEncoder):
14 def default(self, obj):
15 if isinstance(obj, Promise):
18 if isinstance(obj, datetime):
19 return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
21 return json.JSONEncoder.default(self, obj)
24 # shortcut for JSON reponses
25 class JSONResponse(http.HttpResponse):
27 def __init__(self, data={}, **kwargs):
28 # get rid of content_type
29 kwargs.pop('content_type', None)
31 data = json.dumps(data, cls=ExtendedEncoder)
32 super(JSONResponse, self).__init__(data, content_type="application/json", **kwargs)
36 class JSONFormInvalid(JSONResponse):
37 def __init__(self, form):
38 super(JSONFormInvalid, self).__init__(form.errors, status=400)
41 class JSONServerError(JSONResponse):
42 def __init__(self, *args, **kwargs):
43 kwargs['status'] = 500
44 super(JSONServerError, self).__init__(*args, **kwargs)
47 def ajax_login_required(view):
49 def authenticated_view(request, *args, **kwargs):
50 if not request.user.is_authenticated:
51 return http.HttpResponse("Login required.", status=401, content_type="text/plain")
52 return view(request, *args, **kwargs)
53 return authenticated_view
56 def ajax_require_permission(permission):
59 def authorized_view(request, *args, **kwargs):
60 if not request.user.has_perm(permission):
61 return http.HttpResponse("Access Forbidden.", status=403, content_type="text/plain")
62 return view(request, *args, **kwargs)
63 return authorized_view