def add_callbacks(sync): url = state.get("aws_callback") log.info("SSM callback = \"{}\"".format(url)) if not url: return log.info("Adding callbacks...") for acc in sync.get_bunq_accounts(): bunq_api.add_callback(acc["bunq_user_id"], acc["bunq_account_id"], "bunq2ynab-lambda", url)
def get_private_key(): pem_str = state.get("private_key") if pem_str: return crypto.load_privatekey(crypto.FILETYPE_PEM, pem_str) log.info("Generating new private key...") key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, key) state.set("private_key", pem.decode("utf-8")) state.set("private_key_for_api_token", config.get("api_token")) return key
def get_session_token(): check_stale_api_token() token = state.get("session_token") if token: return token if not state.get("installation_token"): get_installation_token() if not state.get("device_registered"): register_device() log.info("Requesting session token...") method = "v1/session-server" data = {"secret": config.get("api_token")} reply = post(method, data) session_token = None for row in reply: if "Token" in row: session_token = row["Token"]["token"] if not session_token: raise Exception("No token returned by session-server") state.set("session_token", session_token) return session_token
def get_installation_token(): token = state.get("installation_token") if token: return token log.info("Requesting installation token...") public_key = get_public_key() pem = crypto.dump_publickey(crypto.FILETYPE_PEM, public_key) method = "v1/installation" data = {"client_public_key": pem.decode("utf-8")} reply = post(method, data) token = None for row in reply: if "Token" in row: token = row["Token"]["token"] if not token: raise Exception("No token returned by installation") state.set("installation_token", token)
def check_stale_api_token(): for_api_token = state.get("private_key_for_api_token") if for_api_token and for_api_token != config.get("api_token"): log.warning("New API token, clearing dependent keys and tokens...") clear_state()