From 4913557ef1f97ece277c2452069677d77cabedf8 Mon Sep 17 00:00:00 2001 From: David Svenson Date: Mon, 8 Apr 2024 16:29:09 +0200 Subject: [PATCH] Expose QR code helper explicitly. This simplifies making use of it without having access to a client instance. --- bankid/__init__.py | 2 ++ bankid/baseclient.py | 30 +++++++++++++++++------------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/bankid/__init__.py b/bankid/__init__.py index 7f628bc..f640091 100644 --- a/bankid/__init__.py +++ b/bankid/__init__.py @@ -23,12 +23,14 @@ from bankid.certutils import create_bankid_test_server_cert_and_key from bankid.syncclient import BankIDClient from bankid.asyncclient import BankIDAsyncClient +from bankid.baseclient import generate_qr_code_content __all__ = [ "BankIDClient", "BankIDAsyncClient", "exceptions", "create_bankid_test_server_cert_and_key", + "generate_qr_code_content", "__version__", "version", ] diff --git a/bankid/baseclient.py b/bankid/baseclient.py index 0d146f6..f23f88c 100644 --- a/bankid/baseclient.py +++ b/bankid/baseclient.py @@ -42,19 +42,8 @@ def __init__( self.client = None @staticmethod - def generate_qr_code_content(qr_start_token: str, start_t: [float, datetime], qr_start_secret: str): - """Given QR start token, time.time() or UTC datetime when initiated authentication call was made and the - QR start secret, calculate the current QR code content to display. - """ - if isinstance(start_t, datetime): - start_t = start_t.timestamp() - elapsed_seconds_since_call = int(floor(time.time() - start_t)) - qr_auth_code = hmac.new( - qr_start_secret.encode(), - msg=str(elapsed_seconds_since_call).encode(), - digestmod=hashlib.sha256, - ).hexdigest() - return f"bankid.{qr_start_token}.{elapsed_seconds_since_call}.{qr_auth_code}" + def generate_qr_code_content(qr_start_token: str, start_t: [float, datetime], qr_start_secret: str) -> str: + return generate_qr_code_content(qr_start_token, start_t, qr_start_secret) @staticmethod def _encode_user_data(user_data): @@ -83,3 +72,18 @@ def _create_payload( if user_visible_data_format and user_visible_data_format == "simpleMarkdownV1": data["userVisibleDataFormat"] = "simpleMarkdownV1" return data + + +def generate_qr_code_content(qr_start_token: str, start_t: [float, datetime], qr_start_secret: str) -> str: + """Given QR start token, time.time() or UTC datetime when initiated authentication call was made and the + QR start secret, calculate the current QR code content to display. + """ + if isinstance(start_t, datetime): + start_t = start_t.timestamp() + elapsed_seconds_since_call = int(floor(time.time() - start_t)) + qr_auth_code = hmac.new( + qr_start_secret.encode(), + msg=str(elapsed_seconds_since_call).encode(), + digestmod=hashlib.sha256, + ).hexdigest() + return f"bankid.{qr_start_token}.{elapsed_seconds_since_call}.{qr_auth_code}"