Cosmetic changes: removed an unused import, stripped some trailing whitespace.
[mediagoblin.git] / mediagoblin / decorators.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 Free Software Foundation, Inc
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17
18 from webob import exc
19
20 from mediagoblin.db.util import ObjectId
21
22
23 def _make_safe(decorator, original):
24 """
25 Copy the function data from the old function to the decorator.
26 """
27 decorator.__name__ = original.__name__
28 decorator.__dict__ = original.__dict__
29 decorator.__doc__ = original.__doc__
30 return decorator
31
32
33 def require_active_login(controller):
34 """
35 Require an active login from the user.
36 """
37 def new_controller_func(request, *args, **kwargs):
38 if not request.user or not request.user.get('status') == u'active':
39 # TODO: Indicate to the user that they were redirected
40 # here because an *active* user is required.
41 return exc.HTTPFound(
42 location="%s?next=%s" % (
43 request.urlgen("mediagoblin.auth.login"),
44 request.path_info))
45
46 return controller(request, *args, **kwargs)
47
48 return _make_safe(new_controller_func, controller)
49
50
51 def uses_pagination(controller):
52 """
53 Check request GET 'page' key for wrong values
54 """
55 def wrapper(request, *args, **kwargs):
56 try:
57 page = int(request.GET.get('page', 1))
58 if page < 0:
59 return exc.HTTPNotFound()
60 except ValueError:
61 return exc.HTTPNotFound()
62
63 return controller(request, page=page, *args, **kwargs)
64
65 return _make_safe(wrapper, controller)
66
67
68 def get_media_entry(controller):
69 """
70 Pass in a MediaEntry based off of a url component
71 """
72 def wrapper(request, *args, **kwargs):
73 media = request.db.MediaEntry.find_one(
74 {'slug': request.matchdict['media'],
75 'state': 'processed'})
76
77 # no media via slug? Grab it via ObjectId
78 if not media:
79 media = request.db.MediaEntry.find_one(
80 {'_id': ObjectId(request.matchdict['media']),
81 'state': 'processed'})
82
83 # Still no media? Okay, 404.
84 if not media:
85 return exc.HTTPNotFound()
86
87 return controller(request, media=media, *args, **kwargs)
88
89 return _make_safe(wrapper, controller)