setup.tsx 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { enableTwoFactor, setupTwoFactor } from "@ente/accounts/api/user";
  2. import { t } from "i18next";
  3. import { useEffect, useState } from "react";
  4. import VerifyTwoFactor, {
  5. VerifyTwoFactorCallback,
  6. } from "@ente/accounts/components/two-factor/VerifyForm";
  7. import { TwoFactorSetup } from "@ente/accounts/components/two-factor/setup";
  8. import { TwoFactorSecret } from "@ente/accounts/types/user";
  9. import { APP_HOMES } from "@ente/shared/apps/constants";
  10. import { PageProps } from "@ente/shared/apps/types";
  11. import { VerticallyCentered } from "@ente/shared/components/Container";
  12. import LinkButton from "@ente/shared/components/LinkButton";
  13. import { encryptWithRecoveryKey } from "@ente/shared/crypto/helpers";
  14. import { logError } from "@ente/shared/sentry";
  15. import { LS_KEYS, getData, setData } from "@ente/shared/storage/localStorage";
  16. import { Box, CardContent, Typography } from "@mui/material";
  17. import Card from "@mui/material/Card";
  18. export enum SetupMode {
  19. QR_CODE,
  20. MANUAL_CODE,
  21. }
  22. export default function SetupTwoFactor({ router, appName }: PageProps) {
  23. const [twoFactorSecret, setTwoFactorSecret] =
  24. useState<TwoFactorSecret>(null);
  25. useEffect(() => {
  26. if (twoFactorSecret) {
  27. return;
  28. }
  29. const main = async () => {
  30. try {
  31. const twoFactorSecret = await setupTwoFactor();
  32. setTwoFactorSecret(twoFactorSecret);
  33. } catch (e) {
  34. logError(e, "failed to get two factor setup code");
  35. }
  36. };
  37. main();
  38. }, []);
  39. const onSubmit: VerifyTwoFactorCallback = async (
  40. otp: string,
  41. markSuccessful,
  42. ) => {
  43. const recoveryEncryptedTwoFactorSecret = await encryptWithRecoveryKey(
  44. twoFactorSecret.secretCode,
  45. );
  46. await enableTwoFactor(otp, recoveryEncryptedTwoFactorSecret);
  47. await markSuccessful();
  48. setData(LS_KEYS.USER, {
  49. ...getData(LS_KEYS.USER),
  50. isTwoFactorEnabled: true,
  51. });
  52. router.push(APP_HOMES.get(appName));
  53. };
  54. return (
  55. <VerticallyCentered>
  56. <Card>
  57. <CardContent>
  58. <VerticallyCentered sx={{ p: 3 }}>
  59. <Box mb={4}>
  60. <Typography variant="h2">
  61. {t("TWO_FACTOR")}
  62. </Typography>
  63. </Box>
  64. <TwoFactorSetup twoFactorSecret={twoFactorSecret} />
  65. <VerifyTwoFactor
  66. onSubmit={onSubmit}
  67. buttonText={t("ENABLE")}
  68. />
  69. <LinkButton sx={{ mt: 2 }} onClick={router.back}>
  70. {t("GO_BACK")}
  71. </LinkButton>
  72. </VerticallyCentered>
  73. </CardContent>
  74. </Card>
  75. </VerticallyCentered>
  76. );
  77. }