/
rdw_app.py
276 lines (245 loc) · 10.8 KB
/
rdw_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# -*- coding: utf-8 -*-
# rdiffweb, A web interface to rdiff-backup repositories
# Copyright (C) 2012-2021 rdiffweb contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
import cherrypy
import cherrypy.lib.sessions
import pkg_resources
from cherrypy import Application
import rdiffweb
import rdiffweb.controller.filter_authorization
import rdiffweb.core.login # noqa
import rdiffweb.core.notification
import rdiffweb.core.quota
import rdiffweb.core.remove_older
import rdiffweb.plugins.ldap
import rdiffweb.plugins.scheduler
import rdiffweb.plugins.smtp
import rdiffweb.tools.auth_form
import rdiffweb.tools.auth_mfa
import rdiffweb.tools.currentuser
import rdiffweb.tools.db
import rdiffweb.tools.enrich_session
import rdiffweb.tools.errors
import rdiffweb.tools.i18n
import rdiffweb.tools.proxy
import rdiffweb.tools.ratelimit
import rdiffweb.tools.secure_headers
from rdiffweb.controller import Controller
from rdiffweb.controller.api import ApiPage
from rdiffweb.controller.dispatch import staticdir, staticfile
from rdiffweb.controller.page_admin import AdminPage
from rdiffweb.controller.page_browse import BrowsePage
from rdiffweb.controller.page_delete import DeletePage
from rdiffweb.controller.page_graphs import GraphsPage
from rdiffweb.controller.page_history import HistoryPage
from rdiffweb.controller.page_locations import LocationsPage
from rdiffweb.controller.page_login import LoginPage
from rdiffweb.controller.page_logs import LogsPage
from rdiffweb.controller.page_mfa import MfaPage
from rdiffweb.controller.page_pref_sshkeys import ApiSshKeys
from rdiffweb.controller.page_prefs import PreferencesPage
from rdiffweb.controller.page_restore import RestorePage
from rdiffweb.controller.page_settings import SettingsPage
from rdiffweb.controller.page_status import StatusPage
from rdiffweb.core import rdw_templating
from rdiffweb.core.config import Option, parse_args
from rdiffweb.core.model import DbSession, UserObject
# Define the logger
logger = logging.getLogger(__name__)
# Define cherrypy development environment
cherrypy.config.environments['development'] = {
'engine.autoreload.on': True,
'checker.on': False,
'tools.log_headers.on': True,
'request.show_tracebacks': True,
'request.show_mismatched_params': True,
'log.screen': False,
}
@cherrypy.tools.auth_form()
@cherrypy.tools.auth_mfa(
mfa_enabled=lambda username: UserObject.get_user(username).mfa == UserObject.ENABLED_MFA,
)
@cherrypy.tools.currentuser(userobj=lambda username: UserObject.get_user(username))
@cherrypy.tools.db()
@cherrypy.tools.enrich_session()
@cherrypy.tools.proxy(remote='X-Real-IP')
@cherrypy.tools.secure_headers()
class Root(LocationsPage):
def __init__(self):
self.login = LoginPage()
self.mfa = MfaPage()
self.browse = BrowsePage()
self.delete = DeletePage()
self.restore = RestorePage()
self.history = HistoryPage()
self.status = StatusPage()
self.admin = AdminPage()
self.prefs = PreferencesPage()
self.settings = SettingsPage()
self.api = ApiPage()
self.api.currentuser.sshkeys = ApiSshKeys()
self.graphs = GraphsPage()
self.logs = LogsPage()
# Register static dir.
static_dir = pkg_resources.resource_filename('rdiffweb', 'static') # @UndefinedVariable
self.static = staticdir(static_dir)
# Register robots.txt
robots_txt = pkg_resources.resource_filename('rdiffweb', 'static/robots.txt') # @UndefinedVariable
self.robots_txt = staticfile(robots_txt)
class RdiffwebApp(Application):
"""This class represent the application context."""
_favicon = Option('favicon')
_header_logo = Option('header_logo')
_tempdir = Option('tempdir')
@classmethod
def parse_args(cls, args=None, config_file_contents=None):
return parse_args(args, config_file_contents)
def __init__(self, cfg):
self.cfg = cfg
db_uri = self.cfg.database_uri if '://' in self.cfg.database_uri else "sqlite:///" + self.cfg.database_uri
cherrypy.config.update(
{
'environment': 'development' if cfg.debug else cfg.environment,
# Configure database plugins
'tools.db.uri': db_uri,
'tools.db.debug': cfg.debug,
# Configure LDAP plugin
'ldap.uri': cfg.ldap_uri,
'ldap.base_dn': cfg.ldap_base_dn,
'ldap.bind_dn': cfg.ldap_bind_dn,
'ldap.bind_password': cfg.ldap_bind_password,
'ldap.scope': cfg.ldap_scope,
'ldap.tls': cfg.ldap_tls,
'ldap.username_attribute': cfg.ldap_username_attribute,
'ldap.required_group': cfg.ldap_required_group,
'ldap.group_attribute': cfg.ldap_group_attribute,
'ldap.group_attribute_is_dn': cfg.ldap_group_attribute_is_dn,
'ldap.version': cfg.ldap_version,
'ldap.network_timeout': cfg.ldap_network_timeout,
'ldap.timeout': cfg.ldap_timeout,
'ldap.encoding': cfg.ldap_encoding,
# Configure login
'login.add_missing_user': cfg.ldap_add_missing_user,
'login.add_user_default_role': cfg.ldap_add_user_default_role,
'login.add_user_default_userroot': cfg.ldap_add_user_default_userroot,
# Configure SMTP plugin
'smtp.server': cfg.email_host,
'smtp.username': cfg.email_username,
'smtp.password': cfg.email_password,
'smtp.email_from': cfg.email_sender
and '%s <%s>'
% (
cfg.header_name,
cfg.email_sender,
),
'smtp.encryption': cfg.email_encryption,
# Configure remove_older plugin
'remove_older.execution_time': self.cfg.remove_older_time,
# Configure notification plugin
'notification.execution_time': self.cfg.email_notification_time,
'notification.send_changed': self.cfg.email_send_changed_notification,
# Configure quota plugin
'quota.set_quota_cmd': self.cfg.quota_set_cmd,
'quota.get_quota_cmd': self.cfg.quota_get_cmd,
'quota.get_usage_cmd': self.cfg.quota_used_cmd,
}
)
# Create database if required
cherrypy.tools.db.create_all()
# Initialise the template engine.
self.templates = rdw_templating.TemplateManager()
# Pick the right implementation for storage
rate_limit_storage_class = rdiffweb.tools.ratelimit.RamRateLimit
if cfg.rate_limit_dir:
rate_limit_storage_class = rdiffweb.tools.ratelimit.FileRateLimit
config = {
'/': {
# To work around the new behaviour in CherryPy >= 5.5.0, force usage of
# ISO-8859-1 encoding for URL. This avoid any conversion of the
# URL into UTF-8.
'request.uri_encoding': 'ISO-8859-1',
'tools.i18n.on': True,
'tools.i18n.default': 'en_US',
'tools.i18n.mo_dir': pkg_resources.resource_filename('rdiffweb', 'locales'), # @UndefinedVariable
'tools.i18n.domain': 'messages',
'tools.encode.on': True,
'tools.encode.encoding': 'utf-8',
'tools.gzip.on': True,
'error_page.default': self.error_page,
'tools.sessions.on': True,
'tools.sessions.debug': cfg.debug,
'tools.sessions.storage_class': DbSession,
'tools.sessions.httponly': True,
'tools.sessions.timeout': cfg.session_idle_timeout, # minutes
'tools.sessions.persistent': False, # auth_form should update this.
'tools.auth_form.persistent_timeout': cfg.session_persistent_timeout, # minutes
'tools.auth_form.absolute_timeout': cfg.session_absolute_timeout, # minutes
'tools.ratelimit.debug': cfg.debug,
'tools.ratelimit.delay': 3600,
'tools.ratelimit.limit': cfg.rate_limit,
'tools.ratelimit.storage_class': rate_limit_storage_class,
'tools.ratelimit.storage_path': cfg.rate_limit_dir,
},
}
# Initialize the application
Application.__init__(self, root=Root(), config=config)
# Register favicon.ico
self.root.favicon_ico = staticfile(self._favicon)
# Register header_logo
if self._header_logo:
self.root.header_logo = staticfile(self._header_logo)
# Define TEMP env
if self._tempdir:
os.environ["TMPDIR"] = self._tempdir
# create user manager
UserObject.create_admin_user(cfg.admin_user, cfg.admin_password)
@property
def currentuser(self):
"""
Proxy property to get current user from cherrypy request object.
Return a UserObject when logged in or None.
"""
return getattr(cherrypy.serving.request, 'currentuser', None)
def error_page(self, **kwargs):
"""
Default error page shown to the user when an unexpected error occur.
"""
# Log exception.
logger.error(
'error page: %s %s\n%s' % (kwargs.get('status', ''), kwargs.get('message', ''), kwargs.get('traceback', ''))
)
# Replace message by generic one for 404. Default implementation leak path info.
if kwargs.get('status', '') == '404 Not Found':
kwargs['message'] = 'Nothing matches the given URI'
# Check expected response type.
mtype = cherrypy.tools.accept.callable(['text/html', 'text/plain']) # @UndefinedVariable
if mtype == 'text/plain':
return kwargs.get('message')
# Try to build a nice error page.
try:
page = Controller()
return page._compile_template('error_page_default.html', **kwargs)
except Exception:
# If failing, send the raw error message.
return kwargs.get('message')
@property
def version(self):
"""
Get the current running version (using package info).
"""
return rdiffweb.__version__