From 8ca9e4ccb179f86deaa1d52c9ce8a5fd666f5b12 Mon Sep 17 00:00:00 2001
From: Michael Telatynski <7t3chguy@gmail.com>
Date: Sat, 4 Apr 2020 00:22:15 +0100
Subject: [PATCH] Fix Electron SSO handling to support multiple profiles

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
---
 electron_app/src/electron-main.js       | 14 +++++++++++++-
 src/vector/platform/ElectronPlatform.js |  8 ++++++++
 2 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/electron_app/src/electron-main.js b/electron_app/src/electron-main.js
index 91258c6c..9453839f 100644
--- a/electron_app/src/electron-main.js
+++ b/electron_app/src/electron-main.js
@@ -68,7 +68,14 @@ if (argv["help"]) {
     app.exit();
 }
 
-if (argv['profile-dir']) {
+// check if we are passed a profile in the SSO callback url
+const deeplinkUrl = argv["_"].find(arg => arg.startsWith('riot://'));
+if (deeplinkUrl && deeplinkUrl.includes('riot-desktop-user-data-path')) {
+    const parsedUrl = new URL(deeplinkUrl);
+    if (parsedUrl.protocol === 'riot:') {
+        app.setPath('userData', parsedUrl.searchParams.get('riot-desktop-user-data-path'));
+    }
+} else if (argv['profile-dir']) {
     app.setPath('userData', argv['profile-dir']);
 } else if (argv['profile']) {
     app.setPath('userData', `${app.getPath('userData')}-${argv['profile']}`);
@@ -233,6 +240,11 @@ ipcMain.on('ipcCall', async function(ev, payload) {
         case 'getConfig':
             ret = vectorConfig;
             break;
+        case 'getUserDataPath':
+            if (argv['profile-dir'] || argv['profile']) {
+                ret = app.getPath('userData');
+            }
+            break;
 
         default:
             mainWindow.webContents.send('ipcReply', {
diff --git a/src/vector/platform/ElectronPlatform.js b/src/vector/platform/ElectronPlatform.js
index 6b75c1ee..09312480 100644
--- a/src/vector/platform/ElectronPlatform.js
+++ b/src/vector/platform/ElectronPlatform.js
@@ -228,6 +228,11 @@ export default class ElectronPlatform extends VectorBasePlatform {
                 description: _td("Open user settings"),
             });
         }
+
+        // we assume this happens before any SSO actions occur but do not block.
+        this._ipcCall('getUserDataPath').then(userDataPath => {
+            this.userDataPath = userDataPath;
+        });
     }
 
     async getConfig(): Promise<{}> {
@@ -424,6 +429,9 @@ export default class ElectronPlatform extends VectorBasePlatform {
     getSSOCallbackUrl(hsUrl: string, isUrl: string): URL {
         const url = super.getSSOCallbackUrl(hsUrl, isUrl);
         url.protocol = "riot";
+        if (this.userDataPath) {
+            url.searchParams.set("riot-desktop-user-data-path", this.userDataPath);
+        }
         return url;
     }