stupid bug
[redakcja.git] / apps / wiki / helpers.py
1 # -*- coding: utf-8 -*-
2 from datetime import datetime
3 from functools import wraps
4
5 from django import http
6 import json
7 from django.utils.functional import Promise
8
9
10 class ExtendedEncoder(json.JSONEncoder):
11
12     def default(self, obj):
13         if isinstance(obj, Promise):
14             return unicode(obj)
15
16         if isinstance(obj, datetime):
17             return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
18
19         return json.JSONEncoder.default(self, obj)
20
21
22 # shortcut for JSON reponses
23 class JSONResponse(http.HttpResponse):
24
25     def __init__(self, data=None, **kwargs):
26         if data is None:
27             data = {}
28         # get rid of mimetype
29         kwargs.pop('mimetype', None)
30
31         data = json.dumps(data, cls=ExtendedEncoder)
32         super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
33
34
35 # return errors
36 class JSONFormInvalid(JSONResponse):
37     def __init__(self, form):
38         super(JSONFormInvalid, self).__init__(form.errors, status=400)
39
40
41 class JSONServerError(JSONResponse):
42     def __init__(self, *args, **kwargs):
43         kwargs['status'] = 500
44         super(JSONServerError, self).__init__(*args, **kwargs)
45
46
47 def ajax_login_required(view):
48     @wraps(view)
49     def authenticated_view(request, *args, **kwargs):
50         if not request.user.is_authenticated():
51             return http.HttpResponse("Login required.", status=401, mimetype="text/plain")
52         return view(request, *args, **kwargs)
53     return authenticated_view
54
55
56 def ajax_require_permission(permission):
57     def decorator(view):
58         @wraps(view)
59         def authorized_view(request, *args, **kwargs):
60             if not request.user.has_perm(permission):
61                 return http.HttpResponse("Access Forbidden.", status=403, mimetype="text/plain")
62             return view(request, *args, **kwargs)
63         return authorized_view
64     return decorator