aiohttp.web.HTTPForbidden

Here are the examples of the python api aiohttp.web.HTTPForbidden taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

16 Examples 7

Example 1

Project: aiohttp-security
License: View license
Source File: handlers.py
def require(permission):
    def wrapper(f):
        @asyncio.coroutine
        @functools.wraps(f)
        def wrapped(self, request):
            has_perm = yield from permits(request, permission)
            if not has_perm:
                message = 'User has no permission {}'.format(permission)
                raise web.HTTPForbidden(body=message.encode())
            return (yield from f(self, request))
        return wrapped
    return wrapper

Example 2

Project: gns3-server
License: View license
Source File: config_handler.py
    @classmethod
    @Route.post(
        r"/config/reload",
        description="Check if version is the same as the server",
        status_codes={
            201: "Config reload",
            403: "Config reload refused"
        })
    def reload(request, response):

        config = Config.instance()
        if config.get_section_config("Server").getboolean("local", False) is False:
            raise HTTPForbidden(text="You can only reload the configuration for a local server")
        config.reload()
        response.set_status(201)

Example 3

Project: gns3-server
License: View license
Source File: project.py
    @location.setter
    def location(self, location):

        if location != self._location and self.is_local() is False:
            raise aiohttp.web.HTTPForbidden(text="You are not allowed to modify the project directory location")

        self._location = location

Example 4

Project: gns3-server
License: View license
Source File: project.py
    @path.setter
    def path(self, path):

        if hasattr(self, "_path"):
            if path != self._path and self.is_local() is False:
                raise aiohttp.web.HTTPForbidden(text="You are not allowed to modify the project directory path")

        if '"' in path:
            raise aiohttp.web.HTTPForbidden(text="You are not allowed to use \" in the project directory path. It's not supported by Dynamips.")

        self._path = path
        self._update_temporary_file()

Example 5

Project: gns3-server
License: View license
Source File: project.py
    @name.setter
    def name(self, name):

        if "/" in name or "\\" in name:
            raise aiohttp.web.HTTPForbidden(text="Name can not contain path separator")
        self._name = name

Example 6

Project: ircb
License: View license
Source File: user.py
    @asyncio.coroutine
    def post(self):
        username = yield from auth.get_auth(self.request)
        if username:
            raise web.HTTPForbidden()
        data = yield from self.request.post()
        form = UserForm(formdata=data)
        form.validate()
        yield from self._validate_username(form)
        yield from self._validate_email(form)
        if form.errors:
            return web.Response(body=json.dumps(form.errors).encode(),
                                status=400,
                                content_type='application/json')
        cleaned_data = form.data
        yield from UserStore.create(
            dict(
                username=cleaned_data['username'],
                email=cleaned_data['email'],
                password=cleaned_data['password'],
                first_name=cleaned_data.get('first_name', ''),
                last_name=cleaned_data.get('last_name', '')
            )
        )
        return web.Response(body=b'OK')

Example 7

Project: sockjs
License: View license
Source File: xhrsend.py
    @asyncio.coroutine
    def process(self):
        request = self.request

        if request.method not in (
                hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS):
            return web.HTTPForbidden(text='Method is not allowed')

        if self.request.method == hdrs.METH_OPTIONS:
            base_headers = (
                (hdrs.ACCESS_CONTROL_ALLOW_METHODS, 'OPTIONS, POST'),
                (hdrs.CONTENT_TYPE, 'application/javascript; charset=UTF-8'))
            headers = list(
                base_headers +
                session_cookie(request) +
                cors_headers(request.headers) +
                cache_headers())
            return web.Response(status=204, headers=headers)

        data = yield from request.read()
        if not data:
            return web.HTTPInternalServerError(text='Payload expected.')

        try:
            messages = loads(data.decode(ENCODING))
        except:
            return web.HTTPInternalServerError(text="Broken JSON encoding.")

        yield from self.session._remote_messages(messages)

        headers = list(
            ((hdrs.CONTENT_TYPE, 'text/plain; charset=UTF-8'),
             (hdrs.CACHE_CONTROL,
              'no-store, no-cache, must-revalidate, max-age=0')) +
            session_cookie(request) +
            cors_headers(request.headers))

        return web.Response(status=204, headers=headers)

Example 8

Project: gns3-server
License: View license
Source File: file_handler.py
    @classmethod
    @Route.get(
        r"/files/stream",
        description="Stream a file from the server",
        status_codes={
            200: "File retrieved",
            404: "File doesn't exist",
            409: "Can't access to file"
        },
        input=FILE_STREAM_SCHEMA
    )
    def read(request, response):
        response.enable_chunked_encoding()

        if not request.json.get("location").endswith(".pcap"):
            raise aiohttp.web.HTTPForbidden(text="Only .pcap file are allowed")

        try:
            with open(request.json.get("location"), "rb") as f:
                loop = asyncio.get_event_loop()
                response.content_type = "application/octet-stream"
                response.set_status(200)
                # Very important: do not send a content lenght otherwise QT close the connection but curl can consume the Feed
                response.content_length = None

                response.start(request)

                while True:
                    data = yield from loop.run_in_executor(None, f.read, 16)
                    if len(data) == 0:
                        yield from asyncio.sleep(0.1)
                    else:
                        response.write(data)
        except FileNotFoundError:
            raise aiohttp.web.HTTPNotFound()
        except OSError as e:
            raise aiohttp.web.HTTPConflict(text=str(e))

Example 9

Project: gns3-server
License: View license
Source File: project_handler.py
    @classmethod
    @Route.get(
        r"/projects/{project_id}/files/{path:.+}",
        description="Get a file of a project",
        parameters={
            "project_id": "The UUID of the project",
        },
        status_codes={
            200: "Return the file",
            403: "Permission denied",
            404: "The file doesn't exist"
        })
    def get_file(request, response):

        pm = ProjectManager.instance()
        project = pm.get_project(request.match_info["project_id"])
        path = request.match_info["path"]
        path = os.path.normpath(path)

        # Raise error if user try to escape
        if path[0] == ".":
            raise aiohttp.web.HTTPForbidden
        path = os.path.join(project.path, path)

        response.content_type = "application/octet-stream"
        response.set_status(200)
        response.enable_chunked_encoding()
        # Very important: do not send a content length otherwise QT close the connection but curl can consume the Feed
        response.content_length = None

        try:
            with open(path, "rb") as f:
                response.start(request)
                while True:
                    data = f.read(4096)
                    if not data:
                        break
                    yield from response.write(data)

        except FileNotFoundError:
            raise aiohttp.web.HTTPNotFound()
        except PermissionError:
            raise aiohttp.web.HTTPForbidden()

Example 10

Project: gns3-server
License: View license
Source File: project_handler.py
    @classmethod
    @Route.post(
        r"/projects/{project_id}/files/{path:.+}",
        description="Get a file of a project",
        parameters={
            "project_id": "The UUID of the project",
        },
        raw=True,
        status_codes={
            200: "Return the file",
            403: "Permission denied",
            404: "The path doesn't exist"
        })
    def write_file(request, response):

        pm = ProjectManager.instance()
        project = pm.get_project(request.match_info["project_id"])
        path = request.match_info["path"]
        path = os.path.normpath(path)

        # Raise error if user try to escape
        if path[0] == ".":
            raise aiohttp.web.HTTPForbidden
        path = os.path.join(project.path, path)

        response.set_status(200)

        try:
            with open(path, 'wb+') as f:
                while True:
                    packet = yield from request.content.read(512)
                    if not packet:
                        break
                    f.write(packet)

        except FileNotFoundError:
            raise aiohttp.web.HTTPNotFound()
        except PermissionError:
            raise aiohttp.web.HTTPForbidden()

Example 11

Project: gns3-server
License: View license
Source File: server_handler.py
    @classmethod
    @Route.post(
        r"/server/shutdown",
        description="Shutdown the local server",
        status_codes={
            201: "Server is shutting down",
            403: "Server shutdown refused"
        })
    def shutdown(request, response):

        config = Config.instance()
        if config.get_section_config("Server").getboolean("local", False) is False:
            raise HTTPForbidden(text="You can only stop a local server")

        # close all the projects first
        pm = ProjectManager.instance()
        projects = pm.projects

        tasks = []
        for project in projects:
            tasks.append(asyncio.async(project.close()))

        if tasks:
            done, _ = yield from asyncio.wait(tasks)
            for future in done:
                try:
                    future.result()
                except Exception as e:
                    log.error("Could not close project {}".format(e), exc_info=1)
                    continue

        # then shutdown the server itself
        from gns3server.server import Server
        server = Server.instance()
        asyncio.async(server.shutdown_server())
        response.set_status(201)

Example 12

Project: gns3-server
License: View license
Source File: upload_handler.py
    @classmethod
    @Route.post(
        r"/upload",
        description="Manage upload of GNS3 images",
        api_version=None,
        raw=True
    )
    def upload(request, response):
        data = yield from request.post()

        if not data["file"]:
            response.redirect("/upload")
            return

        if data["type"] not in ["IOU", "IOURC", "QEMU", "IOS", "IMAGES", "PROJECTS"]:
            raise aiohttp.web.HTTPForbidden(text="You are not authorized to upload this kind of image {}".format(data["type"]))

        try:
            if data["type"] == "IMAGES":
                UploadHandler._restore_directory(data["file"], UploadHandler.image_directory())
            elif data["type"] == "PROJECTS":
                UploadHandler._restore_directory(data["file"], UploadHandler.project_directory())
            else:
                if data["type"] == "IOURC":
                    destination_dir = os.path.expanduser("~/")
                    destination_path = os.path.join(destination_dir, ".iourc")
                else:
                    destination_dir = os.path.join(UploadHandler.image_directory(), data["type"])
                    destination_path = os.path.join(destination_dir, data["file"].filename)
                os.makedirs(destination_dir, exist_ok=True)
                remove_checksum(destination_path)
                with open(destination_path, "wb+") as f:
                    while True:
                        chunk = data["file"].file.read(512)
                        if not chunk:
                            break
                        f.write(chunk)
                md5sum(destination_path)
                st = os.stat(destination_path)
                os.chmod(destination_path, st.st_mode | stat.S_IXUSR)
        except OSError as e:
            response.html("Could not upload file: {}".format(e))
            response.set_status(200)
            return
        response.redirect("/upload")

Example 13

Project: gns3-server
License: View license
Source File: base_manager.py
    @asyncio.coroutine
    def write_image(self, filename, stream):
        directory = self.get_images_directory()
        path = os.path.abspath(os.path.join(directory, *os.path.split(filename)))
        if os.path.commonprefix([directory, path]) != directory:
            raise aiohttp.web.HTTPForbidden(text="Could not write image: {}, {} is forbiden".format(filename, path))
        log.info("Writting image file %s", path)
        try:
            remove_checksum(path)
            # We store the file under his final name only when the upload is finished
            tmp_path = path + ".tmp"
            os.makedirs(os.path.dirname(path), exist_ok=True)
            with open(tmp_path, 'wb+') as f:
                while True:
                    packet = yield from stream.read(512)
                    if not packet:
                        break
                    f.write(packet)
            os.chmod(tmp_path, stat.S_IWRITE | stat.S_IREAD | stat.S_IEXEC)
            shutil.move(tmp_path, path)
            md5sum(path)
        except OSError as e:
            raise aiohttp.web.HTTPConflict(text="Could not write image: {} because {}".format(filename, e))

Example 14

Project: gns3-server
License: View license
Source File: test_project.py
def test_changing_location_not_allowed(tmpdir):
    with patch("gns3server.modules.project.Project.is_local", return_value=False):
        with pytest.raises(aiohttp.web.HTTPForbidden):
            p = Project(location=str(tmpdir))

Example 15

Project: gns3-server
License: View license
Source File: test_project.py
def test_changing_path_not_allowed(tmpdir):
    with patch("gns3server.modules.project.Project.is_local", return_value=False):
        with pytest.raises(aiohttp.web.HTTPForbidden):
            p = Project()
            p.path = str(tmpdir)

Example 16

Project: gns3-server
License: View license
Source File: test_project.py
def test_changing_path_with_quote_not_allowed(tmpdir):
    with patch("gns3server.modules.project.Project.is_local", return_value=True):
        with pytest.raises(aiohttp.web.HTTPForbidden):
            p = Project()
            p.path = str(tmpdir / "project\"53")