28972374433aa54b6c738f08bdeb0350a04c5036
[cascardo/ipsilon.git] / ipsilon / admin / common.py
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2014  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.data import Store
21 from ipsilon.util.page import Page
22 from ipsilon.util.page import admin_protect
23 from ipsilon.util.plugin import PluginObject
24 import cherrypy
25 from ipsilon.login.common import FACILITY as LOGIN_FACILITY
26
27
28 class LoginPluginPage(Page):
29
30     def __init__(self, obj, site, baseurl):
31         super(LoginPluginPage, self).__init__(site)
32         self._obj = obj
33         self.url = '%s/%s' % (baseurl, obj.name)
34
35         # Get the defaults
36         self.plugin_config = obj.get_config_desc()
37         if not self.plugin_config:
38             self.plugin_config = []
39
40         # Now overlay the actual config
41         for option in self.plugin_config:
42             self.plugin_config[option][2] = obj.get_config_value(option)
43
44     @admin_protect
45     def GET(self, *args, **kwargs):
46         return self._template('admin/login_plugin.html',
47                               title='%s plugin' % self._obj.name,
48                               name='admin_login_%s_form' % self._obj.name,
49                               action=self.url,
50                               options=self.plugin_config)
51
52     @admin_protect
53     def POST(self, *args, **kwargs):
54
55         message = "Nothing was modified."
56         message_type = "info"
57         new_values = dict()
58
59         for key, value in kwargs.iteritems():
60             if key in self.plugin_config:
61                 if value != self.plugin_config[key][2]:
62                     cherrypy.log.error("Storing [%s]: %s = %s" %
63                                        (self._obj.name, key, value))
64                     new_values[key] = value
65
66         if len(new_values) != 0:
67             # First we try to save in the database
68             try:
69                 store = Store()
70                 store.save_plugin_config(LOGIN_FACILITY,
71                                          self._obj.name, new_values)
72                 message = "New configuration saved."
73                 message_type = "success"
74             except Exception:  # pylint: disable=broad-except
75                 message = "Failed to save data!"
76                 message_type = "error"
77
78             # And only if it succeeds we change the live object
79             for name, value in new_values.items():
80                 self._obj.set_config_value(name, value)
81                 self.plugin_config[name][2] = value
82
83         return self._template('admin/login_plugin.html',
84                               message=message,
85                               message_type=message_type,
86                               title='%s plugin' % self._obj.name,
87                               name='admin_login_%s_form' % self._obj.name,
88                               action=self.url,
89                               options=self.plugin_config)
90
91     def root(self, *args, **kwargs):
92         cherrypy.log.error("method: %s" % cherrypy.request.method)
93         op = getattr(self, cherrypy.request.method, self.GET)
94         if callable(op):
95             return op(*args, **kwargs)
96
97
98 class LoginPluginsOrder(Page):
99
100     def __init__(self, site, baseurl):
101         super(LoginPluginsOrder, self).__init__(site)
102         self.url = '%s/order' % baseurl
103
104     @admin_protect
105     def GET(self, *args, **kwargs):
106         return self._template('admin/login_order.html',
107                               title='login plugins order',
108                               name='admin_login_order_form',
109                               action=self.url,
110                               options=self._site[LOGIN_FACILITY]['enabled'])
111
112     @admin_protect
113     def POST(self, *args, **kwargs):
114         message = "Nothing was modified."
115         message_type = "info"
116         valid = self._site[LOGIN_FACILITY]['enabled']
117
118         if 'order' in kwargs:
119             order = kwargs['order'].split(',')
120             if len(order) != 0:
121                 new_values = []
122                 try:
123                     for v in order:
124                         val = v.strip()
125                         if val not in valid:
126                             error = "Invalid plugin name: %s" % val
127                             raise ValueError(error)
128                         new_values.append(val)
129                     if len(new_values) < len(valid):
130                         for val in valid:
131                             if val not in new_values:
132                                 new_values.append(val)
133
134                     po = PluginObject()
135                     po.name = "global"
136                     globalconf = dict()
137                     globalconf['order'] = ','.join(new_values)
138                     po.set_config(globalconf)
139                     po.save_plugin_config(LOGIN_FACILITY)
140
141                     # When all is saved update also live config
142                     self._site[LOGIN_FACILITY]['enabled'] = new_values
143
144                     message = "New configuration saved."
145                     message_type = "success"
146
147                 except ValueError, e:
148                     message = str(e)
149                     message_type = "error"
150
151                 except Exception, e:  # pylint: disable=broad-except
152                     message = "Failed to save data!"
153                     message_type = "error"
154
155         return self._template('admin/login_order.html',
156                               message=message,
157                               message_type=message_type,
158                               title='login plugins order',
159                               name='admin_login_order_form',
160                               action=self.url,
161                               options=self._site[LOGIN_FACILITY]['enabled'])
162
163     def root(self, *args, **kwargs):
164         cherrypy.log.error("method: %s" % cherrypy.request.method)
165         op = getattr(self, cherrypy.request.method, self.GET)
166         if callable(op):
167             return op(*args, **kwargs)
168
169
170 class LoginPlugins(Page):
171     def __init__(self, site, baseurl):
172         super(LoginPlugins, self).__init__(site)
173         self.url = '%s/login' % baseurl
174
175         for plugin in self._site[LOGIN_FACILITY]['available']:
176             cherrypy.log.error('Admin login plugin: %s' % plugin)
177             obj = self._site[LOGIN_FACILITY]['available'][plugin]
178             self.__dict__[plugin] = LoginPluginPage(obj, self._site, self.url)
179
180         self.order = LoginPluginsOrder(self._site, self.url)
181
182
183 class Admin(Page):
184
185     def __init__(self, *args, **kwargs):
186         super(Admin, self).__init__(*args, **kwargs)
187         self.url = '%s/admin' % self.basepath
188         self.login = LoginPlugins(self._site, self.url)
189
190     def root(self, *args, **kwargs):
191         login_plugins = self._site[LOGIN_FACILITY]
192         return self._template('admin/index.html', title='Administration',
193                               available=login_plugins['available'],
194                               enabled=login_plugins['enabled'])