Modify deleteuser to fail gracefully
[mediagoblin.git] / mediagoblin / app.py
CommitLineData
8e1e744d 1# GNU MediaGoblin -- federated, autonomous media hosting
cf29e8a8 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
e5572c60
ML
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Affero General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Affero General Public License for more details.
13#
14# You should have received a copy of the GNU Affero General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
571198c9 17import os
ec97c937 18import logging
31a8ff42 19
3d914332
E
20from mediagoblin.routing import get_url_map
21from mediagoblin.tools.routing import endpoint_to_controller
7742dcc1 22
f1d06e1d 23from werkzeug.wrappers import Request
e5e2c5e7 24from werkzeug.exceptions import HTTPException
fd61aac7 25from werkzeug.routing import RequestRedirect
31a8ff42 26
7742dcc1 27from mediagoblin import meddleware, __version__
26583b2c 28from mediagoblin.db.util import check_db_up_to_date
c7424612 29from mediagoblin.tools import common, session, translate, template
785b287f 30from mediagoblin.tools.response import render_http_exception
828fc630 31from mediagoblin.tools.theme import register_themes
152a3bfa 32from mediagoblin.tools import request as mg_request
c81186dd 33from mediagoblin.media_types.tools import media_type_warning
6e7ce8d1 34from mediagoblin.mg_globals import setup_globals
073b61fe 35from mediagoblin.init.celery import setup_celery_from_config
29b6f917 36from mediagoblin.init.plugins import setup_plugins
50854db0 37from mediagoblin.init import (get_jinja_loader, get_staticdirector,
6ef75af5 38 setup_global_and_app_config, setup_locales, setup_workbench, setup_database,
9e1fa239 39 setup_storage)
c5d8d301 40from mediagoblin.tools.pluginapi import PluginManager, hook_transform
5907154a 41from mediagoblin.tools.crypto import setup_crypto
c9dec8b3 42from mediagoblin.auth.tools import check_auth_enabled, no_auth_logout
90e342f9 43
31a8ff42 44
ec97c937
E
45_log = logging.getLogger(__name__)
46
47
8e1e744d 48class MediaGoblinApp(object):
31a8ff42 49 """
3f5cf663
CAW
50 WSGI application of MediaGoblin
51
52 ... this is the heart of the program!
31a8ff42 53 """
3f5cf663
CAW
54 def __init__(self, config_path, setup_celery=True):
55 """
56 Initialize the application based on a configuration file.
57
58 Arguments:
59 - config_path: path to the configuration file we're opening.
60 - setup_celery: whether or not to setup celery during init.
61 (Note: setting 'celery_setup_elsewhere' also disables
62 setting up celery.)
63 """
ec97c937 64 _log.info("GNU MediaGoblin %s main server starting", __version__)
3f369674 65 _log.debug("Using config file %s", config_path)
3f5cf663
CAW
66 ##############
67 # Setup config
68 ##############
69
70 # Open and setup the config
fe289be4 71 global_config, app_config = setup_global_and_app_config(config_path)
3f5cf663 72
c81186dd
RE
73 media_type_warning()
74
5907154a
E
75 setup_crypto()
76
3f5cf663
CAW
77 ##########################################
78 # Setup other connections / useful objects
79 ##########################################
80
b0ee3aae
E
81 # Setup Session Manager, not needed in celery
82 self.session_manager = session.SessionManager()
83
6ef75af5
SS
84 # load all available locales
85 setup_locales()
86
29b6f917
WKG
87 # Set up plugins -- need to do this early so that plugins can
88 # affect startup.
89 _log.info("Setting up plugins.")
90 setup_plugins()
91
3f5cf663 92 # Set up the database
4a698535 93 self.db = setup_database(app_config['run_migrations'])
ff94114c 94
26583b2c
RE
95 # Quit app if need to run dbupdate
96 check_db_up_to_date()
97
828fc630 98 # Register themes
975be468 99 self.theme_registry, self.current_theme = register_themes(app_config)
828fc630 100
5afdd7a1 101 # Get the template environment
42ef819c 102 self.template_loader = get_jinja_loader(
3b47da8e 103 app_config.get('local_templates'),
8545dd50 104 self.current_theme,
05e007c1 105 PluginManager().get_template_paths()
8545dd50 106 )
0c8a30e6 107
744f1c83
RE
108 # Check if authentication plugin is enabled and respond accordingly.
109 self.auth = check_auth_enabled()
1bce0c15
RE
110 if not self.auth:
111 app_config['allow_comments'] = False
744f1c83 112
5afdd7a1 113 # Set up storage systems
dccef262 114 self.public_store, self.queue_store = setup_storage()
5afdd7a1
CAW
115
116 # set up routing
48cf435d 117 self.url_map = get_url_map()
31a8ff42 118
582c4d5f 119 # set up staticdirector tool
c85c9dc7 120 self.staticdirector = get_staticdirector(app_config)
3f5cf663
CAW
121
122 # Setup celery, if appropriate
123 if setup_celery and not app_config.get('celery_setup_elsewhere'):
d9a31a39 124 if os.environ.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':
3f5cf663
CAW
125 setup_celery_from_config(
126 app_config, global_config,
127 force_celery_always_eager=True)
128 else:
129 setup_celery_from_config(app_config, global_config)
130
131 #######################################################
132 # Insert appropriate things into mediagoblin.mg_globals
133 #
df9809c2
CAW
134 # certain properties need to be accessed globally eg from
135 # validators, etc, which might not access to the request
136 # object.
3f5cf663
CAW
137 #######################################################
138
243c3843 139 setup_globals(app=self)
1fd97db3
CAW
140
141 # Workbench *currently* only used by celery, so this only
142 # matters in always eager mode :)
7664b4db 143 setup_workbench()
df9809c2 144
ce5ae8da
CAW
145 # instantiate application meddleware
146 self.meddleware = [common.import_component(m)(self)
147 for m in meddleware.ENABLED_MEDDLEWARE]
0c8a30e6 148
e824570a 149 def call_backend(self, environ, start_response):
31a8ff42 150 request = Request(environ)
0c8a30e6 151
726896b6 152 # Compatibility with django, use request.args preferrably
f1d06e1d 153 request.GET = request.args
f1d06e1d 154
582c4d5f 155 ## Routing / controller loading stuff
7742dcc1 156 map_adapter = self.url_map.bind_to_environ(request.environ)
31a8ff42 157
05788ef4
E
158 # By using fcgi, mediagoblin can run under a base path
159 # like /mediagoblin/. request.path_info contains the
160 # path inside mediagoblin. If the something needs the
161 # full path of the current page, that should include
162 # the basepath.
163 # Note: urlgen and routes are fine!
f1d06e1d 164 request.full_path = environ["SCRIPT_NAME"] + request.path
05788ef4
E
165 # python-routes uses SCRIPT_NAME. So let's use that too.
166 # The other option would be:
167 # request.full_path = environ["SCRIPT_URL"]
168
871fc591 169 # Fix up environ for urlgen
d23d4b23 170 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
871fc591
E
171 if environ.get('HTTPS', '').lower() == 'off':
172 environ.pop('HTTPS')
173
3d0557bf 174 ## Attach utilities to the request object
3d0557bf 175 # Do we really want to load this via middleware? Maybe?
b0ee3aae 176 session_manager = self.session_manager
c7424612 177 request.session = session_manager.load_session_from_cookie(request)
3d0557bf
CAW
178 # Attach self as request.app
179 # Also attach a few utilities from request.app for convenience?
180 request.app = self
0c8a30e6 181
3d0557bf
CAW
182 request.db = self.db
183 request.staticdirect = self.staticdirector
184
1ec7ff2a
JW
185 request.locale = translate.get_locale_from_request(request)
186 request.template_env = template.get_jinja_env(
187 self.template_loader, request.locale)
7742dcc1
JW
188
189 def build_proxy(endpoint, **kw):
190 try:
191 qualified = kw.pop('qualified')
192 except KeyError:
193 qualified = False
194
195 return map_adapter.build(
196 endpoint,
197 values=dict(**kw),
198 force_external=qualified)
199
200 request.urlgen = build_proxy
201
5101c469 202 # Log user out if authentication_disabled
c9dec8b3
RE
203 no_auth_logout(request)
204
8ce8faaf
RE
205 mg_request.setup_user_in_request(request)
206
f7a5c7c7 207 request.controller_name = None
1ec7ff2a 208 try:
05501c57 209 found_rule, url_values = map_adapter.match(return_rule=True)
1ec7ff2a 210 request.matchdict = url_values
fd61aac7
SS
211 except RequestRedirect as response:
212 # Deal with 301 responses eg due to missing final slash
213 return response(environ, start_response)
1ec7ff2a 214 except HTTPException as exc:
785b287f
SS
215 # Stop and render exception
216 return render_http_exception(
217 request, exc,
218 exc.get_description(environ))(environ, start_response)
1ec7ff2a 219
05501c57 220 controller = endpoint_to_controller(found_rule)
98dacfe6 221 # Make a reference to the controller's symbolic name on the request...
38103094 222 # used for lazy context modification
98dacfe6 223 request.controller_name = found_rule.endpoint
91cf6738
NY
224
225 # pass the request through our meddleware classes
785b287f
SS
226 try:
227 for m in self.meddleware:
228 response = m.process_request(request, controller)
229 if response is not None:
230 return response(environ, start_response)
231 except HTTPException as e:
232 return render_http_exception(
233 request, e,
234 e.get_description(environ))(environ, start_response)
91cf6738 235
b1fbf67e
CAW
236 request = hook_transform("modify_request", request)
237
31a8ff42
CAW
238 request.start_response = start_response
239
785b287f
SS
240 # get the Http response from the controller
241 try:
242 response = controller(request)
243 except HTTPException as e:
244 response = render_http_exception(
245 request, e, e.get_description(environ))
0c8a30e6 246
785b287f
SS
247 # pass the response through the meddlewares
248 try:
249 for m in self.meddleware[::-1]:
250 m.process_response(request, response)
251 except HTTPException as e:
6a28bc4e 252 response = render_http_exception(
785b287f 253 request, e, e.get_description(environ))
0c8a30e6 254
b0ee3aae
E
255 session_manager.save_session_to_cookie(request.session,
256 request, response)
c7424612 257
e824570a
E
258 return response(environ, start_response)
259
260 def __call__(self, environ, start_response):
261 ## If more errors happen that look like unclean sessions:
262 # self.db.check_session_clean()
263
2bc8ff0d 264 try:
e824570a
E
265 return self.call_backend(environ, start_response)
266 finally:
267 # Reset the sql session, so that the next request
268 # gets a fresh session
2bc8ff0d 269 self.db.reset_after_request()
31a8ff42
CAW
270
271
5784c4e9 272def paste_app_factory(global_config, **app_config):
91903aa6
CAW
273 configs = app_config['config'].split()
274 mediagoblin_config = None
275 for config in configs:
276 if os.path.exists(config) and os.access(config, os.R_OK):
277 mediagoblin_config = config
278 break
279
280 if not mediagoblin_config:
281 raise IOError("Usable mediagoblin config not found.")
282
283 mgoblin_app = MediaGoblinApp(mediagoblin_config)
c5d8d301 284 mgoblin_app = hook_transform('wrap_wsgi', mgoblin_app)
f3f53028 285
c4d71564 286 return mgoblin_app