l10n: Beginning the French translation
[mygpo.git] / mygpo / decorators.py
blobc5b8c0facde852c3d3a3b691a92a740100fdf93c
1 # -*- coding: utf-8 -*-
3 # gPodder - A media aggregator and podcast client
4 # Copyright (c) 2005-2009 Thomas Perl and the gPodder Team
6 # gPodder is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # gPodder is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 from django.shortcuts import render_to_response, get_object_or_404
21 from django.template import RequestContext
22 from mygpo.web.models import SecurityToken
23 from django.contrib.auth.models import User
24 from django.http import HttpResponseForbidden, HttpResponseNotAllowed
25 import gc
27 def requires_token(object, action, denied_template=None):
28 """
29 returns a decorator that checks if the security token in the 'token' GET
30 parameter matches the requires token for the resource. The resource is indicated by
31 * the username parameter passed to the decorated function
32 * object and action passed to this method
34 The decorated method is returned, if
35 * no token is required for the resource
36 * the token in the 'token' GET parameter matches the required token
38 If the passed token does not match
39 * the denied_template is rendered and returned if given
40 * HttpResponseForbidden is returned, if denied_template is not given
41 """
42 def decorator(fn):
43 def tmp(request, username, *args, **kwargs):
45 user = get_object_or_404(User, username=username)
46 token, c = SecurityToken.objects.get_or_create(user=user, object=object, action=action)
48 u_token = request.GET.get('token', '')
50 if token.token == '' or token.token == u_token:
51 return fn(request, username, *args, **kwargs)
53 else:
54 if denied_template:
55 return render_to_response(denied_template, {
56 'other_user': user
57 }, context_instance=RequestContext(request))
59 else:
60 return HttpResponseForbidden()
62 return tmp
63 return decorator
66 def manual_gc(view):
67 def tmp(*args, **kwargs):
68 res = view(*args, **kwargs)
69 gc.collect()
70 return res
72 return tmp
75 def allowed_methods(methods):
76 def decorator(fn):
77 def tmp(request, *args, **kwargs):
78 if request.method in methods:
79 return fn(request, *args, **kwargs)
80 else:
81 return HttpResponseNotAllowed(methods)
83 return tmp
85 return decorator