add a check for authentication plugin on startup and respond according to no_auth...
[mediagoblin.git] / mediagoblin / app.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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
17 import os
18 import logging
19
20 from mediagoblin.routing import get_url_map
21 from mediagoblin.tools.routing import endpoint_to_controller
22
23 from werkzeug.wrappers import Request
24 from werkzeug.exceptions import HTTPException
25 from werkzeug.routing import RequestRedirect
26
27 from mediagoblin import meddleware, __version__
28 from mediagoblin.tools import common, session, translate, template
29 from mediagoblin.tools.response import render_http_exception
30 from mediagoblin.tools.theme import register_themes
31 from mediagoblin.tools import request as mg_request
32 from mediagoblin.mg_globals import setup_globals
33 from mediagoblin.init.celery import setup_celery_from_config
34 from mediagoblin.init.plugins import setup_plugins
35 from mediagoblin.init import (get_jinja_loader, get_staticdirector,
36 setup_global_and_app_config, setup_locales, setup_workbench, setup_database,
37 setup_storage)
38 from mediagoblin.tools.pluginapi import PluginManager, hook_transform
39 from mediagoblin.tools.crypto import setup_crypto
40 from mediagoblin.auth.tools import check_auth_enabled
41
42
43 _log = logging.getLogger(__name__)
44
45
46 class MediaGoblinApp(object):
47 """
48 WSGI application of MediaGoblin
49
50 ... this is the heart of the program!
51 """
52 def __init__(self, config_path, setup_celery=True):
53 """
54 Initialize the application based on a configuration file.
55
56 Arguments:
57 - config_path: path to the configuration file we're opening.
58 - setup_celery: whether or not to setup celery during init.
59 (Note: setting 'celery_setup_elsewhere' also disables
60 setting up celery.)
61 """
62 _log.info("GNU MediaGoblin %s main server starting", __version__)
63 _log.debug("Using config file %s", config_path)
64 ##############
65 # Setup config
66 ##############
67
68 # Open and setup the config
69 global_config, app_config = setup_global_and_app_config(config_path)
70
71 setup_crypto()
72
73 ##########################################
74 # Setup other connections / useful objects
75 ##########################################
76
77 # Setup Session Manager, not needed in celery
78 self.session_manager = session.SessionManager()
79
80 # load all available locales
81 setup_locales()
82
83 # Set up plugins -- need to do this early so that plugins can
84 # affect startup.
85 _log.info("Setting up plugins.")
86 setup_plugins()
87
88 # Set up the database
89 self.db = setup_database()
90
91 # Register themes
92 self.theme_registry, self.current_theme = register_themes(app_config)
93
94 # Get the template environment
95 self.template_loader = get_jinja_loader(
96 app_config.get('local_templates'),
97 self.current_theme,
98 PluginManager().get_template_paths()
99 )
100
101 # Check if authentication plugin is enabled and respond accordingly.
102 self.auth = check_auth_enabled()
103
104 # Set up storage systems
105 self.public_store, self.queue_store = setup_storage()
106
107 # set up routing
108 self.url_map = get_url_map()
109
110 # set up staticdirector tool
111 self.staticdirector = get_staticdirector(app_config)
112
113 # Setup celery, if appropriate
114 if setup_celery and not app_config.get('celery_setup_elsewhere'):
115 if os.environ.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':
116 setup_celery_from_config(
117 app_config, global_config,
118 force_celery_always_eager=True)
119 else:
120 setup_celery_from_config(app_config, global_config)
121
122 #######################################################
123 # Insert appropriate things into mediagoblin.mg_globals
124 #
125 # certain properties need to be accessed globally eg from
126 # validators, etc, which might not access to the request
127 # object.
128 #######################################################
129
130 setup_globals(app=self)
131
132 # Workbench *currently* only used by celery, so this only
133 # matters in always eager mode :)
134 setup_workbench()
135
136 # instantiate application meddleware
137 self.meddleware = [common.import_component(m)(self)
138 for m in meddleware.ENABLED_MEDDLEWARE]
139
140 def call_backend(self, environ, start_response):
141 request = Request(environ)
142
143 # Compatibility with django, use request.args preferrably
144 request.GET = request.args
145
146 ## Routing / controller loading stuff
147 map_adapter = self.url_map.bind_to_environ(request.environ)
148
149 # By using fcgi, mediagoblin can run under a base path
150 # like /mediagoblin/. request.path_info contains the
151 # path inside mediagoblin. If the something needs the
152 # full path of the current page, that should include
153 # the basepath.
154 # Note: urlgen and routes are fine!
155 request.full_path = environ["SCRIPT_NAME"] + request.path
156 # python-routes uses SCRIPT_NAME. So let's use that too.
157 # The other option would be:
158 # request.full_path = environ["SCRIPT_URL"]
159
160 # Fix up environ for urlgen
161 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
162 if environ.get('HTTPS', '').lower() == 'off':
163 environ.pop('HTTPS')
164
165 ## Attach utilities to the request object
166 # Do we really want to load this via middleware? Maybe?
167 session_manager = self.session_manager
168 request.session = session_manager.load_session_from_cookie(request)
169 # Attach self as request.app
170 # Also attach a few utilities from request.app for convenience?
171 request.app = self
172
173 request.db = self.db
174 request.staticdirect = self.staticdirector
175
176 request.locale = translate.get_locale_from_request(request)
177 request.template_env = template.get_jinja_env(
178 self.template_loader, request.locale)
179
180 def build_proxy(endpoint, **kw):
181 try:
182 qualified = kw.pop('qualified')
183 except KeyError:
184 qualified = False
185
186 return map_adapter.build(
187 endpoint,
188 values=dict(**kw),
189 force_external=qualified)
190
191 request.urlgen = build_proxy
192
193 mg_request.setup_user_in_request(request)
194
195 request.controller_name = None
196 try:
197 found_rule, url_values = map_adapter.match(return_rule=True)
198 request.matchdict = url_values
199 except RequestRedirect as response:
200 # Deal with 301 responses eg due to missing final slash
201 return response(environ, start_response)
202 except HTTPException as exc:
203 # Stop and render exception
204 return render_http_exception(
205 request, exc,
206 exc.get_description(environ))(environ, start_response)
207
208 controller = endpoint_to_controller(found_rule)
209 # Make a reference to the controller's symbolic name on the request...
210 # used for lazy context modification
211 request.controller_name = found_rule.endpoint
212
213 # pass the request through our meddleware classes
214 try:
215 for m in self.meddleware:
216 response = m.process_request(request, controller)
217 if response is not None:
218 return response(environ, start_response)
219 except HTTPException as e:
220 return render_http_exception(
221 request, e,
222 e.get_description(environ))(environ, start_response)
223
224 request.start_response = start_response
225
226 # get the Http response from the controller
227 try:
228 response = controller(request)
229 except HTTPException as e:
230 response = render_http_exception(
231 request, e, e.get_description(environ))
232
233 # pass the response through the meddlewares
234 try:
235 for m in self.meddleware[::-1]:
236 m.process_response(request, response)
237 except HTTPException as e:
238 response = render_http_exception(
239 request, e, e.get_description(environ))
240
241 session_manager.save_session_to_cookie(request.session,
242 request, response)
243
244 return response(environ, start_response)
245
246 def __call__(self, environ, start_response):
247 ## If more errors happen that look like unclean sessions:
248 # self.db.check_session_clean()
249
250 try:
251 return self.call_backend(environ, start_response)
252 finally:
253 # Reset the sql session, so that the next request
254 # gets a fresh session
255 self.db.reset_after_request()
256
257
258 def paste_app_factory(global_config, **app_config):
259 configs = app_config['config'].split()
260 mediagoblin_config = None
261 for config in configs:
262 if os.path.exists(config) and os.access(config, os.R_OK):
263 mediagoblin_config = config
264 break
265
266 if not mediagoblin_config:
267 raise IOError("Usable mediagoblin config not found.")
268
269 mgoblin_app = MediaGoblinApp(mediagoblin_config)
270 mgoblin_app = hook_transform('wrap_wsgi', mgoblin_app)
271
272 return mgoblin_app