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