Handle invalid/expired transactions gracefully
[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 ipsilon.util.trans import Transaction
23 from urllib import unquote
24 import cherrypy
25
26
27 def admin_protect(fn):
28
29     def check(*args, **kwargs):
30         if UserSession().get_user().is_admin:
31             return fn(*args, **kwargs)
32
33         raise cherrypy.HTTPError(403)
34
35     return check
36
37
38 class Page(Log):
39     def __init__(self, site, form=False):
40         if 'template_env' not in site:
41             raise ValueError('Missing template environment')
42         self._site = site
43         self.basepath = cherrypy.config.get('base.mount', "")
44         self.user = None
45         self._is_form_page = form
46         self.default_headers = dict()
47         self.auth_protect = False
48
49     def _compare_urls(self, url1, url2):
50         u1 = unquote(url1)
51         u2 = unquote(url2)
52         if u1 == u2:
53             return True
54         return False
55
56     def __call__(self, *args, **kwargs):
57         # pylint: disable=star-args
58         cherrypy.response.headers.update(self.default_headers)
59
60         self.user = UserSession().get_user()
61
62         if self.auth_protect and self.user.is_anonymous:
63             raise cherrypy.HTTPError(401)
64
65         if len(args) > 0:
66             op = getattr(self, args[0], None)
67             if callable(op) and getattr(op, 'public_function', None):
68                 return op(*args[1:], **kwargs)
69         else:
70             if self._is_form_page:
71                 self._debug("method: %s" % cherrypy.request.method)
72                 op = getattr(self, cherrypy.request.method, None)
73                 if callable(op):
74                     # Basic CSRF protection
75                     if cherrypy.request.method != 'GET':
76                         url = cherrypy.url(relative=False)
77                         if 'referer' not in cherrypy.request.headers:
78                             self._debug("Missing referer in %s request to %s"
79                                         % (cherrypy.request.method, url))
80                             raise cherrypy.HTTPError(403)
81                         referer = cherrypy.request.headers['referer']
82                         if not self._compare_urls(referer, url):
83                             self._debug("Wrong referer %s in request to %s"
84                                         % (referer, url))
85                             raise cherrypy.HTTPError(403)
86                     return op(*args, **kwargs)
87             else:
88                 op = getattr(self, 'root', None)
89                 if callable(op):
90                     return op(*args, **kwargs)
91
92         return self.default(*args, **kwargs)
93
94     def _template_model(self):
95         model = dict()
96         model['basepath'] = self.basepath
97         model['title'] = 'IPSILON'
98         model['user'] = self.user
99         return model
100
101     def _template(self, *args, **kwargs):
102         # pylint: disable=star-args
103         t = self._site['template_env'].get_template(args[0])
104         m = self._template_model()
105         m.update(kwargs)
106         return t.render(**m)
107
108     def default(self, *args, **kwargs):
109         raise cherrypy.NotFound()
110
111     def add_subtree(self, name, page):
112         self.__dict__[name] = page
113
114     def del_subtree(self, name):
115         del self.__dict__[name]
116
117     def get_valid_transaction(self, provider, **kwargs):
118         try:
119             return Transaction(provider, **kwargs)
120         except ValueError:
121             msg = 'Transaction expired, or cookies not available'
122             raise cherrypy.HTTPError(401, msg)
123
124     exposed = True