예제 #1
0
    def __call__(self, environ, start_response):
        # End of URL is now /diff/<rev_id>?context=<context_lines>
        # or /diff/<rev_id>/<rev_id>?context=<context_lines>
        # This allows users to choose how much context they want to see.
        # Old format was /diff/<rev_id>/<rev_id> or /diff/<rev_id>
        """Default method called from /diff URL."""
        z = time.time()

        args = []
        while True:
            arg = path_info_pop(environ)
            if arg is None:
                break
            args.append(arg)

        numlines = 3 # This is the default.

        opts = parse_querystring(environ)
        for opt in opts:
            if opt[0] == 'context':
                try:
                    numlines = int(opt[1])
                except ValueError:
                    pass

        revid_from = args[0]
        # Convert a revno to a revid if we get a revno.
        revid_from = self._history.fix_revid(revid_from)
        change = self._history.get_changes([revid_from])[0]

        if len(args) == 2:
            revid_to = self._history.fix_revid(args[1])
        elif len(change.parents) == 0:
            revid_to = NULL_REVISION
        else:
            revid_to = change.parents[0].revid

        repo = self._branch.branch.repository
        revtree1 = repo.revision_tree(revid_to)
        revtree2 = repo.revision_tree(revid_from)

        diff_content_stream = StringIO()
        show_diff_trees(revtree1, revtree2, diff_content_stream,
                        old_label='', new_label='', context=numlines)

        content = diff_content_stream.getvalue()

        self.log.info('/diff %r:%r in %r secs with %r context' % (revid_from, revid_to,
                                                  time.time() - z, numlines))

        revno1 = self._history.get_revno(revid_from)
        revno2 = self._history.get_revno(revid_to)
        filename = '%s_%s.diff' % (revno1, revno2)
        headers = [
            ('Content-Type', 'application/octet-stream'),
            ('Content-Length', str(len(content))),
            ('Content-Disposition', 'attachment; filename=%s' % (filename,)),
            ]
        start_response('200 OK', headers)
        return [content]
예제 #2
0
    def _parse_params(self, environ):
        # Try to find the parameters in various sources,
        # reflecting preference order:
        # Query string
        params = dict(parse_querystring(environ))
        # POST body
        request = Request(environ)
        if request.content_type == 'application/x-www-form-urlencoded':
            body = request.body
            params.update(parse_formvars(environ, include_get_vars=False))
            request.body = body
        # Authorization header
        auth_header = AUTHORIZATION(environ)
        if auth_header:
            try:
                params.update(oauth2.Request._split_header(auth_header))
            except:
                pass
        # Remove the non-oauth params
        if params:
            for key in params.keys():
                if not (key.startswith('oauth_') or key == 'realm'):
                    del params[key]

        return dict(params)
예제 #3
0
    def __call__(self, environ, start_response):
        session = environ[self.sessionKey]

        # Check for return to address in URI query args set by
        # AuthnRedirectInitiatorMiddleware in application code stack
        params = dict(parse_querystring(environ))

        # Store the return URI query argument in a beaker session
        quotedReferrer = params.get(self.return2uri_argname, '')
        referrerURI = urllib.unquote(quotedReferrer)
        if referrerURI:
            session[self.return2uri_argname] = referrerURI
            session.save()

        # Check for a return URI setting in the beaker session and if the user
        # has just been authenticated by the AuthKit SSL Client authentication
        # middleware.  If so, redirect to this URL deleting the beaker session
        # URL setting
        return2URI = session.get(self.return2uri_argname)
        if self.sslAuthnSucceeded and return2URI:
            del session[self.return2uri_argname]
            session.save()
            return self.redirect(return2URI)

        return self._app(environ, start_response)
예제 #4
0
    def _parse_params(self, environ):
        # Try to find the parameters in various sources,
        # reflecting preference order:
        # Query string
        params = dict(parse_querystring(environ))
        # POST body
        request = Request(environ)
        if request.content_type == 'application/x-www-form-urlencoded':
            body = request.body
            params.update(parse_formvars(environ, include_get_vars=False))
            request.body = body
        # Authorization header
        auth_header = AUTHORIZATION(environ)
        if auth_header:
            try:
                params.update(oauth2.Request._split_header(auth_header))
            except:
                pass
        # Remove the non-oauth params
        if params:
            for key in params.keys():
                if not (key.startswith('oauth_') or key == 'realm'):
                    del params[key]

        return dict(params)
예제 #5
0
    def __call__(self, environ, start_response):
        session = environ[self.sessionKey]

        # Check for return to address in URI query args set by
        # AuthnRedirectInitiatorMiddleware in application code stack
        params = dict(parse_querystring(environ))

        # Store the return URI query argument in a beaker session
        quotedReferrer = params.get(self.return2uri_argname, '')
        referrerURI = urllib.unquote(quotedReferrer)
        if referrerURI:
            session[self.return2uri_argname] = referrerURI
            session.save()

        # Check for a return URI setting in the beaker session and if the user
        # has just been authenticated by the AuthKit SSL Client authentication
        # middleware.  If so, redirect to this URL deleting the beaker session
        # URL setting
        return2URI = session.get(self.return2uri_argname)
        if self.sslAuthnSucceeded and return2URI:
            del session[self.return2uri_argname]
            session.save()
            return self.redirect(return2URI)

        return self._app(environ, start_response)
예제 #6
0
    def _logout(self, environ, start_response):
        """Logout of loggerhead.

        Clear the cookie and redirect to `next_to`.
        """
        environ[self.session_var].clear()
        query = dict(parse_querystring(environ))
        next_url = query.get('next_to')
        if next_url is None:
            next_url = allvhosts.configs['mainsite'].rooturl
        raise HTTPMovedPermanently(next_url)
예제 #7
0
파일: middleware.py 프로젝트: 10sr/hue
 def exception_handler(self, exc_info, environ):
     simple_html_error = False
     if self.xmlhttp_key:
         get_vars = request.parse_querystring(environ)
         if dict(get_vars).get(self.xmlhttp_key):
             simple_html_error = True
     return errormiddleware.handle_exception(
         exc_info, environ['wsgi.errors'],
         html=True,
         debug_mode=True,
         simple_html_error=simple_html_error)
예제 #8
0
    def _logout(self, environ, start_response):
        """Logout of loggerhead.

        Clear the cookie and redirect to `next_to`.
        """
        environ[self.session_var].clear()
        query = dict(parse_querystring(environ))
        next_url = query.get('next_to')
        if next_url is None:
            next_url = allvhosts.configs['mainsite'].rooturl
        raise HTTPMovedPermanently(next_url)
예제 #9
0
 def exception_handler(self, exc_info, environ):
     simple_html_error = False
     if self.xmlhttp_key:
         get_vars = request.parse_querystring(environ)
         if dict(get_vars).get(self.xmlhttp_key):
             simple_html_error = True
     return errormiddleware.handle_exception(
         exc_info,
         environ['wsgi.errors'],
         html=True,
         debug_mode=True,
         simple_html_error=simple_html_error)
예제 #10
0
    def parse_args(self, environ):
        kwargs = dict(parse_querystring(environ))
        util.set_context(kwargs)
        args = []
        while True:
            arg = path_info_pop(environ)
            if arg is None:
                break
            args.append(arg)

        path = None
        if len(args) > 1:
            path = unicode('/'.join(args[1:]), 'utf-8')
        self.args = args
        self.kwargs = kwargs
        return path
예제 #11
0
def application(environ, start_response):
	status = '200 OK'
	output = ''
	#get query
	query = re.sub("[^a-z]","",environ.get('PATH_INFO'))
	#get arguments
	arguments = dict(request.parse_querystring(environ))

	#add stock to database
	if query == 'add':
		#file that handles adding stock to database
		output = add.add_stock(arguments)
	
	response_headers = [('Content-Type', 'application/json')]
	start_response(status, response_headers)
	return [output]
예제 #12
0
    def index(self):
        if 'ndg.security.auth' in request.cookies.keys():
            return '<html><head></head><body onload="window.close()"></body></html>'
        else:
            #get login credentials
            inputs=dict(parse_querystring(request.environ))
            securedResource=inputs['endpoint']
            try:
                u=urllib2.urlopen(securedResource)
            except urllib2.HTTPError, e:
                if e.code == 401:
		    #replace the redirection part of the url with a link to a controller which closes the login window (rather than accessing the WXS resource
                    serverurl=config['app_conf']['serverurl'] 
                    loggedinurl='%s/loggedin'%serverurl
                    c.redirecturl = '%s=%s'%(e.url.split('=')[0],loggedinurl)
                    #i.e. c.redirecturl="https://ndg3beta.badc.rl.ac.uk/verify?ndg.security.r=http%253A%252F%252Flocalhost:5005%252Floggedin"
                    return render('redirecting.html')
예제 #13
0
    def _parse_params(self, environ):
        # Try to find the parameters in various sources:
        # POST body
        params = parse_formvars(environ, include_get_vars=False)
        # Query string
        params.update(parse_querystring(environ))
        # Authorization header
        auth_header = AUTHORIZATION(environ)
        if auth_header:
            params.update(oauth2.Request._split_header(auth_header))

        # Remove the non-oauth params
        if params:
            for key in params.keys():
                if not (key.startswith('oauth_') or key == 'realm'):
                    del params[key]

        return dict(params)
예제 #14
0
 def from_environ(cls, environ, with_query_string=True,
                  with_path_info=True, script_name=None,
                  path_info=None, querystring=None):
     url = request.construct_url(
         environ, with_query_string=False,
         with_path_info=with_path_info, script_name=script_name,
         path_info=path_info)
     if with_query_string:
         if querystring is None:
             vars = request.parse_querystring(environ)
         else:
             vars = parse_qsl(
                 querystring,
                 keep_blank_values=True,
                 strict_parsing=False)
     else:
         vars = None
     v = cls(url, vars=vars)
     return v
예제 #15
0
    def _complete_login(self, environ, start_response):
        """Complete the OpenID authentication process.

        Here we handle the result of the OpenID process.  If the process
        succeeded, we record the username in the session and redirect the user
        to the page they were trying to view that triggered the login attempt.
        In the various failures cases we return a 401 Unauthorized response
        with a brief explanation of what went wrong.
        """
        query = dict(parse_querystring(environ))
        # Passing query['openid.return_to'] here is massive cheating, but
        # given we control the endpoint who cares.
        response = self._make_consumer(environ).complete(
            query, query['openid.return_to'])
        if response.status == SUCCESS:
            self.log.error('open id response: SUCCESS')
            sreg_info = SRegResponse.fromSuccessResponse(response)
            if not sreg_info:
                self.log.error('sreg_info is None.')
                exc = HTTPUnauthorized()
                exc.explanation = (
                    "You don't have a Launchpad account. Check that you're "
                    "logged in as the right user, or log into Launchpad and try "
                    "again.")
                raise exc
            environ[self.session_var]['identity_url'] = response.identity_url
            environ[self.session_var]['user'] = sreg_info['nickname']
            raise HTTPMovedPermanently(query['back_to'])
        elif response.status == FAILURE:
            self.log.error('open id response: FAILURE: %s', response.message)
            exc = HTTPUnauthorized()
            exc.explanation = response.message
            raise exc
        elif response.status == CANCEL:
            self.log.error('open id response: CANCEL')
            exc = HTTPUnauthorized()
            exc.explanation = "Authentication cancelled."
            raise exc
        else:
            self.log.error('open id response: UNKNOWN')
            exc = HTTPUnauthorized()
            exc.explanation = "Unknown OpenID response."
            raise exc
예제 #16
0
파일: url.py 프로젝트: 10sr/hue
 def from_environ(cls, environ, with_query_string=True,
                  with_path_info=True, script_name=None,
                  path_info=None, querystring=None):
     url = request.construct_url(
         environ, with_query_string=False,
         with_path_info=with_path_info, script_name=script_name,
         path_info=path_info)
     if with_query_string:
         if querystring is None:
             vars = request.parse_querystring(environ)
         else:
             vars = cgi.parse_qsl(
                 querystring,
                 keep_blank_values=True,
                 strict_parsing=False)
     else:
         vars = None
     v = cls(url, vars=vars)
     return v
예제 #17
0
 def __call__(self, environ, start_response):
     path_info = environ.get('PATH_INFO')
     
     if path_info.startswith(self.mountpoint):
         # we need to act on the request
         url = path_info.replace(self.mountpoint, '')
         url = urllib.unquote(url)
         if not url.startswith(self.protocol):
             url = self.protocol + url
         qs = parse_querystring(environ)
         f = urllib.urlopen(url + '?' + urllib.urlencode(qs))
         body = f.read()
         f.close()
         start_response('200 OK', [('content-type', self.content_type),
                                   ('content-length', str(len(body)))])
         return [body]
         
     else:
         return self.app(environ, start_response)
예제 #18
0
    def _complete_login(self, environ, start_response):
        """Complete the OpenID authentication process.

        Here we handle the result of the OpenID process.  If the process
        succeeded, we record the username in the session and redirect the user
        to the page they were trying to view that triggered the login attempt.
        In the various failures cases we return a 401 Unauthorized response
        with a brief explanation of what went wrong.
        """
        query = dict(parse_querystring(environ))
        # Passing query['openid.return_to'] here is massive cheating, but
        # given we control the endpoint who cares.
        response = self._make_consumer(environ).complete(
            query, query['openid.return_to'])
        if response.status == SUCCESS:
            self.log.error('open id response: SUCCESS')
            sreg_info = SRegResponse.fromSuccessResponse(response)
            if not sreg_info:
                self.log.error('sreg_info is None.')
                exc = HTTPUnauthorized()
                exc.explanation = (
                  "You don't have a Launchpad account. Check that you're "
                  "logged in as the right user, or log into Launchpad and try "
                  "again.")
                raise exc
            environ[self.session_var]['user'] = sreg_info['nickname']
            raise HTTPMovedPermanently(query['back_to'])
        elif response.status == FAILURE:
            self.log.error('open id response: FAILURE: %s', response.message)
            exc = HTTPUnauthorized()
            exc.explanation = response.message
            raise exc
        elif response.status == CANCEL:
            self.log.error('open id response: CANCEL')
            exc = HTTPUnauthorized()
            exc.explanation = "Authentication cancelled."
            raise exc
        else:
            self.log.error('open id response: UNKNOWN')
            exc = HTTPUnauthorized()
            exc.explanation = "Unknown OpenID response."
            raise exc
예제 #19
0
파일: errormiddleware.py 프로젝트: 10sr/hue
 def exception_handler(self, exc_info, environ):
     simple_html_error = False
     if self.xmlhttp_key:
         get_vars = request.parse_querystring(environ)
         if dict(get_vars).get(self.xmlhttp_key):
             simple_html_error = True
     return handle_exception(
         exc_info, environ['wsgi.errors'],
         html=True,
         debug_mode=self.debug_mode,
         error_email=self.error_email,
         error_log=self.error_log,
         show_exceptions_in_wsgi_errors=self.show_exceptions_in_wsgi_errors,
         error_email_from=self.from_address,
         smtp_server=self.smtp_server,
         smtp_username=self.smtp_username,
         smtp_password=self.smtp_password,
         smtp_use_tls=self.smtp_use_tls,
         error_subject_prefix=self.error_subject_prefix,
         error_message=self.error_message,
         simple_html_error=simple_html_error)
예제 #20
0
 def exception_handler(self, exc_info, environ):
     simple_html_error = False
     if self.xmlhttp_key:
         get_vars = request.parse_querystring(environ)
         if dict(get_vars).get(self.xmlhttp_key):
             simple_html_error = True
     return handle_exception(
         exc_info,
         environ['wsgi.errors'],
         html=True,
         debug_mode=self.debug_mode,
         error_email=self.error_email,
         error_log=self.error_log,
         show_exceptions_in_wsgi_errors=self.show_exceptions_in_wsgi_errors,
         error_email_from=self.from_address,
         smtp_server=self.smtp_server,
         smtp_username=self.smtp_username,
         smtp_password=self.smtp_password,
         smtp_use_tls=self.smtp_use_tls,
         error_subject_prefix=self.error_subject_prefix,
         error_message=self.error_message,
         simple_html_error=simple_html_error)
예제 #21
0
    def __call__(self, environ, start_response):
        path_info = environ.get('PATH_INFO')

        if path_info == self.path:
            # we're being asked to render a view
            querydata = dict(parse_querystring(environ))
            if 'entry' in querydata:
                body = self.entry(querydata['entry'])
            else:
                url = construct_url(environ, with_query_string=False)
                body = self.index(url)
            start_response('200 OK', [('content-type', 'text/html'),
                                      ('content-length', str(len(body)))])
            return [body]
        else:
            # we need to try to catch an error
            identifier = self.new_identifier()
            # we place the error log path and identifier in the
            # environment so the application or other middleware can
            # form a URL to the exception
            environ['repoze.errorlog.path'] = self.path
            environ['repoze.errorlog.entryid'] = identifier
            try:
                return self.application(environ, start_response)
            except self.ignored_exceptions:
                # just reraise an ignored exception
                raise
            except:
                self.insert_error(identifier, sys.exc_info(), environ)
                if self.channel is None:
                    errors = environ.get('wsgi.errors')
                    if errors:
                        traceback.print_exc(None, errors)
                else:
                    logger = getLogger(self.channel)
                    logger.exception('\n')
                raise
예제 #22
0
    def __call__(self, environ, start_response):
        '''
        - Alter start_response to override the status code and force to 401.
        This will enable non-browser based client code to bypass the OpenID 
        interface
        - Manage AuthKit verify and process actions setting the referrer URI
        to manage redirects correctly
        
        @type environ: dict
        @param environ: WSGI environment variables dictionary
        @type start_response: function
        @param start_response: standard WSGI start response function
        @rtype: iterable
        @return: response
        '''
        # Skip Relying Party interface set-up if user has been authenticated
        # by other middleware
        if 'REMOTE_USER' in environ:
            log.debug("Found REMOTE_USER=%s in environ, AuthKit "
                      "based authentication has taken place in other "
                      "middleware, skipping OpenID Relying Party interface" %
                      environ['REMOTE_USER'])
            return self._app(environ, start_response)

        session = environ.get(self.sessionKey)
        if session is None:
            raise OpenIDRelyingPartyConfigError('No beaker session key "%s" '
                                                'found in environ' %
                                                self.sessionKey)

        # Check for return to address in URI query args set by
        # AuthnRedirectMiddleware in application code stack
        params = dict(parse_querystring(environ))
        quotedReferrer = params.get(AuthnRedirectMiddleware.RETURN2URI_ARGNAME,
                                    '')

        referrer = urllib.unquote(quotedReferrer)
        referrerPathInfo = urlsplit(referrer)[2]

        if (referrer and not referrerPathInfo.endswith(self._authKitVerifyPath)
                and not referrerPathInfo.endswith(self._authKitProcessPath)):

            # An app has redirected to the Relying Party interface setting the
            # special ndg.security.r query argument.  Subvert
            # authkit.authenticate.open_id.AuthOpenIDHandler.process
            # reassigning it's session 'referer' key to the URI specified in
            # ndg.security.r in the request URI
            session['referer'] = referrer
            session.save()

        if self._return2URIKey in environ.get('HTTP_REFERER', ''):
            # Remove return to arg to avoid interfering with AuthKit OpenID
            # processing
            splitURI = urlsplit(environ['HTTP_REFERER'])
            query = splitURI[3]

            filteredQuery = '&'.join([
                arg for arg in query.split('&')
                if not arg.startswith(self._return2URIKey)
            ])

            environ['HTTP_REFERER'] = urlunsplit(splitURI[:3] + \
                                                 (filteredQuery,) + \
                                                 splitURI[4:])

        # See _start_response doc for an explanation...
        if environ['PATH_INFO'] == self._authKitVerifyPath:

            def _start_response(status, header, exc_info=None):
                '''Make OpenID Relying Party OpenID prompt page return a 401
                status to signal to non-browser based clients that 
                authentication is required.  Requests are filtered on content 
                type so that static content such as graphics and style sheets 
                associated with the page are let through unaltered
                
                @type status: str
                @param status: HTTP status code and status message
                @type header: list
                @param header: list of field, value tuple HTTP header content
                @type exc_info: Exception
                @param exc_info: exception info
                '''
                _status = status

                # Ignore redirect requests - this is set following a form POST
                # of the OpenID URL to initiate sign-in
                if not _status.startswith('30'):
                    for name, val in header:
                        if (name.lower() == 'content-type'
                                and val.startswith('text/html')):
                            _status = self.getStatusMessage(401)
                            break

                return start_response(_status, header, exc_info)
        else:
            _start_response = start_response

        return self._app(environ, _start_response)
예제 #23
0
파일: middleware.py 프로젝트: 10sr/hue
    def respond(self, environ, start_response):
        if environ.get('paste.throw_errors'):
            return self.application(environ, start_response)
        base_path = request.construct_url(environ, with_path_info=False,
                                          with_query_string=False)
        environ['paste.throw_errors'] = True
        started = []
        def detect_start_response(status, headers, exc_info=None):
            try:
                return start_response(status, headers, exc_info)
            except:
                raise
            else:
                started.append(True)
        try:
            __traceback_supplement__ = errormiddleware.Supplement, self, environ
            app_iter = self.application(environ, detect_start_response)
            try:
                return_iter = list(app_iter)
                return return_iter
            finally:
                if hasattr(app_iter, 'close'):
                    app_iter.close()
        except:
            exc_info = sys.exc_info()
            for expected in environ.get('paste.expected_exceptions', []):
                if isinstance(exc_info[1], expected):
                    raise

            # Tell the Registry to save its StackedObjectProxies current state
            # for later restoration
            registry.restorer.save_registry_state(environ)

            count = get_debug_count(environ)
            view_uri = self.make_view_url(environ, base_path, count)
            if not started:
                headers = [('content-type', 'text/html')]
                headers.append(('X-Debug-URL', view_uri))
                start_response('500 Internal Server Error',
                               headers,
                               exc_info)
            msg = 'Debug at: %s\n' % view_uri
            if six.PY3:
                msg = msg.encode('utf8')
            environ['wsgi.errors'].write(msg)

            exc_data = collector.collect_exception(*exc_info)
            debug_info = DebugInfo(count, exc_info, exc_data, base_path,
                                   environ, view_uri)
            assert count not in self.debug_infos
            self.debug_infos[count] = debug_info

            if self.xmlhttp_key:
                get_vars = request.parse_querystring(environ)
                if dict(get_vars).get(self.xmlhttp_key):
                    exc_data = collector.collect_exception(*exc_info)
                    html = formatter.format_html(
                        exc_data, include_hidden_frames=False,
                        include_reusable=False, show_extra_data=False)
                    return [html]

            # @@: it would be nice to deal with bad content types here
            return debug_info.content()
예제 #24
0
    def respond(self, environ, start_response):
        if environ.get('paste.throw_errors'):
            return self.application(environ, start_response)
        base_path = request.construct_url(environ,
                                          with_path_info=False,
                                          with_query_string=False)
        environ['paste.throw_errors'] = True
        started = []

        def detect_start_response(status, headers, exc_info=None):
            try:
                return start_response(status, headers, exc_info)
            except:
                raise
            else:
                started.append(True)

        try:
            __traceback_supplement__ = errormiddleware.Supplement, self, environ
            app_iter = self.application(environ, detect_start_response)
            try:
                return_iter = list(app_iter)
                return return_iter
            finally:
                if hasattr(app_iter, 'close'):
                    app_iter.close()
        except:
            exc_info = sys.exc_info()
            for expected in environ.get('paste.expected_exceptions', []):
                if isinstance(exc_info[1], expected):
                    raise

            # Tell the Registry to save its StackedObjectProxies current state
            # for later restoration
            registry.restorer.save_registry_state(environ)

            count = get_debug_count(environ)
            view_uri = self.make_view_url(environ, base_path, count)
            if not started:
                headers = [('content-type', 'text/html')]
                headers.append(('X-Debug-URL', view_uri))
                start_response('500 Internal Server Error', headers, exc_info)
            msg = 'Debug at: %s\n' % view_uri
            if six.PY3:
                msg = msg.encode('utf8')
            environ['wsgi.errors'].write(msg)

            exc_data = collector.collect_exception(*exc_info)
            debug_info = DebugInfo(count, exc_info, exc_data, base_path,
                                   environ, view_uri)
            assert count not in self.debug_infos
            self.debug_infos[count] = debug_info

            if self.xmlhttp_key:
                get_vars = request.parse_querystring(environ)
                if dict(get_vars).get(self.xmlhttp_key):
                    exc_data = collector.collect_exception(*exc_info)
                    html = formatter.format_html(exc_data,
                                                 include_hidden_frames=False,
                                                 include_reusable=False,
                                                 show_extra_data=False)
                    return [html]

            # @@: it would be nice to deal with bad content types here
            return debug_info.content()
예제 #25
0
파일: wmsviz.py 프로젝트: NERC-CEH/ecomaps
    def index(self):
        """
        Default controller method to handle the initial requests to the page
        """
        log.debug('entered wmsviz controller index action')

        return HTTPNotFound
        
        g.helpIcon='layout/icons/help.png'  #needs to go in config
        
        self.inputs=dict(parse_querystring(request.environ))
        log.info(self.inputs)
        c.wmcURL = ""
        
        # check if all we're doing is removing a view item
        if 'removeItem' in self.inputs:
            return self.removeViewItem(self.inputs['removeItem'])
        
        
        # check if we're doing an AJAX callback to get some WMC data
        if 'REQUEST' in self.inputs:
                        
            if self.inputs['REQUEST'] == 'GetWebMapContext':
                wmc= GetWebMapContext(self)
                log.debug("finished wmsviz controller index action, req = GetWebMapContext")
                return wmc
           
            if self.inputs['REQUEST'] == 'GetWebMapCapabilities':
                wmcDoc = GetWebMapCapabilities(self.inputs['ENDPOINT'])
                
                response.headers['Content-Type'] = 'text/xml'
                log.debug("finished wmsviz controller index action, req = GetWebMapCapabilities")
                return wmcDoc
            
            elif self.inputs['REQUEST'] == 'GetLegend':
                resp = GetLegend(self)
                log.debug("finished wmsviz controller index action, req = GetLegend")
                return resp
            
            elif self.inputs['REQUEST'] == 'GetLegendUrl':
                resp = GetLegendUrl(self)
                log.debug("finished wmsviz controller index action, req = GetLegendUrl")
                return resp
            
            if self.inputs['REQUEST'] == 'GetDisplayOptions':
                
                jsonTxt = GetResponse(self.inputs['URL'])
                
                response.headers['Content-Type'] = 'application/json'
                log.debug("finished wmsviz controller index action, req = GetDisplayOptions")
                return jsonTxt
            
            if self.inputs['REQUEST'] == 'GetAxisConfig':
                
                respText = GetResponse(self.inputs['URL'])
                
                response.headers['Content-Type'] = 'text/xml'
                return respText

            if self.inputs['REQUEST'] == 'proxy':
                # Client is requesting to use server as a proxy. Only forward the request if the
                # request parameter value is for an acceptable request type.
                url = self.inputs['URL']
                requestType = getQueryParameter(url, 'request')
                if requestType.lower() == 'getfeatureinfo':
                    try:
                        info = GetFeatureInfo(url)
                    except Exception, exc:
                        log.info("REQUEST:proxy Error making request to %s: %s" % (self.inputs['URL'], exc.__str__()))
                        info = "<p>Information is not available for this layer or position.</p>"
                    log.debug("finished wmsviz controller index action, req = GetFeatureInfo")
                    return "<FeatureInfo>" + saxutils.escape(info) + "</FeatureInfo>"
                else:
                    log.info("Proxy forwarding refused for request of type %s to URL %s" % (requestType, url))
                    return None
예제 #26
0
    def __call__(self, environ, start_response):
        '''
        - Alter start_response to override the status code and force to 401.
        This will enable non-browser based client code to bypass the OpenID 
        interface
        - Manage AuthKit verify and process actions setting the referrer URI
        to manage redirects correctly
        
        @type environ: dict
        @param environ: WSGI environment variables dictionary
        @type start_response: function
        @param start_response: standard WSGI start response function
        @rtype: iterable
        @return: response
        '''
        # Skip Relying Party interface set-up if user has been authenticated
        # by other middleware
        if 'REMOTE_USER' in environ:
            log.debug("Found REMOTE_USER=%s in environ, AuthKit "
                      "based authentication has taken place in other "
                      "middleware, skipping OpenID Relying Party interface" %
                      environ['REMOTE_USER'])
            return self._app(environ, start_response)

        session = environ.get(self.sessionKey)
        if session is None:
            raise OpenIDRelyingPartyConfigError('No beaker session key "%s" '
                                                'found in environ' % 
                                                self.sessionKey)
        
        # Check for return to address in URI query args set by 
        # AuthnRedirectMiddleware in application code stack
        params = dict(parse_querystring(environ))
        quotedReferrer = params.get(AuthnRedirectMiddleware.RETURN2URI_ARGNAME,
                                    '')
        
        referrer = urllib.unquote(quotedReferrer)
        referrerPathInfo = urlsplit(referrer)[2]

        if (referrer and 
            not referrerPathInfo.endswith(self._authKitVerifyPath) and 
            not referrerPathInfo.endswith(self._authKitProcessPath)):
            
            # An app has redirected to the Relying Party interface setting the
            # special ndg.security.r query argument.  Subvert 
            # authkit.authenticate.open_id.AuthOpenIDHandler.process
            # reassigning it's session 'referer' key to the URI specified in
            # ndg.security.r in the request URI
            session['referer'] = referrer
            session.save()
            
        if self._return2URIKey in environ.get('HTTP_REFERER', ''):
            # Remove return to arg to avoid interfering with AuthKit OpenID
            # processing
            splitURI = urlsplit(environ['HTTP_REFERER'])
            query = splitURI[3]
            
            filteredQuery = '&'.join([arg for arg in query.split('&')
                                if not arg.startswith(self._return2URIKey)])
            
            environ['HTTP_REFERER'] = urlunsplit(splitURI[:3] + \
                                                 (filteredQuery,) + \
                                                 splitURI[4:])
                            
        # See _start_response doc for an explanation...
        if environ['PATH_INFO'] == self._authKitVerifyPath: 
            def _start_response(status, header, exc_info=None):
                '''Make OpenID Relying Party OpenID prompt page return a 401
                status to signal to non-browser based clients that 
                authentication is required.  Requests are filtered on content 
                type so that static content such as graphics and style sheets 
                associated with the page are let through unaltered
                
                @type status: str
                @param status: HTTP status code and status message
                @type header: list
                @param header: list of field, value tuple HTTP header content
                @type exc_info: Exception
                @param exc_info: exception info
                '''
                _status = status
                for name, val in header:
                    if (name.lower() == 'content-type' and 
                        val.startswith('text/html')):
                        _status = self.getStatusMessage(401)
                        break
                    
                return start_response(_status, header, exc_info)
        else:
            _start_response = start_response

        return self._app(environ, _start_response)
예제 #27
0
    def index(self):
        """
        Default controller method to handle the initial requests to the page
        """
        log.debug('wmsviz controller')
        
        g.helpIcon='layout/icons/help.png'  #needs to go in config
        

        self.inputs=dict(parse_querystring(request.environ))
        log.info(self.inputs)
        c.wmcURL = ""
        
        # check if all we're doing is removing a view item
        if 'removeItem' in self.inputs:
            return self.removeViewItem(self.inputs['removeItem'])
        
        # check if we're doing an AJAX callback to get some WMC data
        if 'REQUEST' in self.inputs:
                        
            if self.inputs['REQUEST'] == 'GetWebMapContext':
                wmc= GetWebMapContext(self)
                return wmc
            
            elif self.inputs['REQUEST'] == 'GetLegend':
                return GetLegend(self)

        
        #get server information from config file
        g.server=config['app_conf']['serverurl']
    
        
        #TODO: WORK OUT HOW TO COUPLE THIS TO BROWSE
        # otherwise, we can get here by two routes:
        # i) either by clicking on the WMC icon in the details view - if so, get passed endpoint and add to
        #    selected items;
        # ii) or from the selections tab - which will already have set up the correct selected items
            
        # if ENDPOINT specified, we've reached the page via the WMC icon
                
        if ('ENDPOINT' in self.inputs):
	    #clear out old endpoints NOTE. this means only one endpoint at a time can be viewed. May want to
        #rethink this to enable 'shopping cart' type selection. 
            self.removeAllViewItems()
            urlstring=str(self.inputs['ENDPOINT'])
            req = urllib2.Request(urlstring)
            req.add_header('Cookie', request.headers.get('Cookie', ''))
            try:
	            filehandle = urllib2.urlopen(req)
            except urllib2.HTTPError, e:
                if e.code == 401:
                    log.info ('401 unauthorized error in ecomaps')
                    return abort(401) #triggers ndg security framework
                elif e.code == 403:  #TODO: 403 response is UNTESTED.
                    # User is authenticated but doesn't have the required permissions
                    # or an error occurred in the authorization process
                    # Read response
                    response = e.read()
                    # Send response to user
                    self.start_response("%d %s" % (e.code, e.msg), e.headers.dict.items())
                    return response
            self.addViewItem(self.inputs['ENDPOINT'])
예제 #28
0
 def _do_logout(self, environ, start_response, session):
     """Execute logout action, 
      - clear the beaker session
      - set the referrer URI to redirect back to by setting a custom 
     start_response function which modifies the HTTP header setting the
     location field for a redirect
     
     @param environ: environment dictionary
     @type environ: dict like object
     @type start_response: function
     @param start_response: standard WSGI start response function
     @param session: beaker session
     @type session: beaker.session.SessionObject
     """
         
     # Clear user details from beaker session
     for keyName in self.__class__.SESSION_KEYNAMES:
         session.pop(keyName, None)
     session.save()
            
     if self.__class__.LOGOUT_RETURN2URI_ARGNAME in environ['QUERY_STRING']:
         params = dict(parse_querystring(environ))
     
         # Store the return URI query argument in a beaker session
         quotedReferrer = params.get(
                             self.__class__.LOGOUT_RETURN2URI_ARGNAME, '')
         referrer = urllib.unquote(quotedReferrer)
         
         log.debug('Set redirect URI following logout based on %r URI query '
                   'string = %r', 
                   self.__class__.LOGOUT_RETURN2URI_ARGNAME,
                   referrer)
     else:
         referrer = environ.get('HTTP_REFERER')
         if referrer is None:
             log.warning('No HTTP return to URI set for redirect following '
                         'logout, either via the return to query string %r '
                         'or the "HTTP_REFERER" environment variable: '
                         'redirecting based on the %r config file option = '
                         '%r', 
                         self.__class__.LOGOUT_RETURN2URI_ARGNAME,
                         self.__class__.DEFAULT_LOGOUT_RETURN2URI_PARAMNAME,
                         self.__defaultLogoutReturnToURI)
             
             referrer = self.__defaultLogoutReturnToURI
         else:
             log.debug('Set redirect URI following logout based on '
                       '"HTTP_REFERER" environment variable = %r',
                       referrer)
             
     def _start_response(status, header, exc_info=None):
         """Alter the header to send a redirect to the logout referrer 
         address"""
         
         # Filter out any existing location field setting
         filteredHeader = [(field, val) for field, val in header 
                           if field.lower() != 'location']  
         
         # Add redirect destination to new location field setting      
         filteredHeader.extend([('Location', referrer)])
         
         statusMsg = self.getStatusMessage(
                                 self.__class__.LOGOUT_REDIRECT_STATUS_CODE)
         
         return start_response(statusMsg, filteredHeader, exc_info)
             
     return _start_response