示例#1
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        controller = environ['pylons.routes_dict']['controller']

        if controller == 'template':
            return WSGIController.__call__(self, environ, start_response)
        username = environ.get('REMOTE_USER')
        if not username and controller != 'config':
            return WSGIResponse(content='please log in', code=401)

        if environ.get('AUTHENTICATION_METHOD') != 'WSSE':
            if controller == 'watch' or controller == 'user':
                c.user = User.get_or_create(username)
            else:
                if (environ.get('REMOTE_ADDR').startswith('127.0.0.1') and controller == 'config') or controller == 'error':
                    #local users can configure Twirlip and see errors
                    pass
                else:
                    #all other authentication must be by wsse
                    return WSGIResponse(code=403, content='You need to authenticate with wsse to access %s ' % controller)
            
        if controller == 'page':
            #json
            self.params = {}
            for param, value in request.params.items():
                self.params[param] = loads(value)
                    
        return WSGIController.__call__(self, environ, start_response)
示例#2
0
文件: base.py 项目: aureg/baruwa2
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        def check_url():
            if ('format' in environ['pylons.routes_dict'] and
                environ['pylons.routes_dict']['format'] in ['csv', 'pdf']):
                return False
            if environ['PATH_INFO'] == '/jsi18n.js':
                return False
            return True

        self.identity = environ.get('repoze.who.identity')
        # raise ValueError(self.identity)
        # if 'baruwa.auth.plugin' in self.identity:
        #     session['baruwa.auth.plugin'] = self.identity['baruwa.auth.plugin']
        #     session.save()
        if (not self.identity is None and 'user' in self.identity and
            environ['pylons.routes_dict']['controller'] != 'error' and
            check_url()):

            if self.identity['user']:
                totals = DailyTotals(Session, self.identity['user'])
                mailq = MailQueue(Session, self.identity['user'])
                c.baruwa_totals = totals.get()
                c.baruwa_inbound = mailq.get(1)[0]
                c.baruwa_outbound = mailq.get(2)[0]
                if self.identity['user'].is_admin:
                    c.baruwa_status = cluster_status()
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()
示例#3
0
文件: base.py 项目: yujiro/rhodecode
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     start = time.time()
     try:
         self.ip_addr = _get_ip_addr(environ)
         # make sure that we update permissions each time we call controller
         api_key = request.GET.get("api_key")
         cookie_store = CookieStoreWrapper(session.get("rhodecode_user"))
         user_id = cookie_store.get("user_id", None)
         username = get_container_username(environ, config)
         auth_user = AuthUser(user_id, api_key, username)
         request.user = auth_user
         self.rhodecode_user = c.rhodecode_user = auth_user
         if not self.rhodecode_user.is_authenticated and self.rhodecode_user.user_id is not None:
             self.rhodecode_user.set_authenticated(cookie_store.get("is_authenticated"))
         log.info("IP: %s User: %s accessed %s" % (self.ip_addr, auth_user, safe_unicode(_get_access_path(environ))))
         return WSGIController.__call__(self, environ, start_response)
     finally:
         log.info(
             "IP: %s Request to %s time: %.3fs"
             % (_get_ip_addr(environ), safe_unicode(_get_access_path(environ)), time.time() - start)
         )
         meta.Session.remove()
示例#4
0
    def __call__(self, environ, start_response):
        # Insert any code to be run per request here. The Routes match
        # is under environ['pylons.routes_dict'] should you want to check
        # the action or route vars here

        # Grab Domain Info
        self.domain = request.environ['REMOTE_USER']
        self.dominfo = get_domain_info(self.domain)

        # Don't allow Locked Domains to make any changes
        if self.dominfo['ispmanDomainLocked'] == 'true' and \
           request.path_info != '/locked':
            h.redirect_to('/locked')
        elif request.path_info == '/':
            h.redirect_to('/domain')

        ccache = cache.get_cache('navigation')

        c.menus = ccache.get_value('i18n_menus',
                                  createfunc=self.__create_i18n_menus,
                                  type='memory', expiretime=3600)

        c.controller = request.environ['pylons.routes_dict']['controller']
        c.action = request.environ['pylons.routes_dict']['action']

        c.imgs_list = self.__images_list()

        if 'message' in session and session['message'] != '':
            c.message = session['message']
            session['message'] = ''
            session.save()

        return WSGIController.__call__(self, environ, start_response)
示例#5
0
文件: base.py 项目: cemeyer2/comoto
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # Insert any code to be run per request here.
        # hg parents --template="r{rev} {date|date} by {author}\n"
        hg_args = ['hg', 'parents', '--template="r{rev} {date|date} by {author}\n"']
        hg_process = subprocess.Popen(hg_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=os.path.dirname(__file__))
        c.revision = hg_process.stdout.readline().strip()[1:]
        if request.environ['HTTP_HOST'].startswith("comoto") and h.get_user(request.environ).superuser: #we are running on the production server and we are a superuser
            hg_args = ['hg', 'incoming', '--template="{rev}\n"']
            hg_process = subprocess.Popen(hg_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=os.path.dirname(__file__))
            incoming_changesets = -2 #start with -4 because of extra lines printed
            while True:
                output = hg_process.stdout.readline()
		if len(output) > 2:
               	    incoming_changesets+=1
                if output.startswith("no"):
                    incoming_changesets = 0
                    break
                if output == '' or hg_process.poll() != None:
                    break
            c.incoming_changesets = incoming_changesets
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            model.Session.remove()
示例#6
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # Moved here from index controller so that all views that import the news.mako template
        # have access to c.db_content_news and c.db_content_press
        news = DbContentType.find_by_name("News", abort_404=False)
        if news:
            c.db_content_news = meta.Session.query(DbContent).filter_by(
                type_id=news.id, published=True).order_by(
                    DbContent.creation_timestamp.desc()).limit(4).all()
            c.db_content_news_all = meta.Session.query(DbContent).filter_by(
                type_id=news.id,
                published=True).order_by(DbContent.creation_timestamp.desc(
                )).all()  #use all to find featured items

        press = DbContentType.find_by_name("In the press", abort_404=False)
        if press:
            c.db_content_press = meta.Session.query(DbContent).filter_by(
                type_id=press.id, published=True).order_by(
                    DbContent.creation_timestamp.desc()).limit(4).all()

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
示例#7
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        tmpl_context.current_navtab = 'blah'
        tmpl_context.current_subnavtab = 'blakj'
        tmpl_context.status = 1
        tmpl_context.messagebar_text = ''
        tmpl_context.message = ''
        tmpl_context.username = ''

        beaker = environ.get('beaker.session') or {}
        try:
            timeout = int(config.get('cw.timeout'))
        except Exception:
            timeout = 0
        if timeout and beaker.get('user_id'):
            last_access = beaker.get('last_accessed') or False
            if last_access and datetime.now() - last_access > timedelta(minutes=timeout):
                try:
                    return "Your session has timed out. You have been logged out for security."
                finally:
                    Session.remove()
            beaker['last_accessed'] = datetime.now()
            beaker.save()

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()
示例#8
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # Clean out any old cookies as they may contain api keys etc
        # This also improves the cachability of our pages as cookies
        # prevent proxy servers from caching content unless they have
        # been configured to ignore them.
        for cookie in request.cookies:
            if cookie.startswith('ckan') and cookie not in ['ckan']:
                response.delete_cookie(cookie)
            # Remove the ckan session cookie if not used e.g. logged out
            elif cookie == 'ckan' and not c.user and not h.are_there_flash_messages(
            ):
                if session.id:
                    if not session.get('lang'):
                        session.delete()
                else:
                    response.delete_cookie(cookie)
            # Remove auth_tkt repoze.who cookie if user not logged in.
            elif cookie == 'auth_tkt' and not session.id:
                response.delete_cookie(cookie)

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            model.Session.remove()
示例#9
0
文件: base.py 项目: novalis/Anagrams
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        environ = request.environ
        controller = environ['pylons.routes_dict'].get('controller')
        if request.method == "POST" and controller != "auth" and controller != "hookbox" and controller != 'error':
            params = request.params
            submitted_token = params.get(secure_form.token_key)
            if submitted_token != secure_form.authentication_token():
                #raise RuntimeError("Not secure")
                pass #FIXME: uncomment above

        user_id = session.get("user_id")
        if user_id:
            c.user = self.user = User.get(user_id)
            if not self.user.is_logged_in():
                del session["user_id"]
                c.user = self.user = None
        else:
            c.user = self.user = None


        #generate hookbox server url
        hookbox_server = url('/', qualified=True)
        parsed = urlparse(hookbox_server)
        #a really fancy way of saying host:8001
        c.hookbox_server = parsed.scheme + "://" + parsed.hostname + ":" + config["hookbox_js_port"]

        return WSGIController.__call__(self, environ, start_response)
示例#10
0
文件: base.py 项目: NERC-CEH/ecomaps
    def __call__(self, environ, start_response):
        """Invoke the Controller"""

        # Before we do anything, is there a "REMOTE USER"?
        # If not, we've not been authenticated!
        if not environ.get('REMOTE_USER') and 'login' not in environ.get('PATH_INFO'):
            raise httpexceptions.HTTPUnauthorized()

        # Redirect to a canonical form of the URL if necessary.
        self._redirect_noncanonical_url(environ)

        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict'

        if 'login' not in environ.get('PATH_INFO'):
            self.current_user = self._user_service.get_user_by_username(environ.get('REMOTE_USER'))

            if not self.current_user:
                raise httpexceptions.HTTPUnauthorized()

            if self.current_user.access_level == "Admin":
                c.admin_user = True
            else:
                c.admin_user = False

        return WSGIController.__call__(self, environ, start_response)
示例#11
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        return WSGIController.__call__(self, environ, start_response)
示例#12
0
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     response.headers['content-type'] = 'application/json;charset=utf-8'
     return WSGIController.__call__(self, environ, start_response)
示例#13
0
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     response.headers["content-type"] = "application/json;charset=utf-8"
     return WSGIController.__call__(self, environ, start_response)
示例#14
0
文件: base.py 项目: jhesketh/zookeepr
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        person = h.signed_in_person()
        if person and not person.activated:
            msg = ("Your account (%s) hasn't been confirmed. Check your email"
                   " for activation instructions." %
                   (person.email_address))
            h.flash(msg, category="warning")

        # Moved here from index controller so that all views that import the news.mako template
        # have access to c.db_content_news and c.db_content_press
        news = DbContentType.find_by_name("News", abort_404 = False)
        if news:
            c.db_content_news = meta.Session.query(DbContent).filter_by(type_id=news.id).filter(DbContent.publish_timestamp <= datetime.datetime.now()).order_by(DbContent.creation_timestamp.desc()).limit(4).all()
            c.db_content_news_all = meta.Session.query(DbContent).filter_by(type_id=news.id).filter(DbContent.publish_timestamp <= datetime.datetime.now()).order_by(DbContent.creation_timestamp.desc()).all() #use all to find featured items

        press = DbContentType.find_by_name("In the press", abort_404 = False)
        if press:
            c.db_content_press = meta.Session.query(DbContent).filter_by(type_id=press.id).order_by(DbContent.creation_timestamp.desc()).filter(DbContent.publish_timestamp <= datetime.datetime.now()).limit(4).all()


        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
示例#15
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            self.ip_addr = _get_ip_addr(environ)
            # make sure that we update permissions each time we call controller
            api_key = request.GET.get('api_key')
            cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
            user_id = cookie_store.get('user_id', None)
            username = get_container_username(environ, config)
            try:
                auth_user = AuthUser(user_id, api_key, username, self.ip_addr)
            except UserCreationError, e:
                from rhodecode.lib import helpers as h
                h.flash(e, 'error')
                # container auth or other auth functions that create users on
                # the fly can throw this exception signaling that there's issue
                # with user creation, explanation should be provided in
                # Exception itself
                auth_user = AuthUser(ip_addr=self.ip_addr)

            request.user = auth_user
            self.rhodecode_user = c.rhodecode_user = auth_user
            if not self.rhodecode_user.is_authenticated and \
                       self.rhodecode_user.user_id is not None:
                self.rhodecode_user.set_authenticated(
                    cookie_store.get('is_authenticated')
                )
            log.info('IP: %s User: %s accessed %s' % (
               self.ip_addr, auth_user, safe_unicode(_get_access_path(environ)))
            )
            return WSGIController.__call__(self, environ, start_response)
示例#16
0
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     start = time.time()
     try:
         # make sure that we update permissions each time we call controller
         api_key = request.GET.get('api_key')
         cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
         user_id = cookie_store.get('user_id', None)
         username = get_container_username(environ, config)
         auth_user = AuthUser(user_id, api_key, username)
         request.user = auth_user
         self.rhodecode_user = c.rhodecode_user = auth_user
         if not self.rhodecode_user.is_authenticated and \
                    self.rhodecode_user.user_id is not None:
             self.rhodecode_user.set_authenticated(
                 cookie_store.get('is_authenticated')
             )
         log.info('User: %s accessed %s' % (
             auth_user, safe_unicode(environ.get('PATH_INFO')))
         )
         return WSGIController.__call__(self, environ, start_response)
     finally:
         log.info('Request to %s time: %.3fs' % (
             safe_unicode(environ.get('PATH_INFO')), time.time() - start)
         )
         meta.Session.remove()
示例#17
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        return WSGIController.__call__(self, environ, start_response)
示例#18
0
    def __call__(self, environ, start_response):
        # we override this here to ensure that this header, and only this
        # header, is trusted to reduce the number of potential
        # misconfigurations between wsgi application servers (e.g. gunicorn
        # which trusts three different headers out of the box for this) and
        # haproxy (which won't clean out bad headers by default)
        forwarded_proto = environ.get("HTTP_X_FORWARDED_PROTO", "http").lower()
        assert forwarded_proto in ("http", "https")
        request.environ["wsgi.url_scheme"] = forwarded_proto

        true_client_ip = environ.get('HTTP_TRUE_CLIENT_IP')
        ip_hash = environ.get('HTTP_TRUE_CLIENT_IP_HASH')
        forwarded_for = environ.get('HTTP_X_FORWARDED_FOR', ())
        remote_addr = environ.get('REMOTE_ADDR')

        if (g.ip_hash
            and true_client_ip
            and ip_hash
            and hashlib.md5(true_client_ip + g.ip_hash).hexdigest() \
            == ip_hash.lower()):
            request.ip = true_client_ip
        elif g.trust_local_proxies and forwarded_for and is_local_address(remote_addr):
            request.ip = forwarded_for.split(',')[-1]
        else:
            request.ip = environ['REMOTE_ADDR']

        #if x-dont-decode is set, pylons won't unicode all the paramters
        if environ.get('HTTP_X_DONT_DECODE'):
            request.charset = None

        request.get = storify(request.GET)
        request.post = storify(request.POST)
        request.referer = environ.get('HTTP_REFERER')
        request.user_agent = environ.get('HTTP_USER_AGENT')
        request.fullpath = environ.get('FULLPATH', request.path)
        request.fullurl = request.host_url + request.fullpath
        request.port = environ.get('request_port')
        
        if_modified_since = environ.get('HTTP_IF_MODIFIED_SINCE')
        if if_modified_since:
            request.if_modified_since = read_http_date(if_modified_since)
        else:
            request.if_modified_since = None

        #set the function to be called
        action = request.environ['pylons.routes_dict'].get('action')
        if action:
            meth = request.method.upper()
            if meth == 'HEAD':
                meth = 'GET'

            if meth != 'OPTIONS':
                handler_name = meth + '_' + action
            else:
                handler_name = meth

            request.environ['pylons.routes_dict']['action_name'] = action
            request.environ['pylons.routes_dict']['action'] = handler_name

        return WSGIController.__call__(self, environ, start_response)
示例#19
0
    def __call__(self, environ, start_response):
        """Invoke the Controller."""
        # set the language fallback to english
        add_fallback("en")
        # define the language based on browser preference
        user_agent_language = request.languages[0][0:2]
        set_lang(user_agent_language)
        formencode.api.set_stdtranslation(user_agent_language)

        # common values mostly inherited from config file
        c.version = __version__ # TODO move this into the development.ini file
        c.site_full_name = config["site_full_name"] # TODO move this into the development.ini file
        c.site_short_name = config["site_short_name"] # TODO move this into the development.ini file

        # controler and action named for use in templates
        #c.controller = request.environ['pylons.routes_dict']['controller']
        #c.action = request.environ['pylons.routes_dict']['action']

        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
示例#20
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        def check_url():
            "check if user should have totals calculated"
            if ('format' in environ['pylons.routes_dict'] and
                environ['pylons.routes_dict']['format'] in ['csv', 'pdf']):
                return False
            if environ['PATH_INFO'] == '/jsi18n.js':
                return False
            return True

        self.identity = environ.get('repoze.who.identity')
        if (self.identity is not None and 'user' in self.identity and
            environ['pylons.routes_dict']['controller'] != 'error' and
            check_url()):

            if self.identity['user']:
                totals = DailyTotals(Session, self.identity['user'])
                mailq = MailQueue(Session, self.identity['user'])
                c.baruwa_totals = totals.get()
                c.baruwa_inbound = mailq.get(1)[0]
                c.baruwa_outbound = mailq.get(2)[0]
                if self.identity['user'].is_admin:
                    c.baruwa_status = cluster_status()

                tzinfo = self.identity['user'].timezone or UTC
                c.tzinfo = make_tz(tzinfo)
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()
示例#21
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        def check_url():
            "check if user should have totals calculated"
            if ('format' in environ['pylons.routes_dict'] and
                    environ['pylons.routes_dict']['format'] in ['csv', 'pdf']):
                return False
            if environ['PATH_INFO'] == '/jsi18n.js':
                return False
            return True

        self.identity = environ.get('repoze.who.identity')
        if (self.identity is not None and 'user' in self.identity
                and environ['pylons.routes_dict']['controller'] != 'error'
                and check_url()):

            if self.identity['user']:
                totals = DailyTotals(Session, self.identity['user'])
                mailq = MailQueue(Session, self.identity['user'])
                c.baruwa_totals = totals.get()
                c.baruwa_inbound = mailq.get(1)[0]
                c.baruwa_outbound = mailq.get(2)[0]
                if self.identity['user'].is_admin:
                    c.baruwa_status = cluster_status()

                tzinfo = self.identity['user'].timezone or UTC
                c.tzinfo = make_tz(tzinfo)
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()
示例#22
0
文件: base.py 项目: wcmckee/zookeepr
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        person = h.signed_in_person()
        if person and not person.activated:
            msg = ("Your account (%s) hasn't been confirmed. Check your email"
                   " for activation instructions. %s" %
                   (person.email_address, 'link-to-reset'))
            h.flash(msg, category="warning")

        # Moved here from index controller so that all views that import the news.mako template
        # have access to c.db_content_news and c.db_content_press
        news = DbContentType.find_by_name("News", abort_404 = False)
        if news:
            c.db_content_news = meta.Session.query(DbContent).filter_by(type_id=news.id).filter(DbContent.publish_timestamp <= datetime.datetime.now()).order_by(DbContent.creation_timestamp.desc()).limit(4).all()
            c.db_content_news_all = meta.Session.query(DbContent).filter_by(type_id=news.id).filter(DbContent.publish_timestamp <= datetime.datetime.now()).order_by(DbContent.creation_timestamp.desc()).all() #use all to find featured items

        press = DbContentType.find_by_name("In the press", abort_404 = False)
        if press:
            c.db_content_press = meta.Session.query(DbContent).filter_by(type_id=press.id).order_by(DbContent.creation_timestamp.desc()).filter(DbContent.publish_timestamp <= datetime.datetime.now()).limit(4).all()


        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
示例#23
0
    def __call__(self, environ, start_response):
        # we override this here to ensure that this header, and only this
        # header, is trusted to reduce the number of potential
        # misconfigurations between wsgi application servers (e.g. gunicorn
        # which trusts three different headers out of the box for this) and
        # haproxy (which won't clean out bad headers by default)
        forwarded_proto = environ.get("HTTP_X_FORWARDED_PROTO", "http").lower()
        assert forwarded_proto in ("http", "https")
        request.environ["wsgi.url_scheme"] = forwarded_proto

        true_client_ip = environ.get('HTTP_TRUE_CLIENT_IP')
        ip_hash = environ.get('HTTP_TRUE_CLIENT_IP_HASH')
        forwarded_for = environ.get('HTTP_X_FORWARDED_FOR', ())
        remote_addr = environ.get('REMOTE_ADDR')

        request.via_cdn = False
        if (g.secrets["true_ip"]
            and true_client_ip
            and ip_hash
            and hashlib.md5(true_client_ip + g.secrets["true_ip"]).hexdigest() \
            == ip_hash.lower()):
            request.ip = true_client_ip
            request.via_cdn = True
        elif g.trust_local_proxies and forwarded_for and is_local_address(remote_addr):
            request.ip = forwarded_for.split(',')[-1]
        else:
            request.ip = environ['REMOTE_ADDR']

        #if x-dont-decode is set, pylons won't unicode all the parameters
        if environ.get('HTTP_X_DONT_DECODE'):
            request.charset = None

        request.referer = environ.get('HTTP_REFERER')
        request.user_agent = environ.get('HTTP_USER_AGENT')
        request.fullpath = environ.get('FULLPATH', request.path)
        request.fullurl = request.host_url + request.fullpath
        request.port = environ.get('request_port')
        
        if_modified_since = environ.get('HTTP_IF_MODIFIED_SINCE')
        if if_modified_since:
            request.if_modified_since = read_http_date(if_modified_since)
        else:
            request.if_modified_since = None

        #set the function to be called
        action = request.environ['pylons.routes_dict'].get('action')
        if action:
            meth = request.method.upper()
            if meth == 'HEAD':
                meth = 'GET'

            if meth != 'OPTIONS':
                handler_name = meth + '_' + action
            else:
                handler_name = meth

            request.environ['pylons.routes_dict']['action_name'] = action
            request.environ['pylons.routes_dict']['action'] = handler_name

        return WSGIController.__call__(self, environ, start_response)
示例#24
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        def check_url():
            if ('format' in environ['pylons.routes_dict'] and
                    environ['pylons.routes_dict']['format'] in ['csv', 'pdf']):
                return False
            if environ['PATH_INFO'] == '/jsi18n.js':
                return False
            return True

        self.identity = environ.get('repoze.who.identity')
        # raise ValueError(self.identity)
        # if 'baruwa.auth.plugin' in self.identity:
        #     session['baruwa.auth.plugin'] = self.identity['baruwa.auth.plugin']
        #     session.save()
        if (not self.identity is None and 'user' in self.identity
                and environ['pylons.routes_dict']['controller'] != 'error'
                and check_url()):

            if self.identity['user']:
                totals = DailyTotals(Session, self.identity['user'])
                mailq = MailQueue(Session, self.identity['user'])
                c.baruwa_totals = totals.get()
                c.baruwa_inbound = mailq.get(1)[0]
                c.baruwa_outbound = mailq.get(2)[0]
                if self.identity['user'].is_admin:
                    c.baruwa_status = cluster_status()
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()
示例#25
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # Clean out any old cookies as they may contain api keys etc
        # This also improves the cachability of our pages as cookies
        # prevent proxy servers from caching content unless they have
        # been configured to ignore them.
        for cookie in request.cookies:
            if cookie.startswith("ckan") and cookie not in ["ckan"]:
                response.delete_cookie(cookie)
            # Remove the ckan session cookie if not used e.g. logged out
            elif cookie == "ckan" and not c.user and not h.are_there_flash_messages():
                if session.id:
                    if not session.get("lang"):
                        session.delete()
                else:
                    response.delete_cookie(cookie)
            # Remove auth_tkt repoze.who cookie if user not logged in.
            elif cookie == "auth_tkt" and not session.id:
                response.delete_cookie(cookie)

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            model.Session.remove()
示例#26
0
文件: base.py 项目: khodges42/reddit
    def __call__(self, environ, start_response):
        # we override this here to ensure that this header, and only this
        # header, is trusted to reduce the number of potential
        # misconfigurations between wsgi application servers (e.g. gunicorn
        # which trusts three different headers out of the box for this) and
        # haproxy (which won't clean out bad headers by default)
        forwarded_proto = environ.get("HTTP_X_FORWARDED_PROTO", "http").lower()
        assert forwarded_proto in ("http", "https")
        request.environ["wsgi.url_scheme"] = forwarded_proto

        forwarded_for = environ.get('HTTP_X_FORWARDED_FOR', ())
        remote_addr = environ.get('REMOTE_ADDR')

        request.via_cdn = False
        cdn_ip = g.cdn_provider.get_client_ip(environ)
        if cdn_ip:
            request.ip = cdn_ip
            request.via_cdn = True
        elif g.trust_local_proxies and forwarded_for and is_local_address(remote_addr):
            request.ip = forwarded_for.split(',')[-1]
        else:
            request.ip = environ['REMOTE_ADDR']

        #if x-dont-decode is set, pylons won't unicode all the parameters
        if environ.get('HTTP_X_DONT_DECODE'):
            request.charset = None

        request.referer = environ.get('HTTP_REFERER')
        request.user_agent = environ.get('HTTP_USER_AGENT')
        request.fullpath = environ.get('FULLPATH', request.path)
        request.fullurl = request.host_url + request.fullpath
        request.port = environ.get('request_port')
        
        if_modified_since = environ.get('HTTP_IF_MODIFIED_SINCE')
        if if_modified_since:
            request.if_modified_since = read_http_date(if_modified_since)
        else:
            request.if_modified_since = None

        #set the function to be called
        action = request.environ['pylons.routes_dict'].get('action')

        if (request.environ.get('r2.controller.exception') and action == 'document'
                and request.environ.get('render_style') == 'api'):
            action = 'api_error'
        if action:
            meth = request.method.upper()
            if meth == 'HEAD':
                meth = 'GET'

            if (meth == 'OPTIONS' and
                    self._get_action_handler(action, meth) is None):
                handler_name = meth
            else:
                handler_name = meth + '_' + action

            request.environ['pylons.routes_dict']['action_name'] = action
            request.environ['pylons.routes_dict']['action'] = handler_name

        return WSGIController.__call__(self, environ, start_response)
示例#27
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        try:
            res = WSGIController.__call__(self, environ, start_response)
        finally:
            model.Session.remove()

        for cookie in request.cookies:
            # Remove the ckan session cookie if not used e.g. logged out
            if cookie == "ckan" and not c.user:
                # Check session for valid data (including flash messages)
                # (DGU also uses session for a shopping basket-type behaviour)
                is_valid_cookie_data = False
                for key, value in session.items():
                    if not key.startswith("_") and value:
                        is_valid_cookie_data = True
                        break
                if not is_valid_cookie_data:
                    if session.id:
                        self.log.debug("No valid session data - " "deleting session")
                        self.log.debug("Session: %r", session.items())
                        session.delete()
                    else:
                        self.log.debug("No session id - " "deleting session cookie")
                        response.delete_cookie(cookie)
            # Remove auth_tkt repoze.who cookie if user not logged in.
            elif cookie == "auth_tkt" and not session.id:
                response.delete_cookie(cookie)

        return res
示例#28
0
文件: base.py 项目: 9peppe/reddit
    def __call__(self, environ, start_response):
        true_client_ip = environ.get('HTTP_TRUE_CLIENT_IP')
        ip_hash = environ.get('HTTP_TRUE_CLIENT_IP_HASH')
        forwarded_for = environ.get('HTTP_X_FORWARDED_FOR', ())
        remote_addr = environ.get('REMOTE_ADDR')

        if (g.ip_hash
            and true_client_ip
            and ip_hash
            and hashlib.md5(true_client_ip + g.ip_hash).hexdigest() \
            == ip_hash.lower()):
            request.ip = true_client_ip
        elif g.trust_local_proxies and forwarded_for and is_local_address(remote_addr):
            request.ip = forwarded_for.split(',')[-1]
        else:
            request.ip = environ['REMOTE_ADDR']

        #if x-dont-decode is set, pylons won't unicode all the paramters
        if environ.get('HTTP_X_DONT_DECODE'):
            request.charset = None

        request.get = storify(request.GET)
        request.post = storify(request.POST)
        request.referer = environ.get('HTTP_REFERER')
        request.user_agent = environ.get('HTTP_USER_AGENT')
        request.fullpath = environ.get('FULLPATH', request.path)
        request.port = environ.get('request_port')
        
        if_modified_since = environ.get('HTTP_IF_MODIFIED_SINCE')
        if if_modified_since:
            request.if_modified_since = read_http_date(if_modified_since)
        else:
            request.if_modified_since = None

        #set the function to be called
        action = request.environ['pylons.routes_dict'].get('action')
        if action:
            meth = request.method.upper()
            if meth == 'HEAD':
                meth = 'GET'

            if meth != 'OPTIONS':
                handler_name = meth + '_' + action
            else:
                handler_name = meth

            request.environ['pylons.routes_dict']['action_name'] = action
            request.environ['pylons.routes_dict']['action'] = handler_name
                    
        try:
            res = WSGIController.__call__(self, environ, start_response)
        except Exception as e:
            if g.exception_logging and not isinstance(e, OPERATIONAL_EXCEPTIONS):
                try:
                    log_exception(e, *sys.exc_info())
                except Exception as f:
                    print "log_exception() freaked out: %r" % f
                    print "sorry for breaking the stack trace:"
            raise
        return res
示例#29
0
 def __call__(self, environ, start_response):
     conn = meta.engine.connect()
     meta.Session.configure(bind=conn)
     try:
         return WSGIController.__call__(self, environ, start_response)
     finally:
         meta.Session.remove()
         conn.close()
示例#30
0
文件: base.py 项目: Pylons/kai
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     pylons.tmpl_context.db = self.db = Database(pylons.config['couchdb_uri'])
     self._setup()
     
     pylons.tmpl_context.use_minified_assets = asbool(
         pylons.config.get('use_minified_assets', 'false'))
     return WSGIController.__call__(self, environ, start_response)
示例#31
0
文件: base.py 项目: ketralnis/reddit
    def __call__(self, environ, start_response):
        true_client_ip = environ.get("HTTP_TRUE_CLIENT_IP")
        ip_hash = environ.get("HTTP_TRUE_CLIENT_IP_HASH")
        forwarded_for = environ.get("HTTP_X_FORWARDED_FOR", ())
        remote_addr = environ.get("REMOTE_ADDR")

        if (
            g.ip_hash
            and true_client_ip
            and ip_hash
            and hashlib.md5(true_client_ip + g.ip_hash).hexdigest() == ip_hash.lower()
        ):
            request.ip = true_client_ip
        elif remote_addr in g.proxy_addr and forwarded_for:
            request.ip = forwarded_for.split(",")[-1]
        else:
            request.ip = environ["REMOTE_ADDR"]

        # if x-dont-decode is set, pylons won't unicode all the paramters
        if environ.get("HTTP_X_DONT_DECODE"):
            request.charset = None

        request.get = storify(request.GET)
        request.post = storify(request.POST)
        request.referer = environ.get("HTTP_REFERER")
        request.path = environ.get("PATH_INFO")
        request.user_agent = environ.get("HTTP_USER_AGENT")
        request.fullpath = environ.get("FULLPATH", request.path)
        request.port = environ.get("request_port")

        if_modified_since = environ.get("HTTP_IF_MODIFIED_SINCE")
        if if_modified_since:
            request.if_modified_since = read_http_date(if_modified_since)
        else:
            request.if_modified_since = None

        # set the function to be called
        action = request.environ["pylons.routes_dict"].get("action")
        if action:
            meth = request.method.upper()
            if meth == "HEAD":
                meth = "GET"
            request.environ["pylons.routes_dict"]["action"] = meth + "_" + action

        c.thread_pool = environ["paste.httpserver.thread_pool"]

        c.response = Response()
        try:
            res = WSGIController.__call__(self, environ, start_response)
        except Exception as e:
            if g.exception_logging:
                try:
                    log_exception(e, *sys.exc_info())
                except Exception as f:
                    print "log_exception() freaked out: %r" % f
                    print "sorry for breaking the stack trace:"
            raise
        return res
示例#32
0
文件: base.py 项目: tigers08/reddit
    def __call__(self, environ, start_response):
        true_client_ip = environ.get('HTTP_TRUE_CLIENT_IP')
        ip_hash = environ.get('HTTP_TRUE_CLIENT_IP_HASH')
        forwarded_for = environ.get('HTTP_X_FORWARDED_FOR', ())
        remote_addr = environ.get('REMOTE_ADDR')

        if (g.ip_hash
            and true_client_ip
            and ip_hash
            and hashlib.md5(true_client_ip + g.ip_hash).hexdigest() \
            == ip_hash.lower()):
            request.ip = true_client_ip
        elif remote_addr in g.proxy_addr and forwarded_for:
            request.ip = forwarded_for.split(',')[-1]
        else:
            request.ip = environ['REMOTE_ADDR']

        #if x-dont-decode is set, pylons won't unicode all the paramters
        if environ.get('HTTP_X_DONT_DECODE'):
            request.charset = None

        request.get = storify(request.GET)
        request.post = storify(request.POST)
        request.referer = environ.get('HTTP_REFERER')
        request.path = environ.get('PATH_INFO')
        request.user_agent = environ.get('HTTP_USER_AGENT')
        request.fullpath = environ.get('FULLPATH', request.path)
        request.port = environ.get('request_port')
        
        if_modified_since = environ.get('HTTP_IF_MODIFIED_SINCE')
        if if_modified_since:
            request.if_modified_since = read_http_date(if_modified_since)
        else:
            request.if_modified_since = None

        #set the function to be called
        action = request.environ['pylons.routes_dict'].get('action')
        if action:
            meth = request.method.upper()
            if meth == 'HEAD':
                meth = 'GET'
            request.environ['pylons.routes_dict']['action'] = \
                    meth + '_' + action

        c.thread_pool = environ['paste.httpserver.thread_pool']

        c.response = Response()
        try:
            res = WSGIController.__call__(self, environ, start_response)
        except Exception as e:
            if g.exception_logging:
                try:
                    log_exception(e, *sys.exc_info())
                except Exception as f:
                    print "log_exception() freaked out: %r" % f
                    print "sorry for breaking the stack trace:"
            raise
        return res
示例#33
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            self._session = Session

            auth.authenticate_basic_auth()

            if '_debug_frontend' in request.params:
                #now we can force this no matter the environment.
                c.debug_frontend = request.params['_debug_frontend'] == 'True'
            else:
                c.debug_frontend = not h.is_production()

            #this is used by timer proxy and the templates
            c.show_debug = bool(session.get('show_debug'))

            request.environ['USER'] = session.get('username', '')
            request.environ['REAL_USER'] = session.get('real_username', '')

            # set the start of the rendering
            c.render_start = time.time()

            c.requested_url = request.environ.get('PATH_INFO')
            if request.environ.get('QUERY_STRING'):
                c.requested_url += '?' + request.environ['QUERY_STRING']
            logger.info(c.requested_url)

            # Capture IP address in non-ssl mode, so we can use it in SSL mode see ticket #2275
            ip = auth.get_user_ip()
            if not session.get('IP_ADDRESS') and ip:
                session['IP_ADDRESS'] = ip
            elif not session.get('IP_ADDRESS') and request.environ.get(
                    'HTTP_RLNCLIENTIPADDR'):
                session['IP_ADDRESS'] = request.environ.get(
                    'HTTP_RLNCLIENTIPADDR')
            elif not session.get('IP_ADDRESS') and request.environ.get(
                    'REMOTE_ADDR'):
                session['IP_ADDRESS'] = request.environ.get('REMOTE_ADDR')

            # Save the first referer we see to store in user record when/if we create one.
            if not session.get('referer'):
                session['referer'] = environ.get('HTTP_REFERER',
                                                 '').decode('utf-8', 'ignore')
                session.save()

            if session.get('notify'):
                c._notify = session['notify']
                del session['notify']
                session.save()

            return WSGIController.__call__(self, environ, start_response)
        finally:
            if 'paste.testing_variables' not in request.environ:
                Session.remove()
示例#34
0
 def __call__(self, environ, start_response):
     """Invoke the WSGI controller."""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     try:
         return WSGIController.__call__(self, environ, start_response)
     finally:
         model.Session.remove()
示例#35
0
    def __call__(self, environ, start_response):

        # Update the user header information (Content found on the very top-right of the GUI)
        self.BaseController_UpdateUserHeader()
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        return WSGIController.__call__(self, environ, start_response)
示例#36
0
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     try: 
         return WSGIController.__call__(self, environ, start_response)
     except NotImplementedError, e:
         abort(501)
示例#37
0
文件: base.py 项目: sinjax/drsin
	def __call__(self, environ, start_response):
		try:
			c.cats = model.Category.query.filter(model.and_(
				model.Category.category!="Default",
				model.Category.category!="Uncategorized"
			)).all()
			return WSGIController.__call__(self, environ, start_response)
		finally:
			model.Session.remove()
示例#38
0
    def __call__(self, environ, start_response):
        # Insert any code to be run per request here. The Routes match
        # is under environ['pylons.routes_dict'] should you want to check
        # the action or route vars here

        # Force Paste not to set the Content-Length to 0 before cgi.FieldStorage
        # can read the request body
        environ['CONTENT_LENGTH'] = '-1'
        return WSGIController.__call__(self, environ, start_response)
示例#39
0
文件: base.py 项目: dativebase/old
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     # environ['paste.content_type'] = 'application/json'
     try:
         return WSGIController.__call__(self, environ, start_response)
     finally:
         Session.remove()
示例#40
0
文件: base.py 项目: leveille/blog.v1
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     try:
         self._setup()
         return WSGIController.__call__(self, environ, start_response)
     finally:
         meta.Session.remove()
示例#41
0
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     try:
         return WSGIController.__call__(self, environ, start_response)
     finally:
         if not 'paste.testing_variables' in request.environ:
             model.Session.remove()
示例#42
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""

        # Set up the database object
        c.db = self.db = Database(config["couchdb_uri"])

        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        return WSGIController.__call__(self, environ, start_response)
示例#43
0
文件: base.py 项目: nint22/CoreCodex
	def __call__(self, environ, start_response):
	
		# Update the user header information (Content found on the very top-right of the GUI)
		self.BaseController_UpdateUserHeader()
		
		"""Invoke the Controller"""
		# WSGIController.__call__ dispatches to the Controller method
		# the request is routed to. This routing information is
		# available in environ['pylons.routes_dict']
		return WSGIController.__call__(self, environ, start_response)
示例#44
0
文件: base.py 项目: pks-os/LinOTP
    def __call__(self, environ, start_response):
        '''Invoke the Controller'''
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # we add a unique request id to the request enviroment
        # so we can trace individual requests in the logging

        environ['REQUEST_ID'] = str(uuid4())
        environ['REQUEST_START_TIMESTAMP'] = datetime.now()

        with request_context_safety():

            try:
                self._parse_request_params(request)
            except UnicodeDecodeError as exx:
                # we supress Exception here as it will be handled in the
                # controller which will return corresponding response
                log.warning('Failed to access request parameters: %r' % exx)

            self.create_context(request, environ)

            try:
                try:
                    user_desc = getUserFromRequest(request)
                    self.base_auth_user = user_desc.get('login', '')
                except UnicodeDecodeError as exx:
                    # we supress Exception here as it will be handled in the
                    # controller which will return corresponding response
                    log.warning('Failed to identify user due to %r' % exx)

                ret = WSGIController.__call__(self, environ, start_response)
                log.debug("Request reply: %r", ret)

            finally:
                meta.Session.remove()
                # free the lock on the scurityPovider if any
                if self.sep:
                    self.sep.dropSecurityModule()
                closeResolvers()

                # hint for the garbage collector to make the dishes
                data_objects = [
                    "resolvers_loaded", "resolver_clazzes", "linotpConfig",
                    "audit", "hsm"
                ]
                for data_obj in data_objects:
                    if hasattr(c, data_obj):
                        data = getattr(c, data_obj)
                        del data

                log_request_timedelta(log)

            return ret
示例#45
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # before setting anything new, first reset the old values from previous request if any
        contextutils.resetcontext(self)

        #LOG.debug(environ)
        if 'service' in environ['pylons.routes_dict']:
            servicename = environ['pylons.routes_dict']['service']
            #if not registered, agent will not try to replace

            if servicename is not None and servicename.count('.') == 2:
                servicename = manifestutil.expandServiceName(servicename)
                LOG.info('service name expanded %s ' % servicename)
                environ['pylons.routes_dict']['service'] = servicename

            contextutils.injectcontext(self, {'service': servicename})

        # get correlationid into context
        if 'X-CORRELATIONID' in request.headers and request.headers[
                'X-CORRELATIONID'] is not None:
            contextutils.injectcontext(
                self, {'guid': request.headers['X-CORRELATIONID']})
        else:
            contextutils.injectcontext(self, {'guid': ''})

        # get timeouts and inject into context
        if 'X-THREAD_TIMEOUT' in request.headers and request.headers[
                'X-THREAD_TIMEOUT'] is not None:
            contextutils.injectcontext(
                self,
                {'thread_timeout': request.headers['X-AGENT_THREAD_TIMEOUT']})

        # get progress timeouts and inject into context
        if 'X-THREAD_PROGRESS_TIMEOUT' in request.headers and request.headers[
                'X-THREAD_PROGRESS_TIMEOUT'] is not None:
            contextutils.injectcontext(
                self, {
                    'thread_progress_timeout':
                    request.headers['X-THREAD_PROGRESS_TIMEOUT']
                })

        # get remote address from request
        remoteAddr = request.environ.get("X_FORWARDED_FOR",
                                         request.environ.get("REMOTE_ADDR"))
        contextutils.injectcontext(self, {'remote_addr': remoteAddr})

        reqChecksum = '%s,%s,%s' % (request.method, request.url, request.body)
        contextutils.injectcontext(self, {'reqChecksum': reqChecksum})

        return WSGIController.__call__(self, environ, start_response)
示例#46
0
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     user = session.get('user')
     if user:
         request.environ['REMOTE_USER'] = user.email
     try:
         return WSGIController.__call__(self, environ, start_response)
     finally:
         Session.remove()
示例#47
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # Insert any code to be run per request here.
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            model.clean_local()
            kcd_model.clean_local()
示例#48
0
文件: base.py 项目: polkrai/srjvkk
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     try:
         config['pylons.g'].loginurl = 'http://' + environ[
             'HTTP_HOST'] + config['jvkk.login.url']
         return WSGIController.__call__(self, environ, start_response)
     finally:
         model.Session.close()
         model.Session.remove()
示例#49
0
文件: base.py 项目: wigg234/reddit
    def __call__(self, environ, start_response):
        true_client_ip = environ.get('HTTP_TRUE_CLIENT_IP')
        ip_hash = environ.get('HTTP_TRUE_CLIENT_IP_HASH')
        forwarded_for = environ.get('HTTP_X_FORWARDED_FOR', ())
        remote_addr = environ.get('REMOTE_ADDR')

        if (g.ip_hash
            and true_client_ip
            and ip_hash
            and hashlib.md5(true_client_ip + g.ip_hash).hexdigest() \
            == ip_hash.lower()):
            request.ip = true_client_ip
        elif g.trust_local_proxies and forwarded_for and is_local_address(
                remote_addr):
            request.ip = forwarded_for.split(',')[-1]
        else:
            request.ip = environ['REMOTE_ADDR']

        #if x-dont-decode is set, pylons won't unicode all the paramters
        if environ.get('HTTP_X_DONT_DECODE'):
            request.charset = None

        request.get = storify(request.GET)
        request.post = storify(request.POST)
        request.referer = environ.get('HTTP_REFERER')
        request.user_agent = environ.get('HTTP_USER_AGENT')
        request.fullpath = environ.get('FULLPATH', request.path)
        request.fullurl = environ.get('FULLURL', request.url)
        request.port = environ.get('request_port')

        if_modified_since = environ.get('HTTP_IF_MODIFIED_SINCE')
        if if_modified_since:
            request.if_modified_since = read_http_date(if_modified_since)
        else:
            request.if_modified_since = None

        #set the function to be called
        action = request.environ['pylons.routes_dict'].get('action')
        if action:
            meth = request.method.upper()
            if meth == 'HEAD':
                meth = 'GET'

            if meth != 'OPTIONS':
                handler_name = meth + '_' + action
            else:
                handler_name = meth

            request.environ['pylons.routes_dict']['action_name'] = action
            request.environ['pylons.routes_dict']['action'] = handler_name

        return WSGIController.__call__(self, environ, start_response)
示例#50
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            model.Session.remove()

            # For whatever reason, query log isn't reliably gc'd, so nuke
            # it manually here
            c.query_log = None
示例#51
0
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     begin = time()
     try:
         return WSGIController.__call__(self, environ, start_response)
     finally:
         db.session.remove()
         db.session.close()
         log.debug("Request to %s took %sms" %
                   (request.path, int((time() - begin) * 1000)))
示例#52
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        c.lang = environ['pylons.routes_dict'].get('_lang')
        if c.lang:
            set_lang(c.lang)

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
示例#53
0
 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     try:
         response = WSGIController.__call__(self, environ, start_response)
         if isinstance(response, types.GeneratorType):
             response = DestroySessionWhenDone(response)
         else:
             Session.remove()
         return response
     except:
         Session.remove()
         raise
示例#54
0
    def __call__(self, environ, start_response):
        action = request.environ['pylons.routes_dict'].get('action')
        if action:
            method = request.method.upper()
            if method == 'HEAD':
                method = 'GET'

            handler_name = method + '_' + action

            #request.environ['pylons.routes_dict']['action_name'] = action
            request.environ['pylons.routes_dict']['action'] = handler_name

        self.environ = environ
        ret = WSGIController.__call__(self, environ, start_response)
        return ret
示例#55
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        from rhodecode.lib import helpers as h

        # Provide the Pylons context to Pyramid's debugtoolbar if it asks
        if environ.get('debugtoolbar.wants_pylons_context', False):
            environ['debugtoolbar.pylons_context'] = c._current_obj()

        _route_name = '.'.join([environ['pylons.routes_dict']['controller'],
                                environ['pylons.routes_dict']['action']])

        self.rc_config = SettingsModel().get_all_settings(cache=True)
        self.ip_addr = get_ip_addr(environ)

        # The rhodecode auth user is looked up and passed through the
        # environ by the pylons compatibility tween in pyramid.
        # So we can just grab it from there.
        auth_user = environ['rc_auth_user']

        # set globals for auth user
        request.user = auth_user
        c.rhodecode_user = self._rhodecode_user = auth_user

        log.info('IP: %s User: %s accessed %s [%s]' % (
            self.ip_addr, auth_user, safe_unicode(get_access_path(environ)),
            _route_name)
        )

        # TODO: Maybe this should be move to pyramid to cover all views.
        # check user attributes for password change flag
        user_obj = auth_user.get_instance()
        if user_obj and user_obj.user_data.get('force_password_change'):
            h.flash('You are required to change your password', 'warning',
                    ignore_duplicate=True)

            skip_user_check_urls = [
                'error.document', 'login.logout', 'login.index',
                'admin/my_account.my_account_password',
                'admin/my_account.my_account_password_update'
            ]
            if _route_name not in skip_user_check_urls:
                return self._dispatch_redirect(
                    url('my_account_password'), environ, start_response)

        return WSGIController.__call__(self, environ, start_response)
示例#56
0
文件: base.py 项目: rb12345/LinOTP
    def __call__(self, environ, start_response):
        '''Invoke the Controller'''
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        path = ""

        with request_context_safety():

            self.create_context(request)

            try:
                if environ:
                    path = environ.get("PATH_INFO", "") or ""

                try:
                    user_desc = getUserFromRequest(request)
                    self.base_auth_user = user_desc.get('login', '')
                except UnicodeDecodeError as exx:
                    # we supress Exception here as it will be handled in the
                    # controller which will return corresponding response
                    log.info('Failed to identify user due to %r' % exx)

                log.debug("request %r" % path)
                ret = WSGIController.__call__(self, environ, start_response)
                log.debug("reply %r" % ret)

            finally:
                meta.Session.remove()
                # free the lock on the scurityPovider if any
                if self.sep:
                    self.sep.dropSecurityModule()
                closeResolvers()

                # hint for the garbage collector to make the dishes
                data_objects = [
                    "resolvers_loaded", "resolver_types", "resolver_clazzes",
                    "linotpConfig", "audit", "hsm"
                ]
                for data_obj in data_objects:
                    if hasattr(c, data_obj):
                        data = getattr(c, data_obj)
                        del data

                log.debug("request %r done!" % path)

            return ret
示例#57
0
文件: base.py 项目: SpComb/myottd
    def __call__(self, environ, start_response):
        # Insert any code to be run per request here. The Routes match
        # is under environ['pylons.routes_dict'] should you want to check
        # the action or route vars here

        try:
            return WSGIController.__call__(self, environ, start_response)
        except Exception, e:
            if isinstance(e, _httpexceptions.HTTPFound):
                raise

            c.error_title = "Generic Internal Error :("
            c.error = "%s: %s" % (e.__class__.__name__, e)
            c.traceback = _traceback.format_exc()

            return render_response('error.myt')
示例#58
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # make available any detailed login information we want on all requests
        # if there's no user set, just setup a blank instance
        tpl.current_user = auth.get_user(User()) 

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            # auto commit at the end of a request
            Session.commit()
            Session.remove()