# Buggy code
def setup_cors(app, origins):
    """Setup cors."""
    import aiohttp_cors

    cors = aiohttp_cors.setup(
        app,
        defaults={
            host: aiohttp_cors.ResourceOptions(
                allow_headers=ALLOWED_CORS_HEADERS,
                allow_methods="*",
            )
            for host in origins
        },
    )

    def allow_cors(route, methods):
        """Allow cors on a route."""
        cors.add(
            route,
            {
                "*": aiohttp_cors.ResourceOptions(
                    allow_headers=ALLOWED_CORS_HEADERS,
                    allow_methods=methods,
                )
            },
        )

    app["allow_cors"] = allow_cors

    if not origins:
        return

    async def cors_startup(app):
        """Initialize cors when app starts up."""
        cors_added = set()

        for route in list(app.router.routes()):
            if hasattr(route, "resource"):
                route = route.resource
            if route in cors_added:
                continue
            cors.add(route)
            cors_added.add(route)

    app.on_startup.append(cors_startup)


# Traceback (ValueError)
2018-07-24 20:02:02 ERROR (MainThread) [homeassistant.core] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
File "/usr/src/app/homeassistant/components/http/__init__.py", line 132, in start_server
await server.start()
File "/usr/src/app/homeassistant/components/http/__init__.py", line 284, in start
await self.app.startup()
File "/usr/local/lib/python3.6/site-packages/aiohttp/web_app.py", line 278, in startup
await self.on_startup.send(self)
File "/usr/local/lib/python3.6/site-packages/aiohttp/signals.py", line 35, in send
await receiver(*args, **kwargs)
File "/usr/src/app/homeassistant/components/http/cors.py", line 53, in cors_startup
cors.add(route)
File "/usr/local/lib/python3.6/site-packages/aiohttp_cors/cors_config.py", line 263, in add
return self._cors_impl.add(routing_entity, config)
File "/usr/local/lib/python3.6/site-packages/aiohttp_cors/cors_config.py", line 137, in add
routing_entity, parsed_config)
File "/usr/local/lib/python3.6/site-packages/aiohttp_cors/urldispatcher_router_adapter.py", line 240, in set_config_for_routing_entity
resource))
ValueError: CORS is already configured for <PlainResource  /auth/token> resource.

# Fixed code
def setup_cors(app, origins):
    """Setup cors."""
    import aiohttp_cors

    cors = aiohttp_cors.setup(
        app,
        defaults={
            host: aiohttp_cors.ResourceOptions(
                allow_headers=ALLOWED_CORS_HEADERS,
                allow_methods="*",
            )
            for host in origins
        },
    )

    cors_added = set()

    def _allow_cors(route, config=None):
        """Allow cors on a route."""
        if hasattr(route, "resource"):
            path = route.resource
        else:
            path = route

        path = path.canonical

        if path in cors_added:
            return

        cors.add(route, config)
        cors_added.add(path)

    app["allow_cors"] = lambda route: _allow_cors(
        route,
        {
            "*": aiohttp_cors.ResourceOptions(
                allow_headers=ALLOWED_CORS_HEADERS,
                allow_methods="*",
            )
        },
    )

    if not origins:
        return

    async def cors_startup(app):
        """Initialize cors when app starts up."""
        for route in list(app.router.routes()):
            _allow_cors(route)

    app.on_startup.append(cors_startup)