AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

two-factor-setup-modal.tsx 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import { Form } from '@inertiajs/react';
  2. import { REGEXP_ONLY_DIGITS } from 'input-otp';
  3. import { Check, Copy, ScanLine } from 'lucide-react';
  4. import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
  5. import AlertError from '@/components/alert-error';
  6. import InputError from '@/components/input-error';
  7. import { Button } from '@/components/ui/button';
  8. import {
  9. Dialog,
  10. DialogContent,
  11. DialogDescription,
  12. DialogHeader,
  13. DialogTitle,
  14. } from '@/components/ui/dialog';
  15. import {
  16. InputOTP,
  17. InputOTPGroup,
  18. InputOTPSlot,
  19. } from '@/components/ui/input-otp';
  20. import { Spinner } from '@/components/ui/spinner';
  21. import { useAppearance } from '@/hooks/use-appearance';
  22. import { useClipboard } from '@/hooks/use-clipboard';
  23. import { OTP_MAX_LENGTH } from '@/hooks/use-two-factor-auth';
  24. import { confirm } from '@/routes/two-factor';
  25. function GridScanIcon() {
  26. return (
  27. <div className="mb-3 rounded-full border border-border bg-card p-0.5 shadow-sm">
  28. <div className="relative overflow-hidden rounded-full border border-border bg-muted p-2.5">
  29. <div className="absolute inset-0 grid grid-cols-5 opacity-50">
  30. {Array.from({ length: 5 }, (_, i) => (
  31. <div
  32. key={`col-${i + 1}`}
  33. className="border-r border-border last:border-r-0"
  34. />
  35. ))}
  36. </div>
  37. <div className="absolute inset-0 grid grid-rows-5 opacity-50">
  38. {Array.from({ length: 5 }, (_, i) => (
  39. <div
  40. key={`row-${i + 1}`}
  41. className="border-b border-border last:border-b-0"
  42. />
  43. ))}
  44. </div>
  45. <ScanLine className="relative z-20 size-6 text-foreground" />
  46. </div>
  47. </div>
  48. );
  49. }
  50. function TwoFactorSetupStep({
  51. qrCodeSvg,
  52. manualSetupKey,
  53. buttonText,
  54. onNextStep,
  55. errors,
  56. }: {
  57. qrCodeSvg: string | null;
  58. manualSetupKey: string | null;
  59. buttonText: string;
  60. onNextStep: () => void;
  61. errors: string[];
  62. }) {
  63. const { resolvedAppearance } = useAppearance();
  64. const [copiedText, copy] = useClipboard();
  65. const IconComponent = copiedText === manualSetupKey ? Check : Copy;
  66. return (
  67. <>
  68. {errors?.length ? (
  69. <AlertError errors={errors} />
  70. ) : (
  71. <>
  72. <div className="mx-auto flex max-w-md overflow-hidden">
  73. <div className="mx-auto aspect-square w-64 rounded-lg border border-border">
  74. <div className="z-10 flex h-full w-full items-center justify-center p-5">
  75. {qrCodeSvg ? (
  76. <div
  77. className="aspect-square w-full rounded-lg bg-white p-2 [&_svg]:size-full"
  78. dangerouslySetInnerHTML={{
  79. __html: qrCodeSvg,
  80. }}
  81. style={{
  82. filter:
  83. resolvedAppearance === 'dark'
  84. ? 'invert(1) brightness(1.5)'
  85. : undefined,
  86. }}
  87. />
  88. ) : (
  89. <Spinner />
  90. )}
  91. </div>
  92. </div>
  93. </div>
  94. <div className="flex w-full space-x-5">
  95. <Button className="w-full" onClick={onNextStep}>
  96. {buttonText}
  97. </Button>
  98. </div>
  99. <div className="relative flex w-full items-center justify-center">
  100. <div className="absolute inset-0 top-1/2 h-px w-full bg-border" />
  101. <span className="relative bg-card px-2 py-1">
  102. or, enter the code manually
  103. </span>
  104. </div>
  105. <div className="flex w-full space-x-2">
  106. <div className="flex w-full items-stretch overflow-hidden rounded-xl border border-border">
  107. {!manualSetupKey ? (
  108. <div className="flex h-full w-full items-center justify-center bg-muted p-3">
  109. <Spinner />
  110. </div>
  111. ) : (
  112. <>
  113. <input
  114. type="text"
  115. readOnly
  116. value={manualSetupKey}
  117. className="h-full w-full bg-background p-3 text-foreground outline-none"
  118. />
  119. <button
  120. onClick={() => copy(manualSetupKey)}
  121. className="border-l border-border px-3 hover:bg-muted"
  122. >
  123. <IconComponent className="w-4" />
  124. </button>
  125. </>
  126. )}
  127. </div>
  128. </div>
  129. </>
  130. )}
  131. </>
  132. );
  133. }
  134. function TwoFactorVerificationStep({
  135. onClose,
  136. onBack,
  137. }: {
  138. onClose: () => void;
  139. onBack: () => void;
  140. }) {
  141. const [code, setCode] = useState<string>('');
  142. const pinInputContainerRef = useRef<HTMLDivElement>(null);
  143. useEffect(() => {
  144. setTimeout(() => {
  145. pinInputContainerRef.current?.querySelector('input')?.focus();
  146. }, 0);
  147. }, []);
  148. return (
  149. <Form
  150. {...confirm.form()}
  151. onSuccess={() => onClose()}
  152. resetOnError
  153. resetOnSuccess
  154. >
  155. {({
  156. processing,
  157. errors,
  158. }: {
  159. processing: boolean;
  160. errors?: { confirmTwoFactorAuthentication?: { code?: string } };
  161. }) => (
  162. <>
  163. <div
  164. ref={pinInputContainerRef}
  165. className="relative w-full space-y-3"
  166. >
  167. <div className="flex w-full flex-col items-center space-y-3 py-2">
  168. <InputOTP
  169. id="otp"
  170. name="code"
  171. maxLength={OTP_MAX_LENGTH}
  172. onChange={setCode}
  173. disabled={processing}
  174. pattern={REGEXP_ONLY_DIGITS}
  175. autoFocus
  176. >
  177. <InputOTPGroup>
  178. {Array.from(
  179. { length: OTP_MAX_LENGTH },
  180. (_, index) => (
  181. <InputOTPSlot
  182. key={index}
  183. index={index}
  184. />
  185. ),
  186. )}
  187. </InputOTPGroup>
  188. </InputOTP>
  189. <InputError
  190. message={
  191. errors?.confirmTwoFactorAuthentication?.code
  192. }
  193. />
  194. </div>
  195. <div className="flex w-full space-x-5">
  196. <Button
  197. type="button"
  198. variant="outline"
  199. className="flex-1"
  200. onClick={onBack}
  201. disabled={processing}
  202. >
  203. Back
  204. </Button>
  205. <Button
  206. type="submit"
  207. className="flex-1"
  208. disabled={
  209. processing || code.length < OTP_MAX_LENGTH
  210. }
  211. >
  212. Confirm
  213. </Button>
  214. </div>
  215. </div>
  216. </>
  217. )}
  218. </Form>
  219. );
  220. }
  221. type Props = {
  222. isOpen: boolean;
  223. onClose: () => void;
  224. requiresConfirmation: boolean;
  225. twoFactorEnabled: boolean;
  226. qrCodeSvg: string | null;
  227. manualSetupKey: string | null;
  228. clearSetupData: () => void;
  229. fetchSetupData: () => Promise<void>;
  230. errors: string[];
  231. };
  232. export default function TwoFactorSetupModal({
  233. isOpen,
  234. onClose,
  235. requiresConfirmation,
  236. twoFactorEnabled,
  237. qrCodeSvg,
  238. manualSetupKey,
  239. clearSetupData,
  240. fetchSetupData,
  241. errors,
  242. }: Props) {
  243. const [showVerificationStep, setShowVerificationStep] =
  244. useState<boolean>(false);
  245. const modalConfig = useMemo<{
  246. title: string;
  247. description: string;
  248. buttonText: string;
  249. }>(() => {
  250. if (twoFactorEnabled) {
  251. return {
  252. title: 'Two-factor authentication enabled',
  253. description:
  254. 'Two-factor authentication is now enabled. Scan the QR code or enter the setup key in your authenticator app.',
  255. buttonText: 'Close',
  256. };
  257. }
  258. if (showVerificationStep) {
  259. return {
  260. title: 'Verify authentication code',
  261. description:
  262. 'Enter the 6-digit code from your authenticator app',
  263. buttonText: 'Continue',
  264. };
  265. }
  266. return {
  267. title: 'Enable two-factor authentication',
  268. description:
  269. 'To finish enabling two-factor authentication, scan the QR code or enter the setup key in your authenticator app',
  270. buttonText: 'Continue',
  271. };
  272. }, [twoFactorEnabled, showVerificationStep]);
  273. const resetModalState = useCallback(() => {
  274. if (twoFactorEnabled) {
  275. clearSetupData();
  276. }
  277. setShowVerificationStep(false);
  278. }, [clearSetupData, twoFactorEnabled]);
  279. const handleClose = useCallback(() => {
  280. resetModalState();
  281. onClose();
  282. }, [onClose, resetModalState]);
  283. const handleModalNextStep = useCallback(() => {
  284. if (requiresConfirmation) {
  285. setShowVerificationStep(true);
  286. return;
  287. }
  288. clearSetupData();
  289. handleClose();
  290. }, [requiresConfirmation, clearSetupData, handleClose]);
  291. const fetchSetupDataRef = useRef(fetchSetupData);
  292. useEffect(() => {
  293. fetchSetupDataRef.current = fetchSetupData;
  294. }, [fetchSetupData]);
  295. useEffect(() => {
  296. if (isOpen && !qrCodeSvg) {
  297. void fetchSetupDataRef.current();
  298. }
  299. }, [isOpen, qrCodeSvg]);
  300. return (
  301. <Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>
  302. <DialogContent className="sm:max-w-md">
  303. <DialogHeader className="flex items-center justify-center">
  304. <GridScanIcon />
  305. <DialogTitle>{modalConfig.title}</DialogTitle>
  306. <DialogDescription className="text-center">
  307. {modalConfig.description}
  308. </DialogDescription>
  309. </DialogHeader>
  310. <div className="flex flex-col items-center space-y-5">
  311. {showVerificationStep ? (
  312. <TwoFactorVerificationStep
  313. onClose={handleClose}
  314. onBack={() => setShowVerificationStep(false)}
  315. />
  316. ) : (
  317. <TwoFactorSetupStep
  318. qrCodeSvg={qrCodeSvg}
  319. manualSetupKey={manualSetupKey}
  320. buttonText={modalConfig.buttonText}
  321. onNextStep={handleModalNextStep}
  322. errors={errors}
  323. />
  324. )}
  325. </div>
  326. </DialogContent>
  327. </Dialog>
  328. );
  329. }