1 # -*- coding: utf-8 -*-
3 # This file is part of MIL/PEER, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from datetime import datetime
7 from functools import wraps
10 from django import http
11 from django.utils.functional import Promise
14 class ExtendedEncoder(json.JSONEncoder):
16 def default(self, obj):
17 if isinstance(obj, Promise):
20 if isinstance(obj, datetime):
21 return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
23 return json.JSONEncoder.default(self, obj)
26 # shortcut for JSON reponses
27 class JSONResponse(http.HttpResponse):
29 def __init__(self, data={}, **kwargs):
31 kwargs.pop('content_type', None)
33 data = json.dumps(data, cls=ExtendedEncoder)
34 super(JSONResponse, self).__init__(data, content_type="application/json", **kwargs)
38 class JSONFormInvalid(JSONResponse):
39 def __init__(self, form):
40 super(JSONFormInvalid, self).__init__(form.errors, status=400)
43 class JSONServerError(JSONResponse):
44 def __init__(self, *args, **kwargs):
45 kwargs['status'] = 500
46 super(JSONServerError, self).__init__(*args, **kwargs)
49 def ajax_login_required(view):
51 def authenticated_view(request, *args, **kwargs):
52 if not request.user.is_authenticated():
53 return http.HttpResponse("Login required.", status=401, content_type="text/plain")
54 return view(request, *args, **kwargs)
55 return authenticated_view
58 def ajax_require_permission(permission):
61 def authorized_view(request, *args, **kwargs):
62 if not request.user.has_perm(permission):
63 return http.HttpResponse("Access Forbidden.", status=403, content_type="text/plain")
64 return view(request, *args, **kwargs)
65 return authorized_view