simplify SearchEntry instantiation
[mygpo.git] / mygpo / decorators.py
blob3c9530e724ef3779448bcdef6f3302f0507c48eb
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 random
26 import string
27 import gc
29 def requires_token(object, action, denied_template=None):
30 """
31 returns a decorator that checks if the security token in the 'token' GET
32 parameter matches the requires token for the resource. The resource is indicated by
33 * the username parameter passed to the decorated function
34 * object and action passed to this method
36 The decorated method is returned, if
37 * no token is required for the resource
38 * the token in the 'token' GET parameter matches the required token
40 If the passed token does not match
41 * the denied_template is rendered and returned if given
42 * HttpResponseForbidden is returned, if denied_template is not given
43 """
44 def decorator(fn):
45 def tmp(request, username, *args, **kwargs):
47 user = get_object_or_404(User, username=username)
48 token, c = SecurityToken.objects.get_or_create(user=user, object=object, action=action,
49 defaults = {'token': "".join(random.sample(string.letters+string.digits, 32))})
51 u_token = request.GET.get('token', '')
53 if token.token == '' or token.token == u_token:
54 return fn(request, username, *args, **kwargs)
56 else:
57 if denied_template:
58 return render_to_response(denied_template, {
59 'other_user': user
60 }, context_instance=RequestContext(request))
62 else:
63 return HttpResponseForbidden()
65 return tmp
66 return decorator
69 def manual_gc(view):
70 def tmp(*args, **kwargs):
71 res = view(*args, **kwargs)
72 gc.collect()
73 return res
75 return tmp
78 def allowed_methods(methods):
79 def decorator(fn):
80 def tmp(request, *args, **kwargs):
81 if request.method in methods:
82 return fn(request, *args, **kwargs)
83 else:
84 return HttpResponseNotAllowed(methods)
86 return tmp
88 return decorator