Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Factor out common login code #2307

Merged
merged 2 commits into from
Dec 5, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 6 additions & 15 deletions src/Lifecycle.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import Modal from './Modal';
import sdk from './index';
import ActiveWidgetStore from './stores/ActiveWidgetStore';
import PlatformPeg from "./PlatformPeg";
import {sendLoginRequest} from "./Login";

/**
* Called at startup, to attempt to build a logged-in Matrix session. It tries
Expand Down Expand Up @@ -129,27 +130,17 @@ export function attemptTokenLogin(queryParams, defaultDeviceDisplayName) {
return Promise.resolve(false);
}

// create a temporary MatrixClient to do the login
const client = Matrix.createClient({
baseUrl: queryParams.homeserver,
});

return client.login(
return sendLoginRequest(
queryParams.homeserver,
queryParams.identityServer,
"m.login.token", {
token: queryParams.loginToken,
initial_device_display_name: defaultDeviceDisplayName,
},
).then(function(data) {
).then(function(creds) {
console.log("Logged in with token");
return _clearStorage().then(() => {
_persistCredentialsToLocalStorage({
userId: data.user_id,
deviceId: data.device_id,
accessToken: data.access_token,
homeserverUrl: queryParams.homeserver,
identityServerUrl: queryParams.identityServer,
guest: false,
});
_persistCredentialsToLocalStorage(creds);
return true;
});
}).catch((err) => {
Expand Down
99 changes: 36 additions & 63 deletions src/Login.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand All @@ -17,7 +18,6 @@ limitations under the License.

import Matrix from "matrix-js-sdk";

import Promise from 'bluebird';
import url from 'url';

export default class Login {
Expand Down Expand Up @@ -141,83 +141,27 @@ export default class Login {
};
Object.assign(loginParams, legacyParams);

const client = this._createTemporaryClient();

const tryFallbackHs = (originalError) => {
const fbClient = Matrix.createClient({
baseUrl: self._fallbackHsUrl,
idBaseUrl: this._isUrl,
});

return fbClient.login('m.login.password', loginParams).then(function(data) {
return Promise.resolve({
homeserverUrl: self._fallbackHsUrl,
identityServerUrl: self._isUrl,
userId: data.user_id,
deviceId: data.device_id,
accessToken: data.access_token,
});
}).catch((fallback_error) => {
return sendLoginRequest(
self._fallbackHsUrl, this._isUrl, 'm.login.password', loginParams,
).catch((fallback_error) => {
console.log("fallback HS login failed", fallback_error);
// throw the original error
throw originalError;
});
};
const tryLowercaseUsername = (originalError) => {
const loginParamsLowercase = Object.assign({}, loginParams, {
user: username.toLowerCase(),
identifier: {
user: username.toLowerCase(),
},
});
return client.login('m.login.password', loginParamsLowercase).then(function(data) {
return Promise.resolve({
homeserverUrl: self._hsUrl,
identityServerUrl: self._isUrl,
userId: data.user_id,
deviceId: data.device_id,
accessToken: data.access_token,
});
}).catch((fallback_error) => {
console.log("Lowercase username login failed", fallback_error);
// throw the original error
throw originalError;
});
};

let originalLoginError = null;
return client.login('m.login.password', loginParams).then(function(data) {
return Promise.resolve({
homeserverUrl: self._hsUrl,
identityServerUrl: self._isUrl,
userId: data.user_id,
deviceId: data.device_id,
accessToken: data.access_token,
});
}).catch((error) => {
return sendLoginRequest(
self._hsUrl, self._isUrl, 'm.login.password', loginParams,
).catch((error) => {
originalLoginError = error;
if (error.httpStatus === 403) {
if (self._fallbackHsUrl) {
return tryFallbackHs(originalLoginError);
}
}
throw originalLoginError;
}).catch((error) => {
// We apparently squash case at login serverside these days:
// https://github.com/matrix-org/synapse/blob/1189be43a2479f5adf034613e8d10e3f4f452eb9/synapse/handlers/auth.py#L475
// so this wasn't needed after all. Keeping the code around in case the
// the situation changes...

/*
if (
error.httpStatus === 403 &&
loginParams.identifier.type === 'm.id.user' &&
username.search(/[A-Z]/) > -1
) {
return tryLowercaseUsername(originalLoginError);
}
*/
throw originalLoginError;
}).catch((error) => {
console.log("Login failed", error);
throw error;
Expand All @@ -239,3 +183,32 @@ export default class Login {
return client.getSsoLoginUrl(url.format(parsedUrl), loginType);
}
}


/**
* Send a login request to the given server, and format the response
* as a MatrixClientCreds
*
* @param {string} hs the base url of the Homeserver used to log in.
* @param {string} is the default identity server
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume URL?

It might also be good to have these be named hsUrl and isUrl for self-documentation reasons.

* @param {string} loginType the type of login to do
* @param {object} loginParams the parameters for the login
*
* @returns {MatrixClientCreds}
*/
export async function sendLoginRequest(hs, is, loginType, loginParams) {
const client = Matrix.createClient({
baseUrl: hs,
idBaseUrl: is,
});

const data = await client.login(loginType, loginParams);

return {
homeserverUrl: hs,
identityServerUrl: is,
userId: data.user_id,
deviceId: data.device_id,
accessToken: data.access_token,
};
}