update requirements
[redakcja.git] / apps / wiki / helpers.py
1 # -*- coding: utf-8 -*-
2 #
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.
5 #
6 from datetime import datetime
7 from functools import wraps
8 import json
9
10 from django import http
11 from django.utils.functional import Promise
12
13
14 class ExtendedEncoder(json.JSONEncoder):
15
16     def default(self, obj):
17         if isinstance(obj, Promise):
18             return unicode(obj)
19
20         if isinstance(obj, datetime):
21             return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
22
23         return json.JSONEncoder.default(self, obj)
24
25
26 # shortcut for JSON reponses
27 class JSONResponse(http.HttpResponse):
28
29     def __init__(self, data={}, **kwargs):
30         # get rid of mimetype
31         kwargs.pop('content_type', None)
32
33         data = json.dumps(data, cls=ExtendedEncoder)
34         super(JSONResponse, self).__init__(data, content_type="application/json", **kwargs)
35
36
37 # return errors
38 class JSONFormInvalid(JSONResponse):
39     def __init__(self, form):
40         super(JSONFormInvalid, self).__init__(form.errors, status=400)
41
42
43 class JSONServerError(JSONResponse):
44     def __init__(self, *args, **kwargs):
45         kwargs['status'] = 500
46         super(JSONServerError, self).__init__(*args, **kwargs)
47
48
49 def ajax_login_required(view):
50     @wraps(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
56
57
58 def ajax_require_permission(permission):
59     def decorator(view):
60         @wraps(view)
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
66     return decorator