New incremental auth

This commit is contained in:
Robert Long 2022-02-15 12:46:58 -08:00
parent 63229ce2d7
commit 0f6b8f9bb1
8 changed files with 249 additions and 81 deletions

View file

@ -41,7 +41,8 @@
"react-router": "6", "react-router": "6",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-use-clipboard": "^1.0.7", "react-use-clipboard": "^1.0.7",
"react-use-measure": "^2.1.1" "react-use-measure": "^2.1.1",
"unique-names-generator": "^4.6.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.16.5", "@babel/core": "^7.16.5",

View file

@ -145,16 +145,21 @@ export function ClientProvider({ children }) {
[client] [client]
); );
const setClient = useCallback((client, session) => { const setClient = useCallback(
if (client) { (newClient, session) => {
if (client && client !== newClient) {
client.stopClient();
}
if (newClient) {
localStorage.setItem("matrix-auth-store", JSON.stringify(session)); localStorage.setItem("matrix-auth-store", JSON.stringify(session));
setState({ setState({
client, client: newClient,
loading: false, loading: false,
isAuthenticated: true, isAuthenticated: true,
isPasswordlessUser: !!session.passwordlessUser, isPasswordlessUser: !!session.passwordlessUser,
userName: client.getUserIdLocalpart(), userName: newClient.getUserIdLocalpart(),
}); });
} else { } else {
localStorage.removeItem("matrix-auth-store"); localStorage.removeItem("matrix-auth-store");
@ -167,7 +172,9 @@ export function ClientProvider({ children }) {
userName: null, userName: null,
}); });
} }
}, []); },
[client]
);
const logout = useCallback(() => { const logout = useCallback(() => {
localStorage.removeItem("matrix-auth-store"); localStorage.removeItem("matrix-auth-store");
@ -226,6 +233,10 @@ export function ClientProvider({ children }) {
] ]
); );
useEffect(() => {
window.matrixclient = client;
}, [client]);
if (error) { if (error) {
return <ErrorView error={error} />; return <ErrorView error={error} />;
} }

View file

@ -31,13 +31,7 @@ import { usePageTitle } from "../usePageTitle";
export function RegisterPage() { export function RegisterPage() {
usePageTitle("Register"); usePageTitle("Register");
const { const { loading, isAuthenticated, isPasswordlessUser, client } = useClient();
loading,
client,
changePassword,
isAuthenticated,
isPasswordlessUser,
} = useClient();
const confirmPasswordRef = useRef(); const confirmPasswordRef = useRef();
const history = useHistory(); const history = useHistory();
const location = useLocation(); const location = useLocation();
@ -64,11 +58,31 @@ export function RegisterPage() {
async function submit() { async function submit() {
setRegistering(true); setRegistering(true);
if (isPasswordlessUser) { let roomIds;
await changePassword(password);
} else { if (client && isPasswordlessUser) {
const groupCalls = client.groupCallEventHandler.groupCalls.values();
roomIds = Array.from(groupCalls).map(
(groupCall) => groupCall.room.roomId
);
}
const recaptchaResponse = await execute(); const recaptchaResponse = await execute();
await register(userName, password, recaptchaResponse); const newClient = await register(
userName,
password,
userName,
recaptchaResponse
);
if (roomIds) {
for (const roomId of roomIds) {
try {
await newClient.joinRoom(roomId);
} catch (error) {
console.warn(`Couldn't join room ${roomId}`, error);
}
}
} }
} }
@ -86,15 +100,7 @@ export function RegisterPage() {
reset(); reset();
}); });
}, },
[ [register, location, history, isPasswordlessUser, reset, execute, client]
register,
changePassword,
location,
history,
isPasswordlessUser,
reset,
execute,
]
); );
useEffect(() => { useEffect(() => {
@ -110,10 +116,10 @@ export function RegisterPage() {
}, [password, passwordConfirmation]); }, [password, passwordConfirmation]);
useEffect(() => { useEffect(() => {
if (!loading && isAuthenticated && !isPasswordlessUser) { if (!loading && isAuthenticated && !isPasswordlessUser && !registering) {
history.push("/"); history.push("/");
} }
}, [history, isAuthenticated, isPasswordlessUser]); }, [history, isAuthenticated, isPasswordlessUser, registering]);
if (loading) { if (loading) {
return <LoadingView />; return <LoadingView />;
@ -137,12 +143,6 @@ export function RegisterPage() {
autoCapitalize="none" autoCapitalize="none"
prefix="@" prefix="@"
suffix={`:${defaultHomeserverHost}`} suffix={`:${defaultHomeserverHost}`}
value={
isAuthenticated && isPasswordlessUser
? client.getUserIdLocalpart()
: undefined
}
disabled={isAuthenticated && isPasswordlessUser}
/> />
</FieldRow> </FieldRow>
<FieldRow> <FieldRow>
@ -168,7 +168,6 @@ export function RegisterPage() {
ref={confirmPasswordRef} ref={confirmPasswordRef}
/> />
</FieldRow> </FieldRow>
{!isPasswordlessUser && (
<Caption> <Caption>
This site is protected by ReCAPTCHA and the Google{" "} This site is protected by ReCAPTCHA and the Google{" "}
<Link href="https://www.google.com/policies/privacy/"> <Link href="https://www.google.com/policies/privacy/">
@ -180,10 +179,9 @@ export function RegisterPage() {
</Link>{" "} </Link>{" "}
apply. apply.
<br /> <br />
By clicking "Log in", you agree to our{" "} By clicking "Register", you agree to our{" "}
<Link href={privacyPolicyUrl}>Terms and conditions</Link> <Link href={privacyPolicyUrl}>Terms and conditions</Link>
</Caption> </Caption>
)}
{error && ( {error && (
<FieldRow> <FieldRow>
<ErrorMessage>{error.message}</ErrorMessage> <ErrorMessage>{error.message}</ErrorMessage>

View file

@ -0,0 +1,137 @@
import {
uniqueNamesGenerator,
adjectives,
colors,
animals,
} from "unique-names-generator";
const elements = [
"hydrogen",
"helium",
"lithium",
"beryllium",
"boron",
"carbon",
"nitrogen",
"oxygen",
"fluorine",
"neon",
"sodium",
"magnesium",
"aluminum",
"silicon",
"phosphorus",
"sulfur",
"chlorine",
"argon",
"potassium",
"calcium",
"scandium",
"titanium",
"vanadium",
"chromium",
"manganese",
"iron",
"cobalt",
"nickel",
"copper",
"zinc",
"gallium",
"germanium",
"arsenic",
"selenium",
"bromine",
"krypton",
"rubidium",
"strontium",
"yttrium",
"zirconium",
"niobium",
"molybdenum",
"technetium",
"ruthenium",
"rhodium",
"palladium",
"silver",
"cadmium",
"indium",
"tin",
"antimony",
"tellurium",
"iodine",
"xenon",
"cesium",
"barium",
"lanthanum",
"cerium",
"praseodymium",
"neodymium",
"promethium",
"samarium",
"europium",
"gadolinium",
"terbium",
"dysprosium",
"holmium",
"erbium",
"thulium",
"ytterbium",
"lutetium",
"hafnium",
"tantalum",
"wolfram",
"rhenium",
"osmium",
"iridium",
"platinum",
"gold",
"mercury",
"thallium",
"lead",
"bismuth",
"polonium",
"astatine",
"radon",
"francium",
"radium",
"actinium",
"thorium",
"protactinium",
"uranium",
"neptunium",
"plutonium",
"americium",
"curium",
"berkelium",
"californium",
"einsteinium",
"fermium",
"mendelevium",
"nobelium",
"lawrencium",
"rutherfordium",
"dubnium",
"seaborgium",
"bohrium",
"hassium",
"meitnerium",
"darmstadtium",
"roentgenium",
"copernicium",
"nihonium",
"flerovium",
"moscovium",
"livermorium",
"tennessine",
"oganesson",
];
export function generateRandomName(config) {
return uniqueNamesGenerator({
dictionaries: [colors, adjectives, animals, elements],
style: "lowerCase",
length: 3,
separator: "-",
...config,
});
}

View file

@ -25,7 +25,13 @@ export function useInteractiveRegistration() {
}, []); }, []);
const register = useCallback( const register = useCallback(
async (username, password, recaptchaResponse, passwordlessUser) => { async (
username,
password,
displayName,
recaptchaResponse,
passwordlessUser
) => {
const interactiveAuth = new InteractiveAuth({ const interactiveAuth = new InteractiveAuth({
matrixClient: authClientRef.current, matrixClient: authClientRef.current,
busyChanged(loading) { busyChanged(loading) {
@ -66,7 +72,7 @@ export function useInteractiveRegistration() {
deviceId: device_id, deviceId: device_id,
}); });
await client.setDisplayName(username); await client.setDisplayName(displayName);
const session = { user_id, device_id, access_token, passwordlessUser }; const session = { user_id, device_id, access_token, passwordlessUser };

View file

@ -14,6 +14,7 @@ import { Body, Caption, Link, Headline } from "../typography/Typography";
import { Form } from "../form/Form"; import { Form } from "../form/Form";
import styles from "./UnauthenticatedView.module.css"; import styles from "./UnauthenticatedView.module.css";
import commonStyles from "./common.module.css"; import commonStyles from "./common.module.css";
import { generateRandomName } from "../auth/generateRandomName";
export function UnauthenticatedView() { export function UnauthenticatedView() {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -26,19 +27,20 @@ export function UnauthenticatedView() {
e.preventDefault(); e.preventDefault();
const data = new FormData(e.target); const data = new FormData(e.target);
const roomName = data.get("callName"); const roomName = data.get("callName");
const userName = data.get("userName"); const displayName = data.get("displayName");
async function submit() { async function submit() {
setError(undefined); setError(undefined);
setLoading(true); setLoading(true);
const recaptchaResponse = await execute(); const recaptchaResponse = await execute();
const userName = generateRandomName();
const client = await register( const client = await register(
userName, userName,
randomString(16), randomString(16),
displayName,
recaptchaResponse, recaptchaResponse,
true true
); );
const roomIdOrAlias = await createRoom(client, roomName); const roomIdOrAlias = await createRoom(client, roomName);
if (roomIdOrAlias) { if (roomIdOrAlias) {
@ -100,10 +102,10 @@ export function UnauthenticatedView() {
</FieldRow> </FieldRow>
<FieldRow> <FieldRow>
<InputField <InputField
id="userName" id="displayName"
name="userName" name="displayName"
label="Username" label="Display Name"
placeholder="Username" placeholder="Display Name"
type="text" type="text"
required required
autoComplete="off" autoComplete="off"

View file

@ -10,6 +10,7 @@ import { randomString } from "matrix-js-sdk/src/randomstring";
import { useInteractiveRegistration } from "../auth/useInteractiveRegistration"; import { useInteractiveRegistration } from "../auth/useInteractiveRegistration";
import { Form } from "../form/Form"; import { Form } from "../form/Form";
import { UserMenuContainer } from "../UserMenuContainer"; import { UserMenuContainer } from "../UserMenuContainer";
import { generateRandomName } from "../auth/generateRandomName";
export function RoomAuthView() { export function RoomAuthView() {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -21,13 +22,20 @@ export function RoomAuthView() {
(e) => { (e) => {
e.preventDefault(); e.preventDefault();
const data = new FormData(e.target); const data = new FormData(e.target);
const userName = data.get("userName"); const displayName = data.get("displayName");
async function submit() { async function submit() {
setError(undefined); setError(undefined);
setLoading(true); setLoading(true);
const recaptchaResponse = await execute(); const recaptchaResponse = await execute();
await register(userName, randomString(16), recaptchaResponse, true); const userName = generateRandomName();
await register(
userName,
randomString(16),
displayName,
recaptchaResponse,
true
);
} }
submit().catch((error) => { submit().catch((error) => {
@ -58,10 +66,10 @@ export function RoomAuthView() {
<Form className={styles.form} onSubmit={onSubmit}> <Form className={styles.form} onSubmit={onSubmit}>
<FieldRow> <FieldRow>
<InputField <InputField
id="userName" id="displayName"
name="userName" name="displayName"
label="Pick a user name" label="Display Name"
placeholder="Pick a user name" placeholder="Display Name"
type="text" type="text"
required required
autoComplete="off" autoComplete="off"

View file

@ -12039,6 +12039,11 @@ unique-filename@^1.1.1:
dependencies: dependencies:
unique-slug "^2.0.0" unique-slug "^2.0.0"
unique-names-generator@^4.6.0:
version "4.6.0"
resolved "https://registry.yarnpkg.com/unique-names-generator/-/unique-names-generator-4.6.0.tgz#852c1db8149815d6cf665a601820fe80ec2fbc37"
integrity sha512-m0fke1emBeT96UYn2psPQYwljooDWRTKt9oUZ5vlt88ZFMBGxqwPyLHXwCfkbgdm8jzioCp7oIpo6KdM+fnUlQ==
unique-slug@^2.0.0: unique-slug@^2.0.0:
version "2.0.2" version "2.0.2"
resolved "https://registry.yarnpkg.com/unique-slug/-/unique-slug-2.0.2.tgz#baabce91083fc64e945b0f3ad613e264f7cd4e6c" resolved "https://registry.yarnpkg.com/unique-slug/-/unique-slug-2.0.2.tgz#baabce91083fc64e945b0f3ad613e264f7cd4e6c"