18b5be2d50032cbdc45d80b239e8e0c820ccafff
[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.user import User
21 import cherrypy
22
23
24 def protect():
25     if cherrypy.request.login:
26         user = cherrypy.session.get('user', None)
27         if user == cherrypy.request.login:
28             return
29         else:
30             cherrypy.session.regenerate()
31             cherrypy.session['user'] = cherrypy.request.login
32
33
34 class Page(object):
35     def __init__(self, template_env):
36         self._env = template_env
37         self.basepath = cherrypy.config.get('base.mount', "")
38         self.username = None
39         self.user = None
40
41     def __call__(self, *args, **kwargs):
42         # pylint: disable=star-args
43         self.username = cherrypy.session.get('user', None)
44         self.user = User(self.username)
45
46         if len(args) > 0:
47             op = getattr(self, args[0], None)
48             if callable(op) and getattr(self, args[0]+'.exposed', None):
49                 return op(args[1:], **kwargs)
50         else:
51             op = getattr(self, 'root', None)
52             if callable(op):
53                 return op(**kwargs)
54
55         return self.default(*args, **kwargs)
56
57     def _template(self, *args, **kwargs):
58         t = self._env.get_template(args[0])
59         return t.render(basepath=self.basepath, user=self.user, **kwargs)
60
61     def default(self, *args, **kwargs):
62         raise cherrypy.HTTPError(404)
63
64     exposed = True