improve auth handler speed

This commit is contained in:
Ingolf Wagner 2024-11-17 07:24:29 +07:00
parent eff7d1c887
commit 95037bb56c
No known key found for this signature in database
GPG key ID: 76BF5F1928B9618B

View file

@ -21,16 +21,12 @@ def get_current_ip_address():
# Function to generate a default username
def generate_default_username():
return "user_" + "".join(
random.choices(string.ascii_lowercase + string.digits, k=8)
)
return "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
# Function to generate a default password
def generate_default_password():
return "".join(
random.choices(string.ascii_letters + string.digits + string.punctuation, k=12)
)
return "".join(random.choices(string.ascii_letters + string.digits, k=12))
# Define the command-line arguments
@ -74,6 +70,12 @@ os.chdir(expanded_directory)
# Define a request handler with basic authentication
class AuthHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, username, passsword, *args, **kwargs):
encoded_bytes = base64.b64encode(f"{username}:{passsword}".encode("utf-8"))
# Convert bytes back to string
self.encoded_str = encoded_bytes.decode("utf-8")
super().__init__(*args, **kwargs)
def do_AUTHHEAD(self):
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="Server Access"')
@ -90,9 +92,10 @@ class AuthHandler(http.server.SimpleHTTPRequestHandler):
def check_auth(self, auth_header):
encoded_credentials = auth_header.split()[1]
decoded_credentials = base64.b64decode(encoded_credentials).decode("utf-8")
username, password = decoded_credentials.split(":")
return username == args.username and password == args.password
return encoded_credentials == self.encoded_str
# decoded_credentials = base64.b64decode(encoded_credentials).decode("utf-8")
# username, password = decoded_credentials.split(":")
# return username == args.username and password == args.password
def save_qr_code(url):
@ -111,8 +114,11 @@ def save_qr_code(url):
img.save("qrcode.png")
from functools import partial
# Set up the server with the AuthHandler and the defined port
with socketserver.TCPServer(("", args.port), AuthHandler) as httpd:
auth_handler = partial(AuthHandler, args.username, args.password)
with socketserver.TCPServer(("", args.port), auth_handler) as httpd:
print("qrcode.png is saved in the current directory.")
ip_address = get_current_ip_address()
print(