-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathotp.tsx
More file actions
168 lines (149 loc) · 4.66 KB
/
otp.tsx
File metadata and controls
168 lines (149 loc) · 4.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import {
FormEventHandler,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { Factor } from "@slashid/slashid";
import { OtpInput, Delayed } from "@slashid/react-primitives";
import { useConfiguration } from "../../../hooks/use-configuration";
import { useForm } from "../../../hooks/use-form";
import { Props } from "./authenticating.types";
import { getAuthenticatingMessage } from "./messages";
import { OTP_CODE_LENGTH, isValidOTPCode } from "./validation";
import { ErrorMessage } from "../error-message";
import { Text } from "../../text";
import * as styles from "./authenticating.css";
import { isFactorOTPEmail, isFactorOTPSms } from "../../../domain/handles";
import { EmailIcon, SmsIcon, Loader } from "./icons";
import { BackButton, RetryPrompt } from "./authenticating.components";
import { useSlashID } from "../../../hooks/use-slash-id";
const FactorIcon = ({ factor }: { factor: Factor }) => {
if (isFactorOTPEmail(factor)) {
return <EmailIcon />;
}
if (isFactorOTPSms(factor)) {
return <SmsIcon />;
}
return <Loader />;
};
const BASE_RETRY_DELAY = 2000;
/**
* Presents the user with a form to enter an OTP code.
* Handles retries in case of submitting an incorrect OTP code.
*/
export const OTPState = ({ flowState }: Props) => {
const { text } = useConfiguration();
const { sid } = useSlashID();
const { values, registerField, registerSubmit, setError, clearError } =
useForm();
const [formState, setFormState] = useState<
"initial" | "input" | "submitting"
>("initial");
const submitInputRef = useRef<HTMLInputElement>(null);
const factor = flowState.context.config.factor;
const hasRetried = flowState.context.attempt > 1;
const { title, message } = getAuthenticatingMessage(factor, {
isSubmitting: formState === "submitting",
hasRetried,
});
const handleSubmit: FormEventHandler<HTMLFormElement> = useCallback(
(e) => {
e.preventDefault();
setFormState("submitting");
sid?.publish("otpCodeSubmitted", values["otp"]);
},
[sid, values]
);
useEffect(() => {
const handler = () => {
setError("otp", {
message: text["authenticating.otpInput.submit.error"],
});
values["otp"] = "";
};
sid?.subscribe("otpIncorrectCodeSubmitted", handler);
return () => sid?.unsubscribe("otpIncorrectCodeSubmitted", handler);
}, [setError, sid, text, values]);
const handleChange = useCallback(
(otp: string) => {
const onChange = registerField("otp", {
validator: (value) => {
if (!isValidOTPCode(value)) {
return { message: text["validationError.otp"] };
}
},
});
const event = {
target: {
value: otp,
},
};
clearError("otp");
onChange(event as never);
},
[clearError, registerField, text]
);
const handleRetry = () => {
flowState.retry();
clearError("otp");
setFormState("submitting");
};
useEffect(() => {
if (isValidOTPCode(values["otp"])) {
// Automatically submit the form when the OTP code is valid
submitInputRef.current?.click();
}
}, [values]);
useEffect(() => {
const onOtpCodeSent = () => setFormState("input");
if (formState === "initial") {
sid?.subscribe("otpCodeSent", onOtpCodeSent);
}
}, [formState, sid]);
return (
<>
<BackButton onCancel={() => flowState.cancel()} />
<Text as="h1" t={title} variant={{ size: "2xl-title", weight: "bold" }} />
<Text t={message} variant={{ color: "contrast", weight: "semibold" }} />
{formState === "initial" && <FactorIcon factor={factor} />}
{formState === "input" && (
<form
onSubmit={registerSubmit(handleSubmit)}
className={styles.otpForm}
>
<div className={styles.formInner}>
<OtpInput
shouldAutoFocus
inputType="number"
value={values["otp"] ?? ""}
onChange={handleChange}
numInputs={OTP_CODE_LENGTH}
/>
<input hidden type="submit" ref={submitInputRef} />
<ErrorMessage name="otp" />
</div>
</form>
)}
{formState === "submitting" ? (
hasRetried ? (
<EmailIcon />
) : (
<Loader />
)
) : null}
{formState === "input" && (
// fallback to prevent layout shift
<Delayed
delayMs={BASE_RETRY_DELAY * flowState.context.attempt}
fallback={<div style={{ height: 16 }} />}
>
<div className={styles.wrapper}>
<RetryPrompt onRetry={handleRetry} />
</div>
</Delayed>
)}
</>
);
};