Proper fallback from referer to REQUEST_URI
[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.endpoint import Endpoint
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     from urlparse import parse_qs
26 except ImportError:
27     # pylint: disable=no-name-in-module, import-error
28     from urllib.parse import urlparse
29     from urllib.parse import parse_qs
30
31
32 def admin_protect(fn):
33
34     def check(*args, **kwargs):
35         if UserSession().get_user().is_admin:
36             return fn(*args, **kwargs)
37
38         raise cherrypy.HTTPError(403)
39
40     return check
41
42
43 class Page(Endpoint):
44     def __init__(self, site, form=False):
45         super(Page, self).__init__(site)
46         if 'template_env' not in site:
47             raise ValueError('Missing template environment')
48         self._site = site
49         self.basepath = cherrypy.config.get('base.mount', "")
50         self.user = None
51         self._is_form_page = form
52         self.default_headers = dict()
53         self.auth_protect = False
54
55     def get_url(self):
56         return cherrypy.url(relative=False)
57
58     def instance_base_url(self):
59         url = self.get_url()
60         s = urlparse(unquote(url))
61         return '%s://%s%s' % (s.scheme, s.netloc, self.basepath)
62
63     def _check_referer(self, referer, url):
64         r = urlparse(unquote(referer))
65         u = urlparse(unquote(url))
66         if r.scheme != u.scheme:
67             return False
68         if r.netloc != u.netloc:
69             return False
70         if r.path.startswith(self.basepath):
71             return True
72         return False
73
74     def __call__(self, *args, **kwargs):
75         # pylint: disable=star-args
76         cherrypy.response.headers.update(self.default_headers)
77
78         self.user = UserSession().get_user()
79
80         if self.auth_protect and self.user.is_anonymous:
81             raise cherrypy.HTTPError(401)
82
83         if len(args) > 0:
84             op = getattr(self, args[0], None)
85             if callable(op) and getattr(op, 'public_function', None):
86                 return op(*args[1:], **kwargs)
87         else:
88             if self._is_form_page:
89                 self._debug("method: %s" % cherrypy.request.method)
90                 op = getattr(self, cherrypy.request.method, None)
91                 if callable(op):
92                     # Basic CSRF protection
93                     if cherrypy.request.method != 'GET':
94                         url = self.get_url()
95                         if 'referer' not in cherrypy.request.headers:
96                             self._debug("Missing referer in %s request to %s"
97                                         % (cherrypy.request.method, url))
98                             raise cherrypy.HTTPError(403)
99                         referer = cherrypy.request.headers['referer']
100                         if not self._check_referer(referer, url):
101                             self._debug("Wrong referer %s in request to %s"
102                                         % (referer, url))
103                             raise cherrypy.HTTPError(403)
104                     return op(*args, **kwargs)
105             else:
106                 op = getattr(self, 'root', None)
107                 if callable(op):
108                     return op(*args, **kwargs)
109
110         return self.default(*args, **kwargs)
111
112     def _template_model(self):
113         model = dict()
114         model['basepath'] = self.basepath
115         model['title'] = 'IPSILON'
116         model['user'] = self.user
117         return model
118
119     def _template(self, *args, **kwargs):
120         # pylint: disable=star-args
121         t = self._site['template_env'].get_template(args[0])
122         m = self._template_model()
123         m.update(kwargs)
124         return t.render(**m)
125
126     def default(self, *args, **kwargs):
127         raise cherrypy.NotFound()
128
129     def add_subtree(self, name, page):
130         self.__dict__[name] = page
131
132     def del_subtree(self, name):
133         del self.__dict__[name]
134
135     def get_valid_transaction(self, provider, **kwargs):
136         try:
137             t = Transaction(provider)
138             # Try with kwargs first
139             tid = t.find_tid(kwargs)
140             if not tid:
141                 # If no TID yet See if we have it in a referer or in the
142                 # environment in the REDIRECT_URL
143                 url = None
144                 if 'referer' in cherrypy.request.headers:
145                     url = cherrypy.request.headers['referer']
146                     r = urlparse(unquote(url))
147                     if r.query:
148                         tid = t.find_tid(parse_qs(r.query))
149                 if not tid and 'REQUEST_URI' in cherrypy.request.wsgi_environ:
150                     url = cherrypy.request.wsgi_environ['REQUEST_URI']
151                     r = urlparse(unquote(url))
152                     if r.query:
153                         tid = t.find_tid(parse_qs(r.query))
154                 if not tid:
155                     t.create_tid()
156             return t
157         except ValueError:
158             msg = 'Transaction expired, or cookies not available'
159             raise cherrypy.HTTPError(401, msg)
160
161     exposed = True