Ejemplo n.º 1
0
def setup_routes(app: Application, base_dir: Path,
                 cors_config: CorsConfig) -> None:
    app.router.add_view('/zbs/login', LoginView, name='login_view')
    app.router.add_view('/zbs/logout', LogoutView)
    app.router.add_view('/zbs/switches',
                        SwitchListAdminView,
                        name='switches_list')
    app.router.add_view('/zbs/switches/add',
                        SwitchAddAdminView,
                        name='switches_add')
    app.router.add_view('/zbs/switches/copy',
                        SwitchesCopyAdminView,
                        name='switches_copy')
    app.router.add_view('/zbs/switches/{id}',
                        SwitchDetailAdminView,
                        name='switch_detail')
    app.router.add_view('/zbs/switches/{id}/delete', SwitchDeleteAdminView)
    app.router.add_view('/zbs/users', UserListAdminView)
    app.router.add_view('/zbs/users/{id}', UserDetailAdminView)

    get_switch_view = app.router.add_view('/api/v1/switch', SwitchListView)
    cors_config.add(get_switch_view)

    if settings.ENABLE_SWITCHES_FULL_INFO_ENDPOINT:
        get_switch_full_view = app.router.add_view(
            '/api/v1/switches_full_info', SwitchFullListView)
        cors_config.add(get_switch_full_view)

    if settings.ENVIRONMENT == 'Dev':
        app.router.add_static('/static', str(base_dir / 'its_on' / 'static'))
Ejemplo n.º 2
0
 def enable_cors(cls, cors: CorsConfig):
     """Enables CORS on the view."""
     try:
         cors.add(cls.route, webview=True)
     except AttributeError as error:
         raise ViewConfigurationError(
             "No route assigned. Please register the route first."
         ) from error
Ejemplo n.º 3
0
 def setUp(self):
     self.loop = asyncio.new_event_loop()
     self.app = web.Application(loop=self.loop)
     self.cors = CorsConfig(self.app, defaults={"*": ResourceOptions()})
     self.get_route = self.app.router.add_route("GET", "/get_path",
                                                _handler)
     self.options_route = self.app.router.add_route("OPTIONS",
                                                    "/options_path",
                                                    _handler)
Ejemplo n.º 4
0
 def setUp(self):
     self.loop = asyncio.new_event_loop()
     self.app = web.Application(loop=self.loop)
     self.cors = CorsConfig(self.app, defaults={
         "*": ResourceOptions()
     })
     self.get_route = self.app.router.add_route(
         "GET", "/get_path", _handler)
     self.options_route = self.app.router.add_route(
         "OPTIONS", "/options_path", _handler)
Ejemplo n.º 5
0
class TestCorsConfig(unittest.TestCase):
    """Unit tests for CorsConfig"""
    def setUp(self):
        self.loop = asyncio.new_event_loop()
        self.app = web.Application(loop=self.loop)
        self.cors = CorsConfig(self.app, defaults={"*": ResourceOptions()})
        self.get_route = self.app.router.add_route("GET", "/get_path",
                                                   _handler)
        self.options_route = self.app.router.add_route("OPTIONS",
                                                       "/options_path",
                                                       _handler)

    def tearDown(self):
        self.loop.close()

    def test_add_options_route(self):
        """Test configuring OPTIONS route"""

        with self.assertRaises(RuntimeError):
            self.cors.add(self.options_route.resource)

    def test_plain_named_route(self):
        """Test adding plain named route."""
        # Adding CORS routes should not introduce new named routes.
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_route("GET",
                                          "/{name}",
                                          _handler,
                                          name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)

    def test_dynamic_named_route(self):
        """Test adding dynamic named route."""
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_route("GET",
                                          "/{name}",
                                          _handler,
                                          name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)

    def test_static_named_route(self):
        """Test adding dynamic named route."""
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_static("/file",
                                           "/",
                                           name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)
Ejemplo n.º 6
0
    def __init__(self, port, logs=None):

        # Build Web App
        self.port = port
        self.logs = logs
        self.webapp = web.Application(middlewares=[
            # Just in case someone wants to use it behind a reverse proxy
            # Not sure why someone will want to do that though
            XForwardedRelaxed().middleware,
            # Handle unexpected and HTTP exceptions
            self._middleware_exceptions,
            # Handle media type validation
            self._middleware_media_type,
            # Handle schema validation
            self._middleware_schema,
        ])

        self.webapp.router.add_get('/api/logs', self.api_logs)
        self.webapp.router.add_post('/api/config', self.api_config)
        self.webapp.router.add_post('/api/push', self.api_push)
        self.webapp.router.add_post('/api/message', self.api_message)

        # Enable CORS in case someone wants to build a web agent
        self.cors = CorsConfig(
            self.webapp, defaults={
                '*': ResourceOptions(
                    allow_credentials=True,
                    expose_headers='*',
                    allow_headers='*',
                )
            }
        )
        for route in self.webapp.router.routes():
            self.cors.add(route)

        # Create task for the push hearbeat
        event_loop = get_event_loop()

        self.timestamp = None
        self.heartbeat = event_loop.create_task(self._check_last_timestamp())

        # Build Terminal UI App
        self.ui = UIManager()
        self.tuiapp = MainLoop(
            self.ui.topmost,
            pop_ups=True,
            palette=self.ui.palette,
            event_loop=AsyncioEventLoop(loop=event_loop),
        )
Ejemplo n.º 7
0
class TestCorsConfig(unittest.TestCase):
    """Unit tests for CorsConfig"""
    def setUp(self):
        self.loop = asyncio.new_event_loop()
        self.app = web.Application(loop=self.loop)
        self.cors = CorsConfig(self.app, defaults={"*": ResourceOptions()})
        self.get_route = self.app.router.add_route("GET", "/get_path",
                                                   _handler)
        self.options_route = self.app.router.add_route("OPTIONS",
                                                       "/options_path",
                                                       _handler)

    def tearDown(self):
        self.loop.close()

    def test_add_get_route(self):
        """Test configuring GET route"""
        result = self.cors.add(self.get_route)
        self.assertIs(result, self.get_route)

        self.assertEqual(len(self.cors._route_config), 1)
        self.assertIn(self.get_route, self.cors._route_config)

        self.assertEqual(len(self.cors._preflight_route_settings), 1)

    def test_add_options_route(self):
        """Test configuring OPTIONS route"""

        with self.assertRaisesRegex(
                ValueError,
                "CORS can't be enabled on route that handles OPTIONS request"):
            self.cors.add(self.options_route)

        self.assertFalse(self.cors._route_config)
        self.assertFalse(self.cors._preflight_route_settings)

    def test_add_preflight_route(self):
        """Test configuring preflight route"""

        self.cors.add(self.get_route)
        preflight_route = next(iter(
            self.cors._preflight_route_settings.keys()))

        self.assertEqual(len(self.cors._route_config), 1)
        self.assertEqual(len(self.cors._preflight_route_settings), 1)

        # TODO: Capture and verify log warning message.
        result = self.cors.add(preflight_route)
        self.assertIs(result, preflight_route)

        self.assertEqual(len(self.cors._route_config), 1)
        self.assertEqual(len(self.cors._preflight_route_settings), 1)

    def test_plain_named_route(self):
        """Test adding plain named route."""
        # Adding CORS routes should not introduce new named routes.
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_route("GET",
                                          "/{name}",
                                          _handler,
                                          name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)

    def test_dynamic_named_route(self):
        """Test adding dynamic named route."""
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_route("GET",
                                          "/{name}",
                                          _handler,
                                          name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)

    def test_static_named_route(self):
        """Test adding dynamic named route."""
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_static("/file",
                                           "/",
                                           name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)
Ejemplo n.º 8
0
def _enable_cors(prefix: str, cors: CorsConfig):
    for route in web_server.router.routes():
        if route.resource and route.resource.canonical.startswith(prefix):
            cors.add(route)
Ejemplo n.º 9
0
def cors(app):
    return CorsConfig(app, defaults={
        "*": ResourceOptions()
    })
Ejemplo n.º 10
0
class TestCorsConfig(unittest.TestCase):
    """Unit tests for CorsConfig"""

    def setUp(self):
        self.loop = asyncio.new_event_loop()
        self.app = web.Application(loop=self.loop)
        self.cors = CorsConfig(self.app, defaults={
            "*": ResourceOptions()
        })
        self.get_route = self.app.router.add_route(
            "GET", "/get_path", _handler)
        self.options_route = self.app.router.add_route(
            "OPTIONS", "/options_path", _handler)

    def tearDown(self):
        self.loop.close()

    def test_add_options_route(self):
        """Test configuring OPTIONS route"""

        with self.assertRaises(RuntimeError):
            self.cors.add(self.options_route.resource)

    def test_plain_named_route(self):
        """Test adding plain named route."""
        # Adding CORS routes should not introduce new named routes.
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_route(
            "GET", "/{name}", _handler, name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)

    def test_dynamic_named_route(self):
        """Test adding dynamic named route."""
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_route(
            "GET", "/{name}", _handler, name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)

    def test_static_named_route(self):
        """Test adding dynamic named route."""
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_static(
            "/file", "/", name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)

    def test_static_resource(self):
        """Test adding static resource."""
        self.assertEqual(len(self.app.router.keys()), 0)
        self.app.router.add_static(
            "/file", "/", name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        for resource in list(self.app.router.resources()):
            if issubclass(resource, web.StaticResource):
                self.cors.add(resource)
        self.assertEqual(len(self.app.router.keys()), 1)
Ejemplo n.º 11
0
def cors(_app):
    ret = CorsConfig(_app, defaults=DEFAULT_CONFIG)
    _app[APP_CONFIG_KEY] = ret
    return ret
Ejemplo n.º 12
0
class TestCorsConfig(unittest.TestCase):
    """Unit tests for CorsConfig"""

    def setUp(self):
        self.loop = asyncio.new_event_loop()
        self.app = web.Application(loop=self.loop)
        self.cors = CorsConfig(self.app, defaults={
            "*": ResourceOptions()
        })
        self.get_route = self.app.router.add_route(
            "GET", "/get_path", _handler)
        self.options_route = self.app.router.add_route(
            "OPTIONS", "/options_path", _handler)

    def tearDown(self):
        self.loop.close()

    def test_add_get_route(self):
        """Test configuring GET route"""
        result = self.cors.add(self.get_route)
        self.assertIs(result, self.get_route)

        self.assertEqual(len(self.cors._route_config), 1)
        self.assertIn(self.get_route, self.cors._route_config)

        self.assertEqual(len(self.cors._preflight_route_settings), 1)

    def test_add_options_route(self):
        """Test configuring OPTIONS route"""

        with self.assertRaisesRegex(
                ValueError,
                "CORS can't be enabled on route that handles OPTIONS request"):
            self.cors.add(self.options_route)

        self.assertFalse(self.cors._route_config)
        self.assertFalse(self.cors._preflight_route_settings)

    def test_add_preflight_route(self):
        """Test configuring preflight route"""

        self.cors.add(self.get_route)
        preflight_route = next(iter(
            self.cors._preflight_route_settings.keys()))

        self.assertEqual(len(self.cors._route_config), 1)
        self.assertEqual(len(self.cors._preflight_route_settings), 1)

        # TODO: Capture and verify log warning message.
        result = self.cors.add(preflight_route)
        self.assertIs(result, preflight_route)

        self.assertEqual(len(self.cors._route_config), 1)
        self.assertEqual(len(self.cors._preflight_route_settings), 1)

    def test_plain_named_route(self):
        """Test adding plain named route."""
        # Adding CORS routes should not introduce new named routes.
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_route(
            "GET", "/{name}", _handler, name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)

    def test_dynamic_named_route(self):
        """Test adding dynamic named route."""
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_route(
            "GET", "/{name}", _handler, name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)

    def test_static_named_route(self):
        """Test adding dynamic named route."""
        self.assertEqual(len(self.app.router.keys()), 0)
        route = self.app.router.add_static(
            "/file", "/", name="dynamic_named_route")
        self.assertEqual(len(self.app.router.keys()), 1)
        self.cors.add(route)
        self.assertEqual(len(self.app.router.keys()), 1)