コード例 #1
0
 def _getHigherLevelUser(self, request, roles=None):
     if roles:
         accessed = self._getPAS()._getObjectContext(
             request["PUBLISHED"], request)[1]
     req_roles = request.roles
     auth = request._auth
     # save response and install new one to prevent side effects
     saved_response = request.response
     try:
         request.response = Response()
         for uf in self._generateHigherLevelUserFolders():
             if req_roles is UNSPECIFIED_ROLES:
                 u = uf.validate(request, auth)
             else:
                 u = uf.validate(request, auth, req_roles)
             if u is None or u is nobody:
                 continue
             # this user folder has authenticated a user able to perform
             # the request
             if roles:
                 # check in addition that is has one of *roles*
                 if not u.allowed(accessed, roles):
                     # reject this user
                     continue
             return u
     finally:
         request.response = saved_response
コード例 #2
0
    def publish(self,
                path,
                basic=None,
                env=None,
                extra=None,
                request_method='GET',
                stdin=None,
                handle_errors=True):
        '''Publishes the object at 'path' returning a response object.'''

        from StringIO import StringIO
        from ZPublisher.HTTPRequest import HTTPRequest as Request
        from ZPublisher.HTTPResponse import HTTPResponse as Response
        from ZServer.ZPublisher.Publish import publish_module

        # Commit the sandbox for good measure
        transaction.commit()

        if env is None:
            env = {}
        if extra is None:
            extra = {}

        request = self.app.REQUEST

        env['SERVER_NAME'] = request['SERVER_NAME']
        env['SERVER_PORT'] = request['SERVER_PORT']
        env['REQUEST_METHOD'] = request_method

        p = path.split('?')
        if len(p) == 1:
            env['PATH_INFO'] = p[0]
        elif len(p) == 2:
            [env['PATH_INFO'], env['QUERY_STRING']] = p
        else:
            raise TypeError('')

        if basic:
            env['HTTP_AUTHORIZATION'] = "Basic %s" % base64.encodestring(basic)

        if stdin is None:
            stdin = StringIO()

        outstream = StringIO()
        response = Response(stdout=outstream, stderr=sys.stderr)
        request = Request(stdin, env, response)
        for k, v in extra.items():
            request[k] = v

        publish_module('Zope2',
                       debug=not handle_errors,
                       request=request,
                       response=response)

        return ResponseWrapper(response, outstream, path)
コード例 #3
0
def publish_module_standard(module_name,
                            stdin=sys.stdin,
                            stdout=sys.stdout,
                            stderr=sys.stderr,
                            environ=os.environ,
                            debug=0,
                            request=None,
                            response=None):
    must_die = 0
    status = 200
    after_list = [None]
    try:
        try:
            if response is None:
                response = Response(stdout=stdout, stderr=stderr)
            else:
                stdout = response.stdout

            # debug is just used by tests (has nothing to do with debug_mode!)
            response.handle_errors = not debug

            if request is None:
                request = Request(stdin, environ, response)

            setRequest(request)

            # make sure that the request we hand over has the
            # default layer/skin set on it; subsequent code that
            # wants to look up views will likely depend on it
            if ISkinnable.providedBy(request):
                setDefaultSkin(request)

            response = publish(request, module_name, after_list, debug=debug)
        except (SystemExit, ImportError):
            # XXX: Rendered ImportErrors were never caught here because they
            # were re-raised as string exceptions. Maybe we should handle
            # ImportErrors like all other exceptions. Currently they are not
            # re-raised at all, so they don't show up here.
            must_die = sys.exc_info()
            request.response.exception(1)
        except:
            # debug is just used by tests (has nothing to do with debug_mode!)
            if debug:
                raise
            request.response.exception()
            status = response.getStatus()

        if response:
            outputBody = getattr(response, 'outputBody', None)
            if outputBody is not None:
                outputBody()
            else:
                response = str(response)
                if response:
                    stdout.write(response)

        # The module defined a post-access function, call it
        if after_list[0] is not None:
            after_list[0]()

    finally:
        if request is not None:
            request.close()
            clearRequest()

    if must_die:
        # Try to turn exception value into an exit code.
        try:
            if hasattr(must_die[1], 'code'):
                code = must_die[1].code
            else:
                code = int(must_die[1])
        except:
            code = must_die[1] and 1 or 0
        if hasattr(request.response, '_requestShutdown'):
            request.response._requestShutdown(code)

        try:
            reraise(must_die[0], must_die[1], must_die[2])
        finally:
            must_die = None

    return status
コード例 #4
0
def http(request_string, handle_errors=True):
    """Execute an HTTP request string via the publisher

    This is used for HTTP doc tests.
    """
    import six.moves.urllib.request, six.moves.urllib.parse, six.moves.urllib.error
    import rfc822
    from cStringIO import StringIO
    from ZPublisher.HTTPResponse import HTTPResponse as Response
    from ZServer.ZPublisher.Publish import publish_module

    # Commit work done by previous python code.
    transaction.commit()

    # Discard leading white space to make call layout simpler
    request_string = request_string.lstrip()

    # Split off and parse the command line
    l = request_string.find('\n')
    command_line = request_string[:l].rstrip()
    request_string = request_string[l + 1:]
    method, path, protocol = command_line.split()
    path = six.moves.urllib.parse.unquote(path)

    instream = StringIO(request_string)

    env = {
        "HTTP_HOST": 'localhost',
        "HTTP_REFERER": 'localhost',
        "REQUEST_METHOD": method,
        "SERVER_PROTOCOL": protocol,
    }

    p = path.split('?', 1)
    if len(p) == 1:
        env['PATH_INFO'] = p[0]
    elif len(p) == 2:
        [env['PATH_INFO'], env['QUERY_STRING']] = p
    else:
        raise TypeError('')

    header_output = HTTPHeaderOutput(
        protocol,
        ('x-content-type-warning', 'x-powered-by', 'bobo-exception-type',
         'bobo-exception-file', 'bobo-exception-value', 'bobo-exception-line'))

    headers = [
        split_header(header) for header in rfc822.Message(instream).headers
    ]

    # Store request body without headers
    instream = StringIO(instream.read())

    for name, value in headers:
        name = ('_'.join(name.upper().split('-')))
        if name not in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
            name = 'HTTP_' + name
        env[name] = value.rstrip()

    if 'HTTP_AUTHORIZATION' in env:
        env['HTTP_AUTHORIZATION'] = auth_header(env['HTTP_AUTHORIZATION'])

    outstream = StringIO()
    response = Response(stdout=outstream, stderr=sys.stderr)

    publish_module('Zope2',
                   response=response,
                   stdin=instream,
                   environ=env,
                   debug=not handle_errors)

    header_output.setResponseStatus(response.getStatus(), response.errmsg)
    header_output.setResponseHeaders(response.headers)
    header_output.headersl.extend(response._cookie_list())
    header_output.appendResponseHeaders(response.accumulated_headers)

    sync()

    return DocResponseWrapper(response, outstream, path, header_output)