-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathotp.tsx
More file actions
211 lines (190 loc) · 5.82 KB
/
otp.tsx
File metadata and controls
211 lines (190 loc) · 5.82 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import {
FormEventHandler,
useCallback,
useEffect,
useMemo,
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 { useSlashID } from "../../../main";
import { Props } from "./authenticating.types";
import {
AuthenticatingMessageOptions,
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 {
AuthenticatingSubtitle,
BackButton,
DelayedPrompt,
Prompt,
} from "./authenticating.components";
import { TIME_MS } from "../types";
const DELAY_BEFORE_RESEND = TIME_MS.second * 30;
const FactorIcon = ({ factor }: { factor: Factor }) => {
if (isFactorOTPEmail(factor)) {
return <EmailIcon />;
}
if (isFactorOTPSms(factor)) {
return <SmsIcon />;
}
return <Loader />;
};
type FormState = "initial" | "input" | "submitting" | "retrying";
function mapFormStateToMessageState(
formState: FormState
): AuthenticatingMessageOptions["state"] {
switch (formState) {
case "submitting":
return "submitting";
case "retrying":
return "retrying";
default:
return undefined;
}
}
/**
* 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, subscribe, unsubscribe } = useSlashID();
const { values, registerField, registerSubmit, setError, clearError } =
useForm();
const [formState, setFormState] = useState<FormState>("initial");
const submitInputRef = useRef<HTMLInputElement>(null);
const { factor, handle } = flowState.context.config;
const { title, message, tokens } = useMemo(() => {
return getAuthenticatingMessage(factor, handle, {
state: mapFormStateToMessageState(formState),
});
}, [factor, formState, handle]);
useEffect(() => {
const onOtpCodeSent = () => setFormState("input");
const onOtpIncorrectCodeSubmitted = () => {
setError("otp", {
message: text["authenticating.otpInput.submit.error"],
});
values["otp"] = "";
setFormState("input");
};
subscribe("otpCodeSent", onOtpCodeSent);
subscribe("otpIncorrectCodeSubmitted", onOtpIncorrectCodeSubmitted);
return () => {
unsubscribe("otpCodeSent", onOtpCodeSent);
unsubscribe("otpIncorrectCodeSubmitted", onOtpIncorrectCodeSubmitted);
};
}, [formState, setError, sid, subscribe, text, unsubscribe, values]);
const handleSubmit: FormEventHandler<HTMLFormElement> = useCallback(
(e) => {
e.preventDefault();
setFormState("submitting");
sid?.publish("otpCodeSubmitted", values["otp"]);
},
[sid, 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("retrying");
};
useEffect(() => {
if (isValidOTPCode(values["otp"])) {
// Automatically submit the form when the OTP code is valid
submitInputRef.current?.click();
}
}, [values]);
return (
<>
<BackButton onCancel={() => flowState.cancel()} />
<Text
as="h1"
className="sid-form-authenticating-title sid-form-authenticating-title-otp"
t={title}
variant={{ size: "2xl-title", weight: "bold" }}
/>
<AuthenticatingSubtitle />
<Text
t={message}
variant={{ color: "contrast", weight: "semibold" }}
tokens={tokens}
/>
{formState === "initial" && <FactorIcon factor={factor} />}
{formState === "input" && (
<form
onSubmit={registerSubmit(handleSubmit)}
className={styles.otpForm}
>
<div
className={styles.formInner}
data-testid="sid-form-authenticating-otp"
>
<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" ? <Loader /> : null}
{formState === "retrying" ? <FactorIcon factor={factor} /> : null}
{["input", "initial"].includes(formState) && (
// fallback to prevent layout shift
<Delayed
delayMs={DELAY_BEFORE_RESEND}
fallback={({ secondsRemaining }) => (
<div className={styles.wrapper}>
<DelayedPrompt
prompt="authenticating.retryPrompt"
cta="authenticating.retry"
secondsRemaining={secondsRemaining}
/>
</div>
)}
>
<div className={styles.wrapper}>
<Prompt
prompt="authenticating.retryPrompt"
cta="authenticating.retry"
onClick={handleRetry}
/>
</div>
</Delayed>
)}
</>
);
};