Created
August 16, 2023 06:36
-
-
Save intentionally-left-nil/39eff4f528f2b95b133b0391bf71755d to your computer and use it in GitHub Desktop.
python-cookie-cors-investigation
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
from http.server import HTTPServer, BaseHTTPRequestHandler | |
from http.cookies import SimpleCookie | |
import json | |
class Handler(BaseHTTPRequestHandler): | |
def add_cors(self): | |
host = self.headers.get('Origin', '*') | |
self.send_header('Access-Control-Allow-Origin', host) | |
self.send_header('Access-Control-Allow-Credentials', 'true') | |
self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS') | |
self.send_header("Access-Control-Allow-Headers", "X-Requested-With") | |
self.send_header("Access-Control-Allow-Headers", "Content-Type") | |
def cookie_val(self, cookies: SimpleCookie, key: str) -> int: | |
val = cookies.get(key, '0') | |
if isinstance(val, str): | |
return int(val) | |
else: | |
return int(val.value) | |
def do_OPTIONS(self): | |
print("got options") | |
self.send_response(200, "ok") | |
self.add_cors() | |
self.end_headers() | |
def do_GET(self): | |
cookies = SimpleCookie() | |
cookies_string = self.headers.get('Cookie') | |
if cookies_string: | |
cookies.load(cookies_string) | |
auth = self.cookie_val(cookies, 'Authorization') | |
demo = self.cookie_val(cookies, 'Demo') | |
print(f"{self.path} route called with auth: {auth}, demo: {demo}") | |
self.send_response(200) | |
self.send_header('Content-Type', 'application/json') | |
if self.path == '/set_cookie': | |
self.send_header("Set-Cookie", f"Authorization={auth + 1}") | |
self.send_header("Set-Cookie", f"Demo={demo + 1}") | |
self.add_cors() | |
self.end_headers() | |
data = { | |
"Authorization": auth, | |
"Demo": demo | |
} | |
if self.path == '/set_cookie': | |
data = {k: v + 1 for k, v in data.items()} | |
self.wfile.write(json.dumps(data).encode('utf-8')) | |
def run(server_class=HTTPServer, handler_class=Handler): | |
print("listening on localhost:8000") | |
server_address = ('', 8000) | |
httpd = server_class(server_address, handler_class) | |
httpd.serve_forever() | |
if __name__ == '__main__': | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment