-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add redirect feature based on proto headers
Starlette/FastAPI don't support https redirect behind the proxy.
- Loading branch information
Showing
4 changed files
with
70 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
from typing import Dict | ||
|
||
from starlette import status | ||
from starlette.datastructures import URL | ||
from starlette.responses import RedirectResponse | ||
from starlette.types import ASGIApp, Receive, Scope, Send | ||
|
||
from app.core import settings | ||
|
||
|
||
class HTTPSRedirectMiddleware: | ||
https_port = 443 | ||
http_port = 80 | ||
proto_header = "x-forwarded-proto" | ||
port_header = "x-forwarded-port" | ||
|
||
def __init__(self, app: ASGIApp) -> None: | ||
self.app = app | ||
|
||
def is_secure(self, headers: Dict): | ||
try: | ||
host: str = headers["host"] | ||
except KeyError: | ||
return False | ||
try: | ||
proto: str = headers[self.proto_header] | ||
except KeyError: | ||
return False | ||
try: | ||
port: str = headers[self.port_header] | ||
except KeyError: | ||
return False | ||
|
||
if ( | ||
host == settings.trusted_host | ||
and proto in ("https", "wss") | ||
and int(port) == self.https_port | ||
): | ||
return True | ||
return False | ||
|
||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
headers: Dict = {h[0].decode().lower(): h[1].decode() for h in scope["headers"]} | ||
if not self.is_secure(headers): | ||
url = URL(scope=scope) | ||
redirect_scheme = {"http": "https", "ws": "wss"}[url.scheme] | ||
netloc = ( | ||
url.hostname | ||
if url.port in (self.http_port, self.https_port) | ||
else url.netloc | ||
) | ||
url = url.replace(scheme=redirect_scheme, netloc=netloc) | ||
response = RedirectResponse( | ||
url, | ||
status_code=status.HTTP_307_TEMPORARY_REDIRECT, | ||
) | ||
await response(scope, receive, send) | ||
else: | ||
await self.app(scope, receive, send) |