Created
December 14, 2023 07:39
-
-
Save minho-comcom-ai/31a06229ed830677bb8b0fc887a2328f to your computer and use it in GitHub Desktop.
I know, It's a shame.
This file contains hidden or 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
| from base64 import b64encode | |
| class AsgiLazySecure: | |
| def __init__(self, app, key, ignore_paths=[]): | |
| self.app = app | |
| self.bearer = f"Bearer {key}" | |
| _basic = b64encode(f"{key}:".encode()).decode() | |
| self.basic = f"Basic {_basic}" | |
| self.ignore_paths = ignore_paths | |
| async def __call__(self, scope, receive, send): | |
| if scope.get("type") != "http": | |
| return await self.app(scope, receive, send) | |
| _path = scope.get("path") | |
| if _path in self.ignore_paths: | |
| return await self.app(scope, receive, send) | |
| _headers = dict(scope.get("headers", {})) | |
| _authorization_header = _headers.get(b"authorization", b"").decode("utf-8").strip() | |
| if _authorization_header in (self.basic, self.bearer): | |
| return await self.app(scope, receive, send) | |
| # Only, chrome shows id/pw prompt to user (just for the dev experience) | |
| _user_agent = _headers.get(b"user-agent", b"").decode("utf-8").strip() | |
| await send( | |
| { | |
| "type": "http.response.start", | |
| "status": 401, | |
| "headers": [ | |
| [b"content-type", b"text/html; charset=UTF-8"], | |
| *([ | |
| [b"www-authenticate", b"basic"], # id/pw prompt. | |
| ] if "Chrome" in _user_agent else []), | |
| ], | |
| } | |
| ) | |
| await send({"type": "http.response.body", "body": "Error 401 - Unauthorized".encode("utf8")}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment