Esempio n. 1
0
    def get_request(self, environ):
        request = Request(environ)
        request.app = self.app
        request.translations = load_core_translations(self.app.cfg['language'])
        request.is_admin = False
        request.is_somebody = False

        cookie_name = self.app.cfg['session_cookie_name']
        session = SecureCookie.load_cookie(
            request, cookie_name, self.app.cfg['secret_key'].encode('utf-8'))
        request.session = session
        engine = self.app.database_engine
        user_id = session.get('uid')

        if user_id:
            admin_privilege = engine.execute(
                privileges.select(
                    privileges.c.name == 'BLOG_ADMIN')).fetchone()

            admin = engine.execute(
                user_privileges.select(
                    and_(
                        user_privileges.c.user_id == int(user_id),
                        user_privileges.c.privilege_id ==
                        admin_privilege.privilege_id))).fetchone()
            request.is_somebody = True
            request.is_admin = admin is not None
        return request
Esempio n. 2
0
    def get_request(self, environ):
        request = Request(environ)
        request.app = self.app
        request.translations = load_core_translations(self.app.cfg['language'])
        request.is_admin = False
        request.is_somebody = False

        cookie_name = self.app.cfg['session_cookie_name']
        session = SecureCookie.load_cookie(
            request, cookie_name, self.app.cfg['secret_key'].encode('utf-8')
        )
        request.session = session
        engine = self.app.database_engine
        user_id = session.get('uid')

        if user_id:
            admin_privilege = engine.execute(
                privileges.select(privileges.c.name=='BLOG_ADMIN')
            ).fetchone()

            admin = engine.execute(user_privileges.select(and_(
                user_privileges.c.user_id==int(user_id),
                user_privileges.c.privilege_id==admin_privilege.privilege_id
            ))).fetchone()
            request.is_somebody = True
            request.is_admin = admin is not None
        return request
Esempio n. 3
0
 def wsgi_app(self, environ, start_response):
     script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
     if script_name:
         environ['SCRIPT_NAME'] = script_name
         path_info = environ['PATH_INFO']
         if path_info.startswith(script_name):
             environ['PATH_INFO'] = path_info[len(script_name):]
     request = Request(environ)
     request.app = self
     response = self.dispatch_request(request)
     return response(environ, start_response)
Esempio n. 4
0
 def wsgi_app(self, environ, start_response):
     script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
     if script_name:
         environ['SCRIPT_NAME'] = script_name
         path_info = environ['PATH_INFO']
         if path_info.startswith(script_name):
             environ['PATH_INFO'] = path_info[len(script_name):]
     request = Request(environ)
     request.app = self
     response = self.dispatch_request(request)
     return response(environ, start_response)
Esempio n. 5
0
    def call_backend(self, environ, start_response):
        request = Request(environ)

        # Compatibility with django, use request.args preferrably
        request.GET = request.args

        ## Routing / controller loading stuff
        map_adapter = self.url_map.bind_to_environ(request.environ)

        # By using fcgi, mediagoblin can run under a base path
        # like /mediagoblin/. request.path_info contains the
        # path inside mediagoblin. If the something needs the
        # full path of the current page, that should include
        # the basepath.
        # Note: urlgen and routes are fine!
        request.full_path = environ["SCRIPT_NAME"] + request.path
        # python-routes uses SCRIPT_NAME. So let's use that too.
        # The other option would be:
        # request.full_path = environ["SCRIPT_URL"]

        # Fix up environ for urlgen
        # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
        if environ.get('HTTPS', '').lower() == 'off':
            environ.pop('HTTPS')

        ## Attach utilities to the request object
        # Do we really want to load this via middleware?  Maybe?
        session_manager = self.session_manager
        request.session = session_manager.load_session_from_cookie(request)
        # Attach self as request.app
        # Also attach a few utilities from request.app for convenience?
        request.app = self

        request.db = self.db
        request.staticdirect = self.staticdirector

        request.locale = translate.get_locale_from_request(request)
        request.template_env = template.get_jinja_env(
            self.template_loader, request.locale)

        def build_proxy(endpoint, **kw):
            try:
                qualified = kw.pop('qualified')
            except KeyError:
                qualified = False

            return map_adapter.build(
                    endpoint,
                    values=dict(**kw),
                    force_external=qualified)

        request.urlgen = build_proxy

        # Log user out if authentication_disabled
        no_auth_logout(request)

        mg_request.setup_user_in_request(request)

        request.controller_name = None
        try:
            found_rule, url_values = map_adapter.match(return_rule=True)
            request.matchdict = url_values
        except RequestRedirect as response:
            # Deal with 301 responses eg due to missing final slash
            return response(environ, start_response)
        except HTTPException as exc:
            # Stop and render exception
            return render_http_exception(
                request, exc,
                exc.get_description(environ))(environ, start_response)

        controller = endpoint_to_controller(found_rule)
        # Make a reference to the controller's symbolic name on the request...
        # used for lazy context modification
        request.controller_name = found_rule.endpoint

        # pass the request through our meddleware classes
        try:
            for m in self.meddleware:
                response = m.process_request(request, controller)
                if response is not None:
                    return response(environ, start_response)
        except HTTPException as e:
            return render_http_exception(
                request, e,
                e.get_description(environ))(environ, start_response)

        request = hook_transform("modify_request", request)

        request.start_response = start_response

        # get the Http response from the controller
        try:
            response = controller(request)
        except HTTPException as e:
            response = render_http_exception(
                request, e, e.get_description(environ))

        # pass the response through the meddlewares
        try:
            for m in self.meddleware[::-1]:
                m.process_response(request, response)
        except HTTPException as e:
            response = render_http_exception(
                request, e, e.get_description(environ))

        session_manager.save_session_to_cookie(request.session,
                                               request, response)

        return response(environ, start_response)
Esempio n. 6
0
def _make_werkzeug_request(environ: dict) -> Request:
    """Make a werkzeug request from the given environ."""
    httprequest = Request(environ)
    _set_request_storage_class(httprequest)
    httprequest.app = root
    return httprequest
Esempio n. 7
0
    def call_backend(self, environ, start_response):
        request = Request(environ)

        ## Compatibility webob -> werkzeug
        request.GET = request.args
        request.accept_language = request.accept_languages
        request.accept = request.accept_mimetypes

        ## Routing / controller loading stuff
        path_info = request.path
        route_match = self.routing.match(path_info)

        # By using fcgi, mediagoblin can run under a base path
        # like /mediagoblin/. request.path_info contains the
        # path inside mediagoblin. If the something needs the
        # full path of the current page, that should include
        # the basepath.
        # Note: urlgen and routes are fine!
        request.full_path = environ["SCRIPT_NAME"] + request.path
        # python-routes uses SCRIPT_NAME. So let's use that too.
        # The other option would be:
        # request.full_path = environ["SCRIPT_URL"]

        # Fix up environ for urlgen
        # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
        if environ.get('HTTPS', '').lower() == 'off':
            environ.pop('HTTPS')

        ## Attach utilities to the request object
        request.matchdict = route_match
        request.urlgen = routes.URLGenerator(self.routing, environ)
        # Do we really want to load this via middleware?  Maybe?
        request.session = request.environ['beaker.session']
        # Attach self as request.app
        # Also attach a few utilities from request.app for convenience?
        request.app = self
        request.locale = translate.get_locale_from_request(request)

        request.template_env = template.get_jinja_env(
            self.template_loader, request.locale)
        request.db = self.db
        request.staticdirect = self.staticdirector

        mg_request.setup_user_in_request(request)

        # No matching page?
        if route_match is None:
            # Try to do see if we have a match with a trailing slash
            # added and if so, redirect
            if not path_info.endswith('/') \
                    and request.method == 'GET' \
                    and self.routing.match(path_info + '/'):
                new_path_info = path_info + '/'
                if request.GET:
                    new_path_info = '%s?%s' % (
                        new_path_info, urllib.urlencode(request.GET))
                redirect = exc.HTTPFound(location=new_path_info)
                return request.get_response(redirect)(environ, start_response)

            # Okay, no matches.  404 time!
            request.matchdict = {}  # in case our template expects it
            return render_404(request)(environ, start_response)

        # import the controller, or if it's already a callable, call that
        route_controller = route_match['controller']
        if isinstance(route_controller, unicode) \
                or isinstance(route_controller, str):
            controller = common.import_component(route_match['controller'])
        else:
            controller = route_match['controller']

        # pass the request through our meddleware classes
        for m in self.meddleware:
            response = m.process_request(request, controller)
            if response is not None:
                return response(environ, start_response)

        request.start_response = start_response

        # get the response from the controller
        response = controller(request)

        # pass the response through the meddleware
        for m in self.meddleware[::-1]:
            m.process_response(request, response)

        return response(environ, start_response)