MQTT embedded broker has to set its own password. (#15929)

This commit is contained in:
Jason Hu 2018-08-13 02:26:06 -07:00 committed by Paulus Schoutsen
parent 6aee535d7c
commit 45f12dd3c7
3 changed files with 82 additions and 25 deletions

View file

@ -27,27 +27,29 @@ HBMQTT_CONFIG_SCHEMA = vol.Any(None, vol.Schema({
})
}, extra=vol.ALLOW_EXTRA))
_LOGGER = logging.getLogger(__name__)
@asyncio.coroutine
def async_start(hass, server_config):
def async_start(hass, password, server_config):
"""Initialize MQTT Server.
This method is a coroutine.
"""
from hbmqtt.broker import Broker, BrokerException
passwd = tempfile.NamedTemporaryFile()
try:
passwd = tempfile.NamedTemporaryFile()
if server_config is None:
server_config, client_config = generate_config(hass, passwd)
server_config, client_config = generate_config(
hass, passwd, password)
else:
client_config = None
broker = Broker(server_config, hass.loop)
yield from broker.start()
except BrokerException:
logging.getLogger(__name__).exception("Error initializing MQTT server")
_LOGGER.exception("Error initializing MQTT server")
return False, None
finally:
passwd.close()
@ -63,9 +65,10 @@ def async_start(hass, server_config):
return True, client_config
def generate_config(hass, passwd):
def generate_config(hass, passwd, password):
"""Generate a configuration based on current Home Assistant instance."""
from homeassistant.components.mqtt import PROTOCOL_311
from . import PROTOCOL_311
config = {
'listeners': {
'default': {
@ -79,29 +82,26 @@ def generate_config(hass, passwd):
},
},
'auth': {
'allow-anonymous': hass.config.api.api_password is None
'allow-anonymous': password is None
},
'plugins': ['auth_anonymous'],
}
if hass.config.api.api_password:
if password:
username = 'homeassistant'
password = hass.config.api.api_password
# Encrypt with what hbmqtt uses to verify
from passlib.apps import custom_app_context
passwd.write(
'homeassistant:{}\n'.format(
custom_app_context.encrypt(
hass.config.api.api_password)).encode('utf-8'))
custom_app_context.encrypt(password)).encode('utf-8'))
passwd.flush()
config['auth']['password-file'] = passwd.name
config['plugins'].append('auth_file')
else:
username = None
password = None
client_config = ('localhost', 1883, username, password, None, PROTOCOL_311)