diff --git a/src/Lifecycle.js b/src/Lifecycle.js index 60da4feb06..f57e1be3c2 100644 --- a/src/Lifecycle.js +++ b/src/Lifecycle.js @@ -88,9 +88,7 @@ export function loadSession(opts) { return q(); } - if (MatrixClientPeg.get() && MatrixClientPeg.get().credentials) { - console.log("Using existing credentials"); - setLoggedIn(MatrixClientPeg.getCredentials()); + if (_restoreFromLocalStorage()) { return q(); } @@ -120,6 +118,39 @@ function _registerAsGuest(hsUrl, isUrl) { }); } +// returns true if a session is found in localstorage +function _restoreFromLocalStorage() { + if (!localStorage) { + return false; + } + const hs_url = localStorage.getItem("mx_hs_url"); + const is_url = localStorage.getItem("mx_is_url") || 'https://matrix.org'; + const access_token = localStorage.getItem("mx_access_token"); + const user_id = localStorage.getItem("mx_user_id"); + + let is_guest; + if (localStorage.getItem("mx_is_guest") !== null) { + is_guest = localStorage.getItem("mx_is_guest") === "true"; + } else { + // legacy key name + is_guest = localStorage.getItem("matrix-is-guest") === "true"; + } + + if (access_token && user_id && hs_url) { + console.log("Restoring session for %s", user_id); + setLoggedIn({ + userId: user_id, + accessToken: access_token, + homeserverUrl: hs_url, + identityServerUrl: is_url, + guest: is_guest, + }); + return true; + } else { + console.log("No previous session found."); + return false; + } +} /** * Transitions to a logged-in state using the given credentials diff --git a/src/MatrixClientPeg.js b/src/MatrixClientPeg.js index e6d0e7f3f7..1c3af7a38f 100644 --- a/src/MatrixClientPeg.js +++ b/src/MatrixClientPeg.js @@ -135,31 +135,6 @@ class MatrixClientPeg { }; } - tryRestore() { - if (localStorage) { - const hs_url = localStorage.getItem("mx_hs_url"); - const is_url = localStorage.getItem("mx_is_url") || 'https://matrix.org'; - const access_token = localStorage.getItem("mx_access_token"); - const user_id = localStorage.getItem("mx_user_id"); - - let is_guest; - if (localStorage.getItem("mx_is_guest") !== null) { - is_guest = localStorage.getItem("mx_is_guest") === "true"; - } else { - // legacy key name - is_guest = localStorage.getItem("matrix-is-guest") === "true"; - } - - if (access_token && user_id && hs_url) { - console.log("Restoring session for %s", user_id); - this._createClient(hs_url, is_url, user_id, access_token); - this.matrixClient.setGuest(is_guest); - } else { - console.log("Session not found."); - } - } - } - _createClient(hs_url, is_url, user_id, access_token, isGuest) { var opts = { baseUrl: hs_url, @@ -186,6 +161,5 @@ class MatrixClientPeg { if (!global.mxMatrixClientPeg) { global.mxMatrixClientPeg = new MatrixClientPeg(); - global.mxMatrixClientPeg.tryRestore(); } module.exports = global.mxMatrixClientPeg;