Use python logging in install / log cherrypy at right severity
[cascardo/ipsilon.git] / ipsilon / util / endpoint.py
1 # Copyright (C) 2015  Ipsilon Contributors see COPYING for license
2
3 import cherrypy
4 from ipsilon.util.log import Log
5 from ipsilon.util.user import UserSession
6 from urllib import unquote
7 from functools import wraps
8 try:
9     from urlparse import urlparse
10 except ImportError:
11     # pylint: disable=no-name-in-module, import-error
12     from urllib.parse import urlparse
13
14
15 def allow_iframe(func):
16     """
17     Remove the X-Frame-Options and CSP frame-options deny headers.
18     """
19     @wraps(func)
20     def wrapper(*args, **kwargs):
21         result = func(*args, **kwargs)
22         for (header, value) in [
23                 ('X-Frame-Options', 'deny'),
24                 ('Content-Security-Policy', 'frame-options \'deny\'')]:
25             if cherrypy.response.headers.get(header, None) == value:
26                 cherrypy.response.headers.pop(header, None)
27         return result
28
29     return wrapper
30
31
32 class Endpoint(Log):
33     def __init__(self, site):
34         self._site = site
35         self.basepath = cherrypy.config.get('base.mount', "")
36         self.user = None
37         self.default_headers = {
38             'Cache-Control': 'no-cache, no-store, must-revalidate, private',
39             'Pragma': 'no-cache',
40             'Content-Security-Policy': 'frame-options \'deny\'',
41             'X-Frame-Options': 'deny',
42         }
43         self.auth_protect = False
44
45     def get_url(self):
46         return cherrypy.url(relative=False)
47
48     def instance_base_url(self):
49         url = self.get_url()
50         s = urlparse(unquote(url))
51         return '%s://%s%s' % (s.scheme, s.netloc, self.basepath)
52
53     def _check_referer(self, referer, url):
54         r = urlparse(unquote(referer))
55         u = urlparse(unquote(url))
56         if r.scheme != u.scheme:
57             return False
58         if r.netloc != u.netloc:
59             return False
60         if r.path.startswith(self.basepath):
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 self.auth_protect and self.user.is_anonymous:
71             raise cherrypy.HTTPError(401)
72
73         self.debug("method: %s" % cherrypy.request.method)
74         op = getattr(self, cherrypy.request.method, None)
75         if callable(op):
76             # Basic CSRF protection
77             if cherrypy.request.method != 'GET':
78                 url = self.get_url()
79                 if 'referer' not in cherrypy.request.headers:
80                     self.debug("Missing referer in %s request to %s"
81                                % (cherrypy.request.method, url))
82                     raise cherrypy.HTTPError(403)
83                 referer = cherrypy.request.headers['referer']
84                 if not self._check_referer(referer, url):
85                     self.debug("Wrong referer %s in request to %s"
86                                % (referer, url))
87                     raise cherrypy.HTTPError(403)
88             return op(*args, **kwargs)
89         else:
90             op = getattr(self, 'root', None)
91             if callable(op):
92                 return op(*args, **kwargs)
93
94         return self.default(*args, **kwargs)
95
96     def default(self, *args, **kwargs):
97         raise cherrypy.NotFound()
98
99     def add_subtree(self, name, page):
100         self.__dict__[name] = page
101
102     def del_subtree(self, name):
103         del self.__dict__[name]
104
105     exposed = True