Files
element-call/src/auth/useRegisterPasswordlessUser.ts

61 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-07-13 16:02:17 +01:00
/*
Copyright 2022-2024 New Vector Ltd.
2022-07-13 16:02:17 +01:00
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
2022-07-13 16:02:17 +01:00
*/
import { useCallback } from "react";
import { secureRandomString } from "matrix-js-sdk/src/randomstring";
2022-07-13 16:02:17 +01:00
import { useClient } from "../ClientContext";
import { useInteractiveRegistration } from "../auth/useInteractiveRegistration";
import { generateRandomName } from "../auth/generateRandomName";
import { useRecaptcha } from "../auth/useRecaptcha";
import { widget } from "../widget";
2022-07-13 16:02:17 +01:00
interface UseRegisterPasswordlessUserType {
privacyPolicyUrl?: string;
2022-07-14 13:11:47 +01:00
registerPasswordlessUser: (displayName: string) => Promise<void>;
recaptchaId?: string;
2022-07-13 16:02:17 +01:00
}
export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType {
const { setClient } = useClient();
const { privacyPolicyUrl, recaptchaKey, register } =
2022-07-13 16:02:17 +01:00
useInteractiveRegistration();
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
const registerPasswordlessUser = useCallback(
async (displayName: string) => {
if (!setClient) {
throw new Error("No client context");
}
if (widget) {
throw new Error(
"Registration was skipped: We should never try to register password-less user in embedded mode.",
);
}
2022-07-13 16:02:17 +01:00
try {
const recaptchaResponse = await execute();
const userName = generateRandomName();
const [client, session] = await register(
userName,
secureRandomString(16),
2022-07-13 16:02:17 +01:00
displayName,
recaptchaResponse,
2023-10-11 10:42:04 -04:00
true,
2022-07-13 16:02:17 +01:00
);
setClient({ client, session });
2022-07-13 16:02:17 +01:00
} catch (e) {
reset();
throw e;
}
},
2023-10-11 10:42:04 -04:00
[execute, reset, register, setClient],
2022-07-13 16:02:17 +01:00
);
return { privacyPolicyUrl, registerPasswordlessUser, recaptchaId };
}