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

Commit 3930f1a

Browse files
Kerryrichvdh
andauthored
OIDC: extract success/failure handlers from token login function (#11154)
* extract success/failure handlers from token login function * typo * use for no homeserver error dialog too * i18n * tidy * Update src/Lifecycle.ts Co-authored-by: Richard van der Hoff <[email protected]> * move try again responsibility --------- Co-authored-by: Richard van der Hoff <[email protected]>
1 parent f62fe26 commit 3930f1a

File tree

3 files changed

+53
-31
lines changed

3 files changed

+53
-31
lines changed

src/Lifecycle.ts

Lines changed: 50 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ See the License for the specific language governing permissions and
1717
limitations under the License.
1818
*/
1919

20+
import { ReactNode } from "react";
2021
import { createClient } from "matrix-js-sdk/src/matrix";
2122
import { InvalidStoreError } from "matrix-js-sdk/src/errors";
2223
import { MatrixClient } from "matrix-js-sdk/src/client";
@@ -204,55 +205,74 @@ export function attemptTokenLogin(
204205
const identityServer = localStorage.getItem(SSO_ID_SERVER_URL_KEY) ?? undefined;
205206
if (!homeserver) {
206207
logger.warn("Cannot log in with token: can't determine HS URL to use");
207-
Modal.createDialog(ErrorDialog, {
208-
title: _t("We couldn't log you in"),
209-
description: _t(
208+
onFailedDelegatedAuthLogin(
209+
_t(
210210
"We asked the browser to remember which homeserver you use to let you sign in, " +
211211
"but unfortunately your browser has forgotten it. Go to the sign in page and try again.",
212212
),
213-
button: _t("Try again"),
214-
});
213+
);
215214
return Promise.resolve(false);
216215
}
217216

218217
return sendLoginRequest(homeserver, identityServer, "m.login.token", {
219218
token: queryParams.loginToken as string,
220219
initial_device_display_name: defaultDeviceDisplayName,
221220
})
222-
.then(function (creds) {
221+
.then(async function (creds) {
223222
logger.log("Logged in with token");
224-
return clearStorage().then(async (): Promise<boolean> => {
225-
await persistCredentials(creds);
226-
// remember that we just logged in
227-
sessionStorage.setItem("mx_fresh_login", String(true));
228-
return true;
229-
});
223+
await onSuccessfulDelegatedAuthLogin(creds);
224+
return true;
230225
})
231-
.catch((err) => {
232-
Modal.createDialog(ErrorDialog, {
233-
title: _t("We couldn't log you in"),
234-
description: messageForLoginError(err, {
226+
.catch((error) => {
227+
const tryAgainCallback: TryAgainFunction = () => {
228+
const cli = createClient({
229+
baseUrl: homeserver,
230+
idBaseUrl: identityServer,
231+
});
232+
const idpId = localStorage.getItem(SSO_IDP_ID_KEY) || undefined;
233+
PlatformPeg.get()?.startSingleSignOn(cli, "sso", fragmentAfterLogin, idpId, SSOAction.LOGIN);
234+
};
235+
onFailedDelegatedAuthLogin(
236+
messageForLoginError(error, {
235237
hsUrl: homeserver,
236238
hsName: homeserver,
237239
}),
238-
button: _t("Try again"),
239-
onFinished: (tryAgain) => {
240-
if (tryAgain) {
241-
const cli = createClient({
242-
baseUrl: homeserver,
243-
idBaseUrl: identityServer,
244-
});
245-
const idpId = localStorage.getItem(SSO_IDP_ID_KEY) || undefined;
246-
PlatformPeg.get()?.startSingleSignOn(cli, "sso", fragmentAfterLogin, idpId, SSOAction.LOGIN);
247-
}
248-
},
249-
});
250-
logger.error("Failed to log in with login token:");
251-
logger.error(err);
240+
tryAgainCallback,
241+
);
242+
logger.error("Failed to log in with login token:", error);
252243
return false;
253244
});
254245
}
255246

247+
/**
248+
* Called after a successful token login or OIDC authorization.
249+
* Clear storage then save new credentials in storage
250+
* @param credentials as returned from login
251+
*/
252+
async function onSuccessfulDelegatedAuthLogin(credentials: IMatrixClientCreds): Promise<void> {
253+
await clearStorage();
254+
await persistCredentials(credentials);
255+
256+
// remember that we just logged in
257+
sessionStorage.setItem("mx_fresh_login", String(true));
258+
}
259+
260+
type TryAgainFunction = () => void;
261+
/**
262+
* Display a friendly error to the user when token login or OIDC authorization fails
263+
* @param description error description
264+
* @param tryAgain OPTIONAL function to call on try again button from error dialog
265+
*/
266+
async function onFailedDelegatedAuthLogin(description: string | ReactNode, tryAgain?: TryAgainFunction): Promise<void> {
267+
Modal.createDialog(ErrorDialog, {
268+
title: _t("We couldn't log you in"),
269+
description,
270+
button: _t("Try again"),
271+
// if we have a tryAgain callback, call it the primary 'try again' button was clicked in the dialog
272+
onFinished: tryAgain ? (shouldTryAgain?: boolean) => shouldTryAgain && tryAgain() : undefined,
273+
});
274+
}
275+
256276
export function handleInvalidStoreError(e: InvalidStoreError): Promise<void> | void {
257277
if (e.reason === InvalidStoreError.TOGGLED_LAZY_LOADING) {
258278
return Promise.resolve()

src/components/structures/MatrixChat.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,8 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
330330
this.tokenLogin = true;
331331

332332
// Create and start the client
333+
// accesses the new credentials just set in storage during attemptTokenLogin
334+
// and sets logged in state
333335
await Lifecycle.restoreFromLocalStorage({
334336
ignoreGuest: true,
335337
});

src/i18n/strings/en_EN.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,8 @@
101101
"Failed to transfer call": "Failed to transfer call",
102102
"Permission Required": "Permission Required",
103103
"You do not have permission to start a conference call in this room": "You do not have permission to start a conference call in this room",
104-
"We couldn't log you in": "We couldn't log you in",
105104
"We asked the browser to remember which homeserver you use to let you sign in, but unfortunately your browser has forgotten it. Go to the sign in page and try again.": "We asked the browser to remember which homeserver you use to let you sign in, but unfortunately your browser has forgotten it. Go to the sign in page and try again.",
105+
"We couldn't log you in": "We couldn't log you in",
106106
"Try again": "Try again",
107107
"User is not logged in": "User is not logged in",
108108
"Database unexpectedly closed": "Database unexpectedly closed",

0 commit comments

Comments
 (0)