Added logging to meddleware.csrf
[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
31a8ff42 18import urllib
ec97c937 19import logging
31a8ff42 20
31a8ff42 21import routes
b61874b2 22from webob import Request, exc
31a8ff42 23
ec97c937 24from mediagoblin import routing, meddleware, __version__
c0022ecc
CAW
25from mediagoblin.tools import common, translate, template
26from mediagoblin.tools.response import render_404
152a3bfa 27from mediagoblin.tools import request as mg_request
6e7ce8d1 28from mediagoblin.mg_globals import setup_globals
073b61fe 29from mediagoblin.init.celery import setup_celery_from_config
50854db0
WKG
30from mediagoblin.init import (get_jinja_loader, get_staticdirector,
31 setup_global_and_app_config, setup_workbench, setup_database,
0533f117 32 setup_storage, setup_beaker_cache)
90e342f9 33
31a8ff42 34
ec97c937
E
35_log = logging.getLogger(__name__)
36
37
8e1e744d 38class MediaGoblinApp(object):
31a8ff42 39 """
3f5cf663
CAW
40 WSGI application of MediaGoblin
41
42 ... this is the heart of the program!
31a8ff42 43 """
3f5cf663
CAW
44 def __init__(self, config_path, setup_celery=True):
45 """
46 Initialize the application based on a configuration file.
47
48 Arguments:
49 - config_path: path to the configuration file we're opening.
50 - setup_celery: whether or not to setup celery during init.
51 (Note: setting 'celery_setup_elsewhere' also disables
52 setting up celery.)
53 """
ec97c937 54 _log.info("GNU MediaGoblin %s main server starting", __version__)
3f369674 55 _log.debug("Using config file %s", config_path)
3f5cf663
CAW
56 ##############
57 # Setup config
58 ##############
59
60 # Open and setup the config
fe289be4 61 global_config, app_config = setup_global_and_app_config(config_path)
3f5cf663
CAW
62
63 ##########################################
64 # Setup other connections / useful objects
65 ##########################################
66
67 # Set up the database
3f4b5e4a 68 self.connection, self.db = setup_database()
ff94114c 69
5afdd7a1 70 # Get the template environment
42ef819c 71 self.template_loader = get_jinja_loader(
1e9d1acc 72 app_config.get('local_templates'))
0c8a30e6 73
5afdd7a1 74 # Set up storage systems
dccef262 75 self.public_store, self.queue_store = setup_storage()
5afdd7a1
CAW
76
77 # set up routing
0f63a944 78 self.routing = routing.get_mapper()
31a8ff42 79
582c4d5f 80 # set up staticdirector tool
c85c9dc7 81 self.staticdirector = get_staticdirector(app_config)
3f5cf663 82
0533f117
CAW
83 # set up caching
84 self.cache = setup_beaker_cache()
85
3f5cf663
CAW
86 # Setup celery, if appropriate
87 if setup_celery and not app_config.get('celery_setup_elsewhere'):
d9a31a39 88 if os.environ.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':
3f5cf663
CAW
89 setup_celery_from_config(
90 app_config, global_config,
91 force_celery_always_eager=True)
92 else:
93 setup_celery_from_config(app_config, global_config)
94
95 #######################################################
96 # Insert appropriate things into mediagoblin.mg_globals
97 #
df9809c2
CAW
98 # certain properties need to be accessed globally eg from
99 # validators, etc, which might not access to the request
100 # object.
3f5cf663
CAW
101 #######################################################
102
243c3843 103 setup_globals(app=self)
1fd97db3
CAW
104
105 # Workbench *currently* only used by celery, so this only
106 # matters in always eager mode :)
7664b4db 107 setup_workbench()
df9809c2 108
ce5ae8da
CAW
109 # instantiate application meddleware
110 self.meddleware = [common.import_component(m)(self)
111 for m in meddleware.ENABLED_MEDDLEWARE]
0c8a30e6 112
e824570a 113 def call_backend(self, environ, start_response):
31a8ff42 114 request = Request(environ)
0c8a30e6 115
582c4d5f 116 ## Routing / controller loading stuff
0c8a30e6 117 path_info = request.path_info
0f63a944 118 route_match = self.routing.match(path_info)
31a8ff42 119
05788ef4
E
120 # By using fcgi, mediagoblin can run under a base path
121 # like /mediagoblin/. request.path_info contains the
122 # path inside mediagoblin. If the something needs the
123 # full path of the current page, that should include
124 # the basepath.
125 # Note: urlgen and routes are fine!
126 request.full_path = environ["SCRIPT_NAME"] + request.path_info
127 # python-routes uses SCRIPT_NAME. So let's use that too.
128 # The other option would be:
129 # request.full_path = environ["SCRIPT_URL"]
130
871fc591 131 # Fix up environ for urlgen
d23d4b23 132 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
871fc591
E
133 if environ.get('HTTPS', '').lower() == 'off':
134 environ.pop('HTTPS')
135
3d0557bf
CAW
136 ## Attach utilities to the request object
137 request.matchdict = route_match
138 request.urlgen = routes.URLGenerator(self.routing, environ)
139 # Do we really want to load this via middleware? Maybe?
140 request.session = request.environ['beaker.session']
141 # Attach self as request.app
142 # Also attach a few utilities from request.app for convenience?
143 request.app = self
ae3bc7fa 144 request.locale = translate.get_locale_from_request(request)
0c8a30e6 145
ae3bc7fa 146 request.template_env = template.get_jinja_env(
3d0557bf
CAW
147 self.template_loader, request.locale)
148 request.db = self.db
149 request.staticdirect = self.staticdirector
150
152a3bfa 151 mg_request.setup_user_in_request(request)
3d0557bf 152
31a8ff42
CAW
153 # No matching page?
154 if route_match is None:
155 # Try to do see if we have a match with a trailing slash
156 # added and if so, redirect
157 if not path_info.endswith('/') \
158 and request.method == 'GET' \
0f63a944 159 and self.routing.match(path_info + '/'):
31a8ff42
CAW
160 new_path_info = path_info + '/'
161 if request.GET:
162 new_path_info = '%s?%s' % (
163 new_path_info, urllib.urlencode(request.GET))
1bb0fdf2 164 redirect = exc.HTTPFound(location=new_path_info)
31a8ff42
CAW
165 return request.get_response(redirect)(environ, start_response)
166
167 # Okay, no matches. 404 time!
3807e8e2 168 request.matchdict = {} # in case our template expects it
c0022ecc 169 return render_404(request)(environ, start_response)
31a8ff42 170
8a0d35e7
CAW
171 # import the controller, or if it's already a callable, call that
172 route_controller = route_match['controller']
173 if isinstance(route_controller, unicode) \
174 or isinstance(route_controller, str):
175 controller = common.import_component(route_match['controller'])
176 else:
177 controller = route_match['controller']
91cf6738
NY
178
179 # pass the request through our meddleware classes
180 for m in self.meddleware:
181 response = m.process_request(request, controller)
182 if response is not None:
183 return response(environ, start_response)
184
31a8ff42
CAW
185 request.start_response = start_response
186
0c8a30e6
NY
187 # get the response from the controller
188 response = controller(request)
189
ce5ae8da
CAW
190 # pass the response through the meddleware
191 for m in self.meddleware[::-1]:
0c8a30e6
NY
192 m.process_response(request, response)
193
e824570a
E
194 return response(environ, start_response)
195
196 def __call__(self, environ, start_response):
197 ## If more errors happen that look like unclean sessions:
198 # self.db.check_session_clean()
199
2bc8ff0d 200 try:
e824570a
E
201 return self.call_backend(environ, start_response)
202 finally:
203 # Reset the sql session, so that the next request
204 # gets a fresh session
2bc8ff0d 205 self.db.reset_after_request()
31a8ff42
CAW
206
207
5784c4e9 208def paste_app_factory(global_config, **app_config):
91903aa6
CAW
209 configs = app_config['config'].split()
210 mediagoblin_config = None
211 for config in configs:
212 if os.path.exists(config) and os.access(config, os.R_OK):
213 mediagoblin_config = config
214 break
215
216 if not mediagoblin_config:
217 raise IOError("Usable mediagoblin config not found.")
218
219 mgoblin_app = MediaGoblinApp(mediagoblin_config)
b61874b2 220
c4d71564 221 return mgoblin_app