Ejemplo n.º 1
0
 def not_allowed(self,
                 request: web.Request = None,
                 response: dict = {},
                 headers: dict = {},
                 allowed: dict = {},
                 **kwargs) -> web.Response:
     if not request:
         request = self.request
     if not allowed:
         allow = self._allowed
     else:
         allow = allowed
     args = {
         "method": request.method,
         "text": json.dumps(response, cls=BaseEncoder),
         "reason": "Method not Allowed",
         "content_type": "application/json",
         "allowed_methods": allow,
         **kwargs,
     }
     if allowed:
         headers["Allow"] = ",".join(allow)
     else:
         headers["Allow"] = ",".join(allow)
     obj = HTTPMethodNotAllowed(**args)
     for header, value in headers.items():
         obj.headers[header] = value
     return obj
Ejemplo n.º 2
0
    async def dispatch(cls, request):
        view = cls(request)
        method = getattr(view, request.method.lower())
        if not method:
            return HTTPMethodNotAllowed()

        return await method()
Ejemplo n.º 3
0
    async def dispatch(self, request: Request):
        """

        :param request:
        :return:
        """
        method = self.methods.get(request.method.upper())
        if not method:
            raise HTTPMethodNotAllowed('', SUPPORTED_METHODS)

        wanted_args = list(inspect.signature(method).parameters.keys())
        available_args = request.match_info.copy()

        for aa in available_args:
            if aa not in wanted_args:
                raise Exception(
                    'REST endpoint method {0} should be able to process URL "{1}" parameter.'
                    .format(request.method.upper(), aa))

        available_args.update({'request': request})

        unsatisfied_args = set(wanted_args) - set(available_args.keys())
        if unsatisfied_args:
            # Expected match info that doesn't exist
            raise HttpBadRequest('')

        return await method(
            **{arg_name: available_args[arg_name]
               for arg_name in wanted_args})
Ejemplo n.º 4
0
 def __call__(self, request):
     method = request.method.lower()
     if method not in self.http_methods:
         raise HTTPMethodNotAllowed(method=request.method,
                                    allowed_methods=[
                                        m for m in self.http_methods
                                        if getattr(self, m, None)
                                    ])
     try:
         handler = getattr(self, method)
     except AttributeError:
         raise HTTPMethodNotAllowed(method=request.method,
                                    allowed_methods=[
                                        m for m in self.http_methods
                                        if getattr(self, m, None)
                                    ])
     return (yield from handler(request))
Ejemplo n.º 5
0
    async def preflight(self):
        """We need to check if there is cors enabled and is valid."""
        headers = {}

        renderer = app_settings['cors_renderer'](self.request)
        settings = await renderer.get_settings()

        if not settings:
            return {}

        origin = self.request.headers.get('Origin', None)
        if not origin:
            raise HTTPNotFound(text='Origin this header is mandatory')

        requested_method = self.getRequestMethod()
        if not requested_method:
            raise HTTPNotFound(
                text='Access-Control-Request-Method this header is mandatory')

        requested_headers = (self.request.headers.get(
            'Access-Control-Request-Headers', ()))

        if requested_headers:
            requested_headers = map(str.strip, requested_headers.split(', '))

        requested_method = requested_method.upper()
        allowed_methods = settings['allow_methods']
        if requested_method not in allowed_methods:
            raise HTTPMethodNotAllowed(
                requested_method,
                allowed_methods,
                text='Access-Control-Request-Method Method not allowed')

        supported_headers = settings['allow_headers']
        if '*' not in supported_headers and requested_headers:
            supported_headers = [s.lower() for s in supported_headers]
            for h in requested_headers:
                if not h.lower() in supported_headers:
                    raise HTTPUnauthorized(
                        text=
                        'Access-Control-Request-Headers Header %s not allowed'
                        % h)

        supported_headers = [] if supported_headers is None else supported_headers
        requested_headers = [] if requested_headers is None else requested_headers

        supported_headers = set(supported_headers) | set(requested_headers)

        headers['Access-Control-Allow-Headers'] = ','.join(supported_headers)
        headers['Access-Control-Allow-Methods'] = ','.join(
            settings['allow_methods'])
        headers['Access-Control-Max-Age'] = str(settings['max_age'])
        return headers
Ejemplo n.º 6
0
 async def handler(self, request: 'Request') -> 'Response':
     logger.info(
         f'Request - path: {request.path}; method: {request.method}')
     try:
         method = self.methods[request.method]
     except KeyError:
         raise HTTPMethodNotAllowed('', RestBase.METHODS)
     status, body = await method(request)
     logger.info(f'Response - status: {status}; body: {body}')
     return Response(status=status,
                     body=body,
                     content_type='application/json')
Ejemplo n.º 7
0
 async def resolve(self, request):
     try:
         match = self.routes.match(path=request.path, method=request.method)
     except Exception as err:
         if isinstance(err,
                       MatchError):  # the HTTPMethodRouter raised an error
             method_key = err._pyger['router'].method_key
             method = err._pyger['kwargs'][method_key]
             allowed_methods = err._pyger['router'].keys()
             err = HTTPMethodNotAllowed(method, allowed_methods)
         return MatchInfoError(err)
     route = ResourceRoute(request.method, match.target, match)
     return UrlMappingMatchInfo(match.match_info, route)
Ejemplo n.º 8
0
    async def dispatch(self, request: Request):
        method = self.methods.get(request.method.upper())
        if not method:
            raise HTTPMethodNotAllowed('', DEFAULT_METHODS)

        wanted_args = list(inspect.signature(method).parameters.keys())
        available_args = request.match_info.copy()
        available_args.update({'request': request})

        unsatisfied_args = set(wanted_args) - set(available_args.keys())
        if unsatisfied_args:
            raise HttpBadRequest('')

        return await method(**{arg_name: available_args[arg_name] for arg_name in wanted_args})
Ejemplo n.º 9
0
def resolve2(router, method, path):
    allowed_methods = set()

    for resource in router._resources:
        match_dict, allowed = yield from resource.resolve(method, path)
        if match_dict is not None:
            return match_dict
        else:
            allowed_methods |= allowed
    else:
        if allowed_methods:
            return MatchInfoError(HTTPMethodNotAllowed(method,
                                                       allowed_methods))
        else:
            return MatchInfoError(HTTPNotFound())
Ejemplo n.º 10
0
    def resolve(self, request):
        method = request._method
        allowed_methods = set()

        for resource in self._resources:
            match_dict, allowed = yield from resource.resolve(request)
            if match_dict is not None:
                return match_dict
            else:
                allowed_methods |= allowed
        else:
            if allowed_methods:
                return MatchInfoError(HTTPMethodNotAllowed(method,
                                                           allowed_methods))
            else:
                return MatchInfoError(HTTPNotFound())
Ejemplo n.º 11
0
    def get_handler_or_raise_405(
            self) -> t.Callable[[], t.Coroutine[t.Any, t.Any, Response]]:
        """
        Finds and returns the handler in current class for requested method.
        Otherwise raises 405 response.
        """

        handler = getattr(self, self.request.method.lower(), None)

        if not handler:
            raise HTTPMethodNotAllowed(
                method=self.request.method,
                allowed_methods=self.get_allowed_methods(),
            )

        return handler
Ejemplo n.º 12
0
    async def dispatch(self, request: Request):
        """
        This method is used in calling HTTP methods in subclasses.
        :param request: HTTP method. In this API it is GET.
        """
        method = self.methods.get(request.method.upper())
        if not method:
            raise HTTPMethodNotAllowed('', DEFAULT_METHODS)

        method_args = list(inspect.signature(method).parameters)
        received_request_args = request.match_info.copy()
        ordered_method_arguments = {
            arg_name: received_request_args[arg_name]
            for arg_name in method_args
        }

        return await method(**ordered_method_arguments)
Ejemplo n.º 13
0
    async def _iter(self):
        try:
            await self._parse_request()
            await self.pre_handle()

            action_title = self.request.match_info['method']

            if action_title is None:
                raise HTTPNotFound()

            method = self.request.method.upper()
            methods = self.methods
            if methods is None:
                methods = {}

            actions = methods.get(method, {})

            def_method = self.default_methods.get(method)
            if action_title in actions:
                executing_method = actions.get(action_title)
            elif def_method is not None:
                executing_method = def_method
            else:
                executing_method = None

            if executing_method is not None:
                await self.before_action()
                result = await executing_method()
                await self.after_action()
                await self.post_handle(self.request, result)
                return result
            else:
                allowed_methods = []
                for k, k_actions in methods.items():
                    if action_title in k_actions:
                        allowed_methods.append(k)

                if allowed_methods:
                    raise HTTPMethodNotAllowed(method,
                                               allowed_methods=allowed_methods)

                raise HTTPNotFound()
        except Exception as e:
            res = self.handle_exception(e)
            return res
Ejemplo n.º 14
0
    async def resolve(self, request):
        allowed_methods = set()

        for resource in self._resources:
            match_dict, allowed = await resource.resolve(request)
            if match_dict is not None:
                return match_dict
            else:
                allowed_methods |= allowed

        if not allowed_methods:
            return MatchInfoError(HTTPNotFound())
        elif self._default_options_route is not None:
            request['allowed_methods'] = allowed_methods
            return UrlMappingMatchInfo({}, self._default_options_route)
        else:
            return MatchInfoError(
                HTTPMethodNotAllowed(request.method, allowed_methods))
Ejemplo n.º 15
0
    async def dispatch(self, request: Request):
        """
        This is the method being called when the user sends the request
        """
        method = self.methods.get(request.method.upper())
        if not method:
            raise HTTPMethodNotAllowed('', DEFAULT_METHODS)

        wanted_args = list(inspect.signature(method).parameters.keys())
        available_args = request.match_info.copy()
        available_args.update({'request': request})

        unsatisfied_args = set(wanted_args) - set(available_args.keys())
        if unsatisfied_args:
            # Expected match info that doesn't exist
            raise HttpBadRequest('')

        return await method(**{arg_name: available_args[arg_name] for arg_name in wanted_args})
Ejemplo n.º 16
0
    async def dispatch(self, request: Request):
        method = self.methods.get(request.method.upper())
        if not method:
            raise HTTPMethodNotAllowed("", DEFAULT_METHODS)

        wanted_args = list(inspect.signature(method).parameters.keys())

        available_args = request.match_info.copy()
        available_args["request"] = request

        unsatisfied_args = set(wanted_args) - set(available_args.keys())
        if unsatisfied_args:
            # Expected match info that doesn't exist
            raise HttpBadRequest("")

        return await method(
            **{arg_name: available_args[arg_name]
               for arg_name in wanted_args})
Ejemplo n.º 17
0
    async def handle(self, request):
        body = await request.json()
        req_id = body['id']
        method = body['method']
        hash_or_number, _ = body['params']
        if method == 'eth_getBlockByNumber':
            if hash_or_number == "latest":
                head = self.chain.get_canonical_head()
                number = head.block_number
            else:
                number = int(hash_or_number, 16)
            block = await self.chain.get_canonical_block_by_number(number)
        elif method == 'eth_getBlockByHash':
            block_hash = decode_hex(hash_or_number)
            block = await self.chain.get_block_by_hash(block_hash)
        else:
            raise HTTPMethodNotAllowed(method, self.allowed_methods)

        block_dict = self._block_to_dict(block)
        response = {"jsonrpc": "2.0", "id": req_id, "result": block_dict}
        return web.json_response(response)
Ejemplo n.º 18
0
    async def dispatch(self, request):
        method = self.methods.get(request.method.upper())
        if not method:
            _logger.warning(f'Method {request.method.upper()} not allowed'
                            f' in {self.__class__.__name__}!')
            raise HTTPMethodNotAllowed('', DEFAULT_METHODS)

        # Checking if args are available in method
        _logger.debug('Checking args...')
        required_args = list(inspect.signature(method).parameters.keys())
        given_args = request.match_info.copy()
        given_args.update({'request': request})

        unsatisfied_args = set(required_args) - set(given_args.keys())
        if unsatisfied_args:
            # If required args are not provided raises BadRequest Exc
            _logger.error(f'Unsatisfied args: {unsatisfied_args}')
            raise HTTPBadRequest('')

        return await method(
            **{arg_name: given_args[arg_name]
               for arg_name in given_args})
Ejemplo n.º 19
0
    def _handle(self, request, path):
        """Route data to hassio."""
        if path.startswith('addons/'):
            parts = path.split('/')

            if len(parts) != 3:
                raise HTTPNotFound()

            allowed_methods = ADDON_REST_COMMANDS.get(parts[-1])
        else:
            allowed_methods = HASSIO_REST_COMMANDS.get(path)

        if allowed_methods is None:
            raise HTTPNotFound()
        if request.method not in allowed_methods:
            raise HTTPMethodNotAllowed(request.method, allowed_methods)

        client = yield from self.hassio.command_proxy(path, request)

        data = yield from client.read()
        if path.endswith('/logs'):
            return _create_response_log(client, data)
        return _create_response(client, data)
Ejemplo n.º 20
0
    async def dispatch(self, request: web.Request):
        method = self.methods.get(request.method.upper())
        if not method:
            raise HTTPMethodNotAllowed('', DEFAULT_METHODS)

        wanted_args = list(inspect.signature(method).parameters.keys())
        available_args = request.match_info.copy()
        available_args.update({'request': request})

        unsatisfied_args = set(wanted_args) - set(available_args.keys())
        if unsatisfied_args:
            raise HttpBadRequest('')

        try:
            return await method(**{
                arg_name: available_args[arg_name]
                for arg_name in wanted_args
            })
        except Exception as ex:
            template = "Server error, an exception of type {0} occurred. Arguments:{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            return web.Response(status=500,
                                body=json.dumps({message: 500}),
                                content_type='application/json')
Ejemplo n.º 21
0
    async def dispatch(self, method, url, **kwargs):
        method = self.methods.get(method.upper())
        if not method:
            raise HTTPMethodNotAllowed('', DEFAULT_METHODS)

        return await method(url, **kwargs)
Ejemplo n.º 22
0
 def _raise_allowed_methods(self) -> None:
     allowed_methods = {
         m for m in self.allowed_methods if hasattr(self, m.lower())}
     raise HTTPMethodNotAllowed(self.request.method, allowed_methods)
Ejemplo n.º 23
0
 def _raise_allowed_methods(self):
     allowed_methods = {
         m for m in hdrs.METH_ALL if hasattr(self, m.lower())}
     raise HTTPMethodNotAllowed(self.request.method, allowed_methods)
Ejemplo n.º 24
0
 def _raise_allowed_methods(self) -> None:
     raise HTTPMethodNotAllowed(self.request.method, self.allowed_methods)
Ejemplo n.º 25
0
    async def dispatch(self, request: Request):
        method = self.__methods.get(request.method)
        if not method:
            raise HTTPMethodNotAllowed(self.DEFAULT_METHODS)

        return await method()
Ejemplo n.º 26
0
    async def dispatch(self):
        method = self.methods.get(self.request.method.lower())
        if not method:
            raise HTTPMethodNotAllowed('', DEFAULT_METHODS)

        return await method()
Ejemplo n.º 27
0
    async def real_resolve(self, request: IRequest) -> MatchInfo:
        """Main function to resolve a request."""
        security = get_adapter(request, IInteraction)

        if request.method not in app_settings['http_methods']:
            raise HTTPMethodNotAllowed()
        method = app_settings['http_methods'][request.method]

        language = language_negotiation(request)
        language_object = language(request)

        try:
            resource, tail = await self.traverse(request)
        except ConflictError:
            # can also happen from connection errors so we bubble this...
            raise
        except Exception as _exc:
            logger.error('Unhandled exception occurred', exc_info=True)
            request.resource = request.tail = None
            request.exc = _exc
            data = {
                'success': False,
                'exception_message': str(_exc),
                'exception_type': getattr(type(_exc), '__name__',
                                          str(type(_exc))),  # noqa
            }
            if app_settings.get('debug'):
                data['traceback'] = traceback.format_exc()
            raise HTTPBadRequest(text=ujson.dumps(data))

        request.record('traversed')

        await notify(ObjectLoadedEvent(resource))
        request.resource = resource
        request.tail = tail

        if request.resource is None:
            raise HTTPBadRequest(text='Resource not found')

        traverse_to = None
        if tail and len(tail) == 1:
            view_name = tail[0]
        elif tail is None or len(tail) == 0:
            view_name = ''
        else:
            view_name = tail[0]
            traverse_to = tail[1:]

        request.record('beforeauthentication')
        await self.apply_authorization(request)
        request.record('authentication')

        translator = query_adapter(language_object,
                                   ITranslated,
                                   args=[resource, request])
        if translator is not None:
            resource = translator.translate()

        # Add anonymous participation
        if len(security.participations) == 0:
            security.add(AnonymousParticipation(request))

        # container registry lookup
        try:
            view = query_multi_adapter((resource, request),
                                       method,
                                       name=view_name)
        except AttributeError:
            view = None

        request.found_view = view
        request.view_name = view_name

        # Traverse view if its needed
        if traverse_to is not None and view is not None:
            if not ITraversableView.providedBy(view):
                return None
            else:
                try:
                    view = await view.publish_traverse(traverse_to)
                except KeyError:
                    return None  # not found, it's okay.
                except Exception as e:
                    logger.error("Exception on view execution",
                                 exc_info=e,
                                 request=request)
                    return None

        request.record('viewfound')
        permission = get_utility(IPermission, name='guillotina.AccessContent')

        if not security.check_permission(permission.id, resource):
            # Check if its a CORS call:
            if IOPTIONS != method:
                # Check if the view has permissions explicit
                if view is None or not view.__allow_access__:
                    logger.info(
                        "No access content {content} with {auths}".format(
                            content=resource,
                            auths=str([
                                x.principal.id for x in security.participations
                            ])),
                        request=request)
                    raise HTTPUnauthorized()

        if view is None and method == IOPTIONS:
            view = DefaultOPTIONS(resource, request)

        if view:
            ViewClass = view.__class__
            view_permission = get_view_permission(ViewClass)
            if not security.check_permission(view_permission, view):
                logger.info("No access for view {content} with {auths}".format(
                    content=resource,
                    auths=str(
                        [x.principal.id for x in security.participations])),
                            request=request)
                raise HTTPUnauthorized()

        request.record('authorization')

        renderer = content_type_negotiation(request, resource, view)
        renderer_object = renderer(request)

        rendered = query_multi_adapter((renderer_object, view, request),
                                       IRendered)

        request.record('renderer')

        if rendered is not None:
            return MatchInfo(resource, request, view, rendered)
        else:
            return None
Ejemplo n.º 28
0
 async def raise_not_allowed(self):
     raise HTTPMethodNotAllowed(self.request.method, self.allowed_methods)
Ejemplo n.º 29
0
 def handler(request):
     raise HTTPMethodNotAllowed(method='GET', allowed_methods=[])