From 2100f54451e1fd0750752832250d2bc860f3797e Mon Sep 17 00:00:00 2001 From: Drew Short Date: Tue, 7 Jan 2020 13:31:58 -0600 Subject: [PATCH] Improved bot login flow with optional password auth --- bot/bot.js | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/bot/bot.js b/bot/bot.js index 2c2eb6b..0baf1e3 100644 --- a/bot/bot.js +++ b/bot/bot.js @@ -17,7 +17,6 @@ class Bot { logger.info("Creating Matrix Client") this.client = sdk.createClient({ baseUrl: this.config.baseUrl, - accessToken: this.config.accessToken, userId: this.config.userId }); @@ -60,8 +59,39 @@ class Bot { async connect() { // logger.info("Initializing Crypto"); // await bot.client.initCrypto(); - logger.info("Starting Matrix SDK Client"); - await this.client.startClient(); + let botClient = this.client; + let botConfig = this.config; + + let startServerConnection = async () => { + logger.info("Starting Matrix SDK Client"); + await this.client.startClient(); + } + + let connectWithPassword = (err, data) => { + if (err === null) { + logger.info("Successfully authenticated with password %o", data); + startServerConnection(); + } else { + logger.error("Failed to authenticate with password %o", err); + } + } + + let connectWithToken = (err, data) => { + if (err === null) { + logger.info("Successfully authenticated with access token %o", data); + startServerConnection(); + } else { + logger.error("Failed to authenticate with access token %o", err); + if (typeof botConfig.userPassword !== 'undefined') { + botClient.loginWithPassword(botConfig.userId, botConfig.userPassword, connectWithPassword); + } else { + logger.error("No fallback password provided!"); + } + } + } + + logger.info("Authenticating With Server"); + botClient.loginWithToken(this.config.accessToken, connectWithToken); } sendStatusStartup() {