1 import { Button, Heading, Hint, Input, OtpInput, Text } from "@medusajs/ui"
2 import type { AuthTypes } from "@medusajs/types"
3 import { useState } from "react"
4 import { useTranslation } from "react-i18next"
5 import { Link } from "react-router-dom"
6 import { useVerifyAuthMfaChallenge } from "../../../hooks/api"
7
8 const getDefaultMethod = (
9 methods: AuthTypes.AuthMfaChallengeMethod[]
10 ): AuthTypes.AuthMfaChallengeMethod => {
11 if (methods.includes("totp")) {
12 return "totp"
13 }
14
15 return methods[0] ?? "totp"
16 }
17
18 type MfaChallengeFormProps = {
19 challenge: AuthTypes.AuthMfaChallengeDTO
20 onSuccess: (token: string) => void | Promise<void>
21 onBack?: () => void
22 }
23
24 export const MfaChallengeForm = ({
25 challenge,
26 onSuccess,
27 onBack,
28 }: MfaChallengeFormProps) => {
29 const { t } = useTranslation()
30 const [method, setMethod] = useState<AuthTypes.AuthMfaChallengeMethod>(
31 getDefaultMethod(challenge.methods)
32 )
33 const [code, setCode] = useState("")
34 const [error, setError] = useState<string | null>(null)
35 const [verifiedToken, setVerifiedToken] = useState<string | null>(null)
36 const [isCompleting, setIsCompleting] = useState(false)
37 const { mutateAsync, isPending } = useVerifyAuthMfaChallenge()
38
39 const isRecoveryCode = method === "recovery_code"
40 const canUseRecoveryCode = challenge.methods.includes("recovery_code")
41 const canVerify = isRecoveryCode ? !!code.trim() : code.length === 6
42 const isLoading = isPending || isCompleting
43
44 const handleVerify = async (nextCode = code) => {
45 const verificationCode = nextCode.trim()
46
47 if (
48 !verifiedToken &&
49 (!verificationCode || (!isRecoveryCode && verificationCode.length !== 6))
50 ) {
51 return
52 }
53
54 setError(null)
55
56 let token = verifiedToken
57
58 if (!token) {
59 try {
60 token = await mutateAsync({
61 id: challenge.id,
62 method,
63 code: verificationCode,
64 })
65 setVerifiedToken(token)
66 } catch (e) {
67 setError(e instanceof Error ? e.message : t("login.mfa.verifyError"))
68 setCode("")
69 return
70 }
71 }
72
73 setIsCompleting(true)
74
75 try {
76 await onSuccess(token)
77 } catch (e) {
78 setError(e instanceof Error ? e.message : t("login.mfa.completeError"))
79 } finally {
80 setIsCompleting(false)
81 }
82 }
83
84 const handleOtpChange = (value: string) => {
85 setCode(value)
86 }
87
88 const handleMethodChange = (nextMethod: AuthTypes.AuthMfaChallengeMethod) => {
89 setMethod(nextMethod)
90 setCode("")
91 setError(null)
92 setVerifiedToken(null)
93 }
94
95 return (
96 <div className="flex w-full flex-col items-center">
97 <div className="mb-6 flex flex-col items-center">
98 <Heading>{t("login.mfa.title")}</Heading>
99 <Text size="small" className="text-ui-fg-subtle text-center">
100 {isRecoveryCode
101 ? t("login.mfa.recoveryDescription")
102 : t("login.mfa.description")}
103 </Text>
104 </div>
105 <div className="flex w-full flex-col gap-y-4">
106 {isRecoveryCode ? (
107 <Input
108 autoComplete="one-time-code"
109 className="bg-ui-bg-field-component"
110 placeholder={t("login.mfa.recoveryCodePlaceholder")}
111 value={code}
112 onChange={(e) => setCode(e.target.value)}
113 disabled={isLoading || !!verifiedToken}
114 />
115 ) : (
116 <OtpInput
117 value={code}
118 onChange={handleOtpChange}
119 onComplete={handleVerify}
120 disabled={isLoading || !!verifiedToken}
121 autoFocus
122 />
123 )}
124 {error && (
125 <div className="text-center">
126 <Hint className="inline-flex" variant="error">
127 {error}
128 </Hint>
129 </div>
130 )}
131 <Button
132 className="w-full"
133 isLoading={isLoading}
134 disabled={!verifiedToken && !canVerify}
135 onClick={() => handleVerify()}
136 >
137 {t("login.mfa.verify")}
138 </Button>
139 {onBack && (
140 <Link
141 to="/login"
142 className="txt-small text-ui-fg-muted transition-fg hover:text-ui-fg-subtle focus-visible:text-ui-fg-subtle text-center outline-none"
143 onClick={onBack}
144 >
145 {t("login.mfa.backToLogin")}
146 </Link>
147 )}
148 </div>
149 {canUseRecoveryCode && (
150 <div className="text-ui-fg-muted txt-small mt-6 text-center">
151 {isRecoveryCode
152 ? t("login.mfa.useAuthenticatorPrompt")
153 : t("login.mfa.useRecoveryCodePrompt")}{" "}
154 <button
155 type="button"
156 className="text-ui-fg-interactive transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover font-medium outline-none"
157 onClick={() =>
158 handleMethodChange(isRecoveryCode ? "totp" : "recovery_code")
159 }
160 >
161 {isRecoveryCode
162 ? t("login.mfa.useAuthenticator")
163 : t("login.mfa.useRecoveryCode")}
164 </button>
165 </div>
166 )}
167 </div>
168 )
169 }