Beispiel #1
0
    def __call__(self, environ, start_response):
        status, headers, app_iter, exc_info = call_wsgi_application(self.app, environ, catch_exc_info=True)
        if status[:3] in self.errors and "pylons.status_code_redirect" not in environ and self.error_path:
            # Create a response object
            environ["pylons.original_response"] = Response(status=status, headerlist=headers, app_iter=app_iter)
            environ["pylons.original_request"] = Request(environ)

            # Create a new environ to avoid touching the original request data
            new_environ = environ.copy()
            new_environ["PATH_INFO"] = self.error_path

            newstatus, headers, app_iter, exc_info = call_wsgi_application(self.app, new_environ, catch_exc_info=True)
        start_response(status, headers, exc_info)
        return app_iter
Beispiel #2
0
    def __call__(self, environ, start_response):
        # Run application.
        status, headers, app_iter = call_wsgi_application(self.application, environ)

        # Get location header.
        location = None
        for (name, value) in headers:
            if name == "location":
                location = value
                break
        
        if location:
            # Redirection.

            redirect_exceptions = [('file_upload', 'upload')]
            controller = environ['wsgiorg.routing_args'][1]['controller']
            action = environ['wsgiorg.routing_args'][1]['action']

            if request.headers.get('X-KAjax', None):
                log.debug("KWMOMiddleware: redirecting through a kajax request to '%s'." % ( location ) )
                raise KJsonifyRedirect(location)

            elif (controller, action) in redirect_exceptions:                              
                log.debug("KWMOMiddleware: ignoring redirect to '%s'." % ( location ) )
                status = '200 OK'
                response_headers = [('Content-type','text/plain')]
                start_response(status, response_headers)
                return 'redirection:%s' % ( location )

            else:
                log.debug("KWMOMiddleware: redirecting to '%s'." % ( location ) )
 
        start_response(status, headers)
        return app_iter
Beispiel #3
0
 def __call__(self, environ, start_response):
     status, headers, app_iter, exc_info = call_wsgi_application(
         self.app, environ, catch_exc_info=True)
     if status[:3] in self.errors and \
         'pylons.status_code_redirect' not in environ and self.error_path:
         # Create a response object
         environ['pylons.original_response'] = Response(
             status=status, headerlist=headers, app_iter=app_iter)
         environ['pylons.original_request'] = Request(environ)
         
         # Create a new environ to avoid touching the original request data
         new_environ = environ.copy()
         new_environ['PATH_INFO'] = self.error_path
         
         newstatus, headers, app_iter, exc_info = call_wsgi_application(
                 self.app, new_environ, catch_exc_info=True)
     start_response(status, headers, exc_info)
     return app_iter
Beispiel #4
0
	def __call__(self, environ, start_response):
		#this is from StatusCodeRedirect
		status, headers, app_iter, exc_info = call_wsgi_application(
			self.app, environ, catch_exc_info=True
		)
		if status[:3] in self.errors and 'columns.authentication_redirect' not in environ and self.login_path:
			# Create a response object
			environ['pylons.original_response'] = Response(
				status=status, headerlist=headers, app_iter=app_iter
			)
			environ['pylons.original_request'] = Request(environ)
			
			# Create a new environ to avoid touching the original request data
			new_environ = environ.copy()
			new_environ['PATH_INFO'] = self.login_path
			
			newstatus, headers, app_iter, exc_info = call_wsgi_application(
				self.app, new_environ, catch_exc_info=True
			)
		start_response(status, headers, exc_info)
		return app_iter
    def __call__(self, environ, start_response):
        '''WSGI Middleware that renders the page as usual, then
        transcludes some of the content from a Wordpress proxy.
        '''
        # get our content
        status, headers, app_iter, exc_info = call_wsgi_application(
            self.app, environ, catch_exc_info=True)
        skip_codes = ['301', '302', '304', '401']
        skip = [x for x in skip_codes if status.startswith(x)]
        if environ['REQUEST_METHOD'] in ['GET', 'POST'] \
               and not skip:
            # XXX return text/html too
            # make sure it's unicode
            charset = "utf-8"
            content_type = ""
            for k, v in headers:
                if k.lower() == "content-type":
                    content_type = v
                    charset_pos = v.find("charset")
                    if charset_pos > -1:
                        charset = v[charset_pos + 8:]
            if content_type.startswith("text/html"):
                # note we sometimes get "text/html" for xml, hence
                # extra test below
                content = FileAppIterWrapper(app_iter).read()
                content = content.decode(charset)
                if content and not content.startswith("<?xml"):
                    # get wordpress page content
                    try:
                        wp_status, wp_content = self.get_wordpress_content(
                            environ,
                            environ['PATH_INFO'])
                        environ['ckanext.wordpresser.wp_status'] = wp_status
                        environ['ckanext.wordpresser.local_status'] = status
                        content = self.replace_relevant_bits(content,
                                                             wp_content,
                                                             status,
                                                             wp_status)
                        headers = [(k, v) for k, v in headers \
                                   if k != "Content-Length"]
                        headers.append(('Content-Length',
                                        str(len(content.encode('utf-8')))
                                        ))

                        if not status.startswith("200"):
                            if not wp_status.startswith("404"):
                                status = wp_status
                        app_iter = [content]
                    except (HTTPMovedPermanently, HTTPFound), exc:
                        status = exc.status
                        content = ""
                        headers = [('Location', exc.location)]
Beispiel #6
0
    def __call__(self, environ, start_response):
        # Check the request to determine if we need
        # to respond with an error message or just the code.

        status, headers, app_iter, exc_info = call_wsgi_application(
            self.app, environ, catch_exc_info=True)
        #log.debug ("ENV=%s" % environ)
        if status[:3] in self.codes and environ.has_key('HTTP_USER_AGENT') and \
                environ['HTTP_USER_AGENT'].startswith('Python'):
            environ['pylons.status_code_redirect'] = True
            log.info('ERROR: disabled status_code_redirect')
        start_response(status, headers, exc_info)
        return app_iter
Beispiel #7
0
    def __call__(self, environ, start_response):
        '''WSGI Middleware that renders the page as usual, then
        transcludes some of the content from a Wordpress proxy.
        '''
        # get our content
        status, headers, app_iter, exc_info = call_wsgi_application(
            self.app, environ, catch_exc_info=True)
        skip_codes = [
            '301', '302', '304', '401', '200'
        ]  # add 200 to prevent dashboard being inaccessible. Not sure why this fixes it
        skip = [x for x in skip_codes if status.startswith(x)]

        if environ['REQUEST_METHOD'] in ['GET', 'POST'] \
               and not skip:
            # XXX return text/html too
            # make sure it's unicode
            charset = "utf-8"
            content_type = ""
            for k, v in headers:
                if k.lower() == "content-type":
                    content_type = v
                    charset_pos = v.find("charset")
                    if charset_pos > -1:
                        charset = v[charset_pos + 8:]
            if content_type.startswith("text/html"):
                # note we sometimes get "text/html" for xml, hence
                # extra test below
                content = FileAppIterWrapper(app_iter).read()
                content = content.decode(charset)
                if content and not content.startswith("<?xml"):
                    # get wordpress page content
                    try:
                        wp_status, wp_content = self.get_wordpress_content(
                            environ, environ['PATH_INFO'])
                        environ['ckanext.wordpresser.wp_status'] = wp_status
                        environ['ckanext.wordpresser.local_status'] = status
                        content = self.replace_relevant_bits(
                            content, wp_content, status, wp_status)
                        headers = [(k, v) for k, v in headers \
                                   if k != "Content-Length"]
                        headers.append(('Content-Length',
                                        str(len(content.encode('utf-8')))))

                        if not status.startswith("200"):
                            if not wp_status.startswith("404"):
                                status = wp_status
                        app_iter = [content]
                    except (HTTPMovedPermanently, HTTPFound), exc:
                        status = exc.status
                        content = ""
                        headers = [('Location', exc.location)]
Beispiel #8
0
 def __call__(self, environ, start_response):
     status, headers, app_iter, exc_info = call_wsgi_application(
         self.app, environ, catch_exc_info=True)
     if status[:3] == '401':
         login_url = tg.config.get('auth.login_url', '/auth/')
         if environ['REQUEST_METHOD'] == 'GET':
             return_to = environ['PATH_INFO']
             if environ.get('QUERY_STRING'):
                 return_to += '?' + environ['QUERY_STRING']
             location = tg.url(login_url, dict(return_to=return_to))
         else:
             # Don't try to re-post; the body has been lost.
             location = tg.url(login_url)
         r = exc.HTTPFound(location=location)
         return r(environ, start_response)
     start_response(status, headers, exc_info)
     return app_iter
Beispiel #9
0
 def __call__(self, environ, start_response):
     status, headers, app_iter, exc_info = call_wsgi_application(
         self.app, environ, catch_exc_info=True)
     if status[:3] == '401':
         login_url = tg.config.get('auth.login_url', '/auth/')
         if environ['REQUEST_METHOD'] == 'GET':
             return_to = environ['PATH_INFO']
             if environ.get('QUERY_STRING'):
                 return_to += '?' + environ['QUERY_STRING']
             location = tg.url(login_url, dict(return_to=return_to))
         else:
             # Don't try to re-post; the body has been lost.
             location = tg.url(login_url)
         r = exc.HTTPFound(location=location)
         return r(environ, start_response)
     start_response(status, headers, exc_info)
     return app_iter
Beispiel #10
0
    def __call__(self, environ, start_response):
        # Run application.
        status, headers, app_iter = call_wsgi_application(
            self.application, environ)

        # Get location header.
        location = None
        for (name, value) in headers:
            if name == "location":
                location = value
                break

        if location:
            # Redirection.

            redirect_exceptions = [('file_upload', 'upload')]
            controller = environ['wsgiorg.routing_args'][1]['controller']
            action = environ['wsgiorg.routing_args'][1]['action']

            if request.headers.get('X-KAjax', None):
                log.debug(
                    "KWMOMiddleware: redirecting through a kajax request to '%s'."
                    % (location))
                raise KJsonifyRedirect(location)

            elif (controller, action) in redirect_exceptions:
                log.debug("KWMOMiddleware: ignoring redirect to '%s'." %
                          (location))
                status = '200 OK'
                response_headers = [('Content-type', 'text/plain')]
                start_response(status, response_headers)
                return 'redirection:%s' % (location)

            else:
                log.debug("KWMOMiddleware: redirecting to '%s'." % (location))

        start_response(status, headers)
        return app_iter
 def __call__(self, environ, start_response):
     #log.debug ('** environ=\n%s' %(self.object_dumps(environ)))
     status_text, headers, app_iter = call_wsgi_application (self.app, environ, catch_exc_info=False)
     method = environ.get('REQUEST_METHOD')
     path   = environ.get('PATH_INFO')
     qs     = environ.get('QUERY_STRING')
     if status_text.startswith("404") and path.startswith(self.path_prefix):
         # The resource was not found: reverse-proxy this request to wordpress host
         path = path [len(self.path_prefix):]
         req_url = self.proxy_host.scheme + "://" + self.proxy_host.netloc + self.proxy_host.path + path + "?" + qs
         req_headers = self.request_headers(environ)
         log.info ('Proxying to URL: %s' %(req_url))
         # Proxy request
         res = None
         if method == 'GET':
             res = requests.get (req_url, headers=req_headers, stream=True)
         elif method == 'POST':
             with environ.get('wsgi.input') as reader:
                 req_data = reader.read()
             res = requests.post (req_url, headers=req_headers, data=req_data, stream=True)
         # Handle proxied request's result
         if res and res.ok:
             # succeded: return it's response
             log.info ("Proxied request (%s %s) succeded!" %(method, req_url))
             start_response ("%s %s" %(res.raw.status, res.raw.reason),
                 filter(lambda t: not (t[0] in ['server', 'x-pingback', 'x-powered-by']), res.headers.items()))
             return self.response_body_generator(res)
         else:
             # failed: return original Pylons response
             log.warning ("Proxied request (%s %s) failed: returning original 404 response" %(method, req_url))
             start_response (status_text, headers)
             return app_iter
     else:
         # The resource was either found or rejected: nop
         start_response (status_text, headers)
         return app_iter
     pass