From a4fec975a665b6ebcb07fd7451e381f49f3c497a Mon Sep 17 00:00:00 2001 From: Matheus Date: Fri, 10 Oct 2025 23:22:52 -0300 Subject: fix:Não colocar credenciais no código MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (-_-) --- compose.yaml | 3 +++ mqtt_client/main.py | 11 ++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/compose.yaml b/compose.yaml index f56c1d2..4e4def4 100644 --- a/compose.yaml +++ b/compose.yaml @@ -18,6 +18,9 @@ services: source: ./mosquitto-config/ target: /mosquitto/config/ mqtt-client: + environment: + MQTT_CLIENT_USER: ${MQTT_CLIENT_USER} + MQTT_CLIENT_PASSWORD: ${MQTT_CLIENT_PASSWORD} build: context: ./mqtt_client/ network_mode: "service:mosquitto" diff --git a/mqtt_client/main.py b/mqtt_client/main.py index 78cdca6..80b4da9 100644 --- a/mqtt_client/main.py +++ b/mqtt_client/main.py @@ -2,6 +2,7 @@ import paho.mqtt.client as mqtt from paho.mqtt.enums import MQTTProtocolVersion import json from time import sleep +import os def on_connect(client, userdata, flags, reason_code, properties): print(f"Conectado: {reason_code}") @@ -16,10 +17,18 @@ def on_message(client, userdata, msg): print(f"Unit: {payload["unit"]}") print(f"Timestamp: {payload["timestamp"]}") +try: + user_name = os.environ["MQTT_CLIENT_USER"] + user_pass = os.environ["MQTT_CLIENT_PASSWORD"] +except KeyError: + print("credentials not supplied in environment variables. Going unauthenticated...") + user_name = None + user_pass = None + mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, protocol=MQTTProtocolVersion.MQTTv5) mqttc.on_connect = on_connect mqttc.on_message = on_message -mqttc.username_pw_set('tester', 'rosebud') +mqttc.username_pw_set(user_name, user_pass) connected = False -- cgit v1.2.3