Skip to content

Commit

Permalink
Extract schemes
Browse files Browse the repository at this point in the history
  • Loading branch information
koldakov committed Jun 21, 2024
1 parent 0bc95c8 commit d8a1cd5
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion futuramaapi/middlewares/secure.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from typing import ClassVar

from starlette import status
from starlette.datastructures import URL
Expand All @@ -15,6 +16,10 @@
class HTTPSRedirectMiddleware(BaseHTTPMiddleware):
https_port: int = 443
http_port: int = 80
insecure_to_secure: ClassVar[dict[str, str]] = {
"http": "https",
"ws": "wss",
}

def is_secure(self, headers: dict):
try:
Expand All @@ -39,7 +44,7 @@ def is_secure(self, headers: dict):

def _fix_url(self, scope: Scope, /):
url = URL(scope=scope)
redirect_scheme = {"http": "https", "ws": "wss"}[url.scheme]
redirect_scheme = self.insecure_to_secure[url.scheme]
netloc = url.hostname if url.port in (self.http_port, self.https_port) else url.netloc
return url.replace(scheme=redirect_scheme, netloc=netloc)

Expand Down

0 comments on commit d8a1cd5

Please sign in to comment.