Add way to set default headers
[cascardo/ipsilon.git] / ipsilon / util / page.py
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2013  Simo Sorce <simo@redhat.com>
4 #
5 # see file 'COPYING' for use and warranty information
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 from ipsilon.util.log import Log
21 from ipsilon.util.user import UserSession
22 from urllib import unquote
23 import cherrypy
24
25
26 def admin_protect(fn):
27
28     def check(*args, **kwargs):
29         if UserSession().get_user().is_admin:
30             return fn(*args, **kwargs)
31
32         raise cherrypy.HTTPError(403)
33
34     return check
35
36
37 def auth_protect(fn):
38     def check(self, *args, **kwargs):
39         if UserSession().get_user().is_anonymous:
40             raise cherrypy.HTTPRedirect(self.basepath)
41         else:
42             return fn(self, *args, **kwargs)
43
44     return check
45
46
47 class Page(Log):
48     def __init__(self, site, form=False):
49         if 'template_env' not in site:
50             raise ValueError('Missing template environment')
51         self._site = site
52         self.basepath = cherrypy.config.get('base.mount', "")
53         self.user = None
54         self._is_form_page = form
55         self.default_headers = dict()
56
57     def _compare_urls(self, url1, url2):
58         u1 = unquote(url1)
59         u2 = unquote(url2)
60         if u1 == u2:
61             return True
62         return False
63
64     def __call__(self, *args, **kwargs):
65         # pylint: disable=star-args
66         cherrypy.response.headers.update(self.default_headers)
67
68         self.user = UserSession().get_user()
69
70         if len(args) > 0:
71             op = getattr(self, args[0], None)
72             if callable(op) and getattr(op, 'public_function', None):
73                 return op(*args[1:], **kwargs)
74         else:
75             if self._is_form_page:
76                 self._debug("method: %s" % cherrypy.request.method)
77                 op = getattr(self, cherrypy.request.method, None)
78                 if callable(op):
79                     # Basic CSRF protection
80                     if cherrypy.request.method != 'GET':
81                         url = cherrypy.url(relative=False)
82                         if 'referer' not in cherrypy.request.headers:
83                             self._debug("Missing referer in %s request to %s"
84                                         % (cherrypy.request.method, url))
85                             raise cherrypy.HTTPError(403)
86                         referer = cherrypy.request.headers['referer']
87                         if not self._compare_urls(referer, url):
88                             self._debug("Wrong referer %s in request to %s"
89                                         % (referer, url))
90                             raise cherrypy.HTTPError(403)
91                     return op(*args, **kwargs)
92             else:
93                 op = getattr(self, 'root', None)
94                 if callable(op):
95                     return op(*args, **kwargs)
96
97         return self.default(*args, **kwargs)
98
99     def _template_model(self):
100         model = dict()
101         model['basepath'] = self.basepath
102         model['title'] = 'IPSILON'
103         model['user'] = self.user
104         return model
105
106     def _template(self, *args, **kwargs):
107         # pylint: disable=star-args
108         t = self._site['template_env'].get_template(args[0])
109         m = self._template_model()
110         m.update(kwargs)
111         return t.render(**m)
112
113     def default(self, *args, **kwargs):
114         raise cherrypy.NotFound()
115
116     def add_subtree(self, name, page):
117         self.__dict__[name] = page
118
119     def del_subtree(self, name):
120         del self.__dict__[name]
121
122     exposed = True