Enhancements for wikidata imports.
[redakcja.git] / src / wiki / helpers.py
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.
3 #
4 from datetime import datetime
5 from functools import wraps
6
7 from django import http
8 import json
9 from django.utils.functional import Promise
10
11
12 class ExtendedEncoder(json.JSONEncoder):
13
14     def default(self, obj):
15         if isinstance(obj, Promise):
16             return str(obj)
17
18         if isinstance(obj, datetime):
19             return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
20
21         return json.JSONEncoder.default(self, obj)
22
23
24 # shortcut for JSON reponses
25 class JSONResponse(http.HttpResponse):
26
27     def __init__(self, data={}, **kwargs):
28         # get rid of content_type
29         kwargs.pop('content_type', None)
30
31         data = json.dumps(data, cls=ExtendedEncoder)
32         super(JSONResponse, self).__init__(data, content_type="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, content_type="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, content_type="text/plain")
62             return view(request, *args, **kwargs)
63         return authorized_view
64     return decorator