π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
add two factor verify page
Abhinav1dd48caddbd4
diff --git a/apps/photos/src/pages/two-factor/verify/index.tsx b/apps/photos/src/pages/two-factor/verify/index.tsxindex 0821069af8..1684d804e2 100644--- a/apps/photos/src/pages/two-factor/verify/index.tsx+++ b/apps/photos/src/pages/two-factor/verify/index.tsx@@ -1,85 +1,17 @@-import VerifyTwoFactor, {- VerifyTwoFactorCallback,-} from 'components/TwoFactor/VerifyForm';-import router from 'next/router';-import { useEffect, useState } from 'react';-import { logoutUser, verifyTwoFactor } from 'services/userService';-import { PAGES } from 'constants/pages';-import { User } from 'types/user';-import { setData, LS_KEYS, getData } from 'utils/storage/localStorage';-import { t } from 'i18next';+import TwoFactorVerifyPage from '@ente/accounts/pages/two-factor/verify';+import { useRouter } from 'next/router';+import { AppContext } from 'pages/_app';+import { useContext } from 'react';+import { APPS } from '@ente/shared/apps/constants';-import LinkButton from 'components/pages/gallery/LinkButton';-import FormPaper from 'components/Form/FormPaper';-import FormTitle from 'components/Form/FormPaper/Title';-import FormPaperFooter from 'components/Form/FormPaper/Footer';-import { VerticallyCentered } from 'components/Container';-import InMemoryStore, { MS_KEYS } from 'services/InMemoryStore';-import { ApiError } from 'utils/error';-import { HttpStatusCode } from 'axios';--export default function Home() {- const [sessionID, setSessionID] = useState('');-- useEffect(() => {- const main = async () => {- router.prefetch(PAGES.CREDENTIALS);- const user: User = getData(LS_KEYS.USER);- if (!user?.email || !user.twoFactorSessionID) {- router.push(PAGES.ROOT);- } else if (- !user.isTwoFactorEnabled &&- (user.encryptedToken || user.token)- ) {- router.push(PAGES.CREDENTIALS);- } else {- setSessionID(user.twoFactorSessionID);- }- };- main();- }, []);-- const onSubmit: VerifyTwoFactorCallback = async (otp) => {- try {- const resp = await verifyTwoFactor(otp, sessionID);- const { keyAttributes, encryptedToken, token, id } = resp;- setData(LS_KEYS.USER, {- ...getData(LS_KEYS.USER),- token,- encryptedToken,- id,- });- setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes);- const redirectURL = InMemoryStore.get(MS_KEYS.REDIRECT_URL);- InMemoryStore.delete(MS_KEYS.REDIRECT_URL);- router.push(redirectURL ?? PAGES.CREDENTIALS);- } catch (e) {- if (- e instanceof ApiError &&- e.httpStatusCode === HttpStatusCode.NotFound- ) {- logoutUser();- } else {- throw e;- }- }- };+export default function TwoFactorVerify() {+ const appContext = useContext(AppContext);+ const router = useRouter();return (- <VerticallyCentered>- <FormPaper sx={{ maxWidth: '410px' }}>- <FormTitle>{t('TWO_FACTOR')}</FormTitle>- <VerifyTwoFactor onSubmit={onSubmit} buttonText={t('VERIFY')} />-- <FormPaperFooter style={{ justifyContent: 'space-between' }}>- <LinkButton- onClick={() => router.push(PAGES.TWO_FACTOR_RECOVER)}>- {t('LOST_DEVICE')}- </LinkButton>- <LinkButton onClick={logoutUser}>- {t('CHANGE_EMAIL')}- </LinkButton>- </FormPaperFooter>- </FormPaper>- </VerticallyCentered>+ <TwoFactorVerifyPage+ appContext={appContext}+ router={router}+ appName={APPS.PHOTOS}+ />);}diff --git a/packages/accounts/api/user.ts b/packages/accounts/api/user.tsindex 9c066204ff..c0f263163e 100644--- a/packages/accounts/api/user.ts+++ b/packages/accounts/api/user.ts@@ -3,7 +3,10 @@ import { getEndpoint } from '@ente/shared/network/api';import { getToken } from '@ente/shared/storage/localStorage/helpers';-import { KeyAttributes } from '@ente/shared/user/types';+import {+ KeyAttributes,+ UserVerificationResponse,+} from '@ente/shared/user/types';import { ApiError } from '@ente/shared/error';import { HttpStatusCode } from 'axios';@@ -51,3 +54,15 @@ export const _logout = async () => {throw e;}};++export const verifyTwoFactor = async (code: string, sessionID: string) => {+ const resp = await HTTPService.post(+ `${ENDPOINT}/users/two-factor/verify`,+ {+ code,+ sessionID,+ },+ null+ );+ return resp.data as UserVerificationResponse;+};diff --git a/packages/accounts/components/TwoFactor/InvalidInputMessage.tsx b/packages/accounts/components/TwoFactor/InvalidInputMessage.tsxnew file mode 100644index 0000000000..aebd08b945--- /dev/null+++ b/packages/accounts/components/TwoFactor/InvalidInputMessage.tsx@@ -0,0 +1,18 @@+import React from 'react';+import { TypographyProps, Typography } from '@mui/material';+import { FC } from 'react';++const InvalidInputMessage: FC<TypographyProps> = (props) => {+ return (+ <Typography+ variant="mini"+ sx={{+ color: (theme) => theme.colors.danger.A700,+ }}+ {...props}>+ {props.children}+ </Typography>+ );+};++export default InvalidInputMessage;diff --git a/packages/accounts/components/TwoFactor/VerifyForm.tsx b/packages/accounts/components/TwoFactor/VerifyForm.tsxnew file mode 100644index 0000000000..db48f95040--- /dev/null+++ b/packages/accounts/components/TwoFactor/VerifyForm.tsx@@ -0,0 +1,108 @@+import { Formik, FormikHelpers } from 'formik';+import { useRef, useState } from 'react';+import OtpInput from 'react-otp-input';+import { t } from 'i18next';++import SubmitButton from '@ente/shared/components/SubmitButton';+import {+ VerticallyCentered,+ CenteredFlex,+} from '@ente/shared/components/Container';+import { Box, Typography } from '@mui/material';+import InvalidInputMessage from '@ente/accounts/components/TwoFactor/InvalidInputMessage';+import { sleep } from '@ente/shared/utils';++interface formValues {+ otp: string;+}+interface Props {+ onSubmit: VerifyTwoFactorCallback;+ buttonText: string;+}++export type VerifyTwoFactorCallback = (+ otp: string,+ markSuccessful: () => Promise<void>+) => Promise<void>;++export default function VerifyTwoFactor(props: Props) {+ const [waiting, setWaiting] = useState(false);+ const otpInputRef = useRef(null);+ const [success, setSuccess] = useState(false);++ const markSuccessful = async () => {+ setWaiting(false);+ setSuccess(true);+ await sleep(1000);+ };++ const submitForm = async (+ { otp }: formValues,+ { setFieldError, resetForm }: FormikHelpers<formValues>+ ) => {+ try {+ setWaiting(true);+ await props.onSubmit(otp, markSuccessful);+ } catch (e) {+ resetForm();+ for (let i = 0; i < 6; i++) {+ otpInputRef.current?.focusPrevInput();+ }+ setFieldError('otp', `${t('UNKNOWN_ERROR')} ${e.message}`);+ }+ setWaiting(false);+ };++ const onChange =+ (callback: Function, triggerSubmit: Function) => (otp: string) => {+ callback(otp);+ if (otp.length === 6) {+ triggerSubmit(otp);+ }+ };+ return (+ <Formik<formValues>+ initialValues={{ otp: '' }}+ validateOnChange={false}+ validateOnBlur={false}+ onSubmit={submitForm}>+ {({ values, errors, handleChange, handleSubmit, submitForm }) => (+ <VerticallyCentered>+ <form noValidate onSubmit={handleSubmit}>+ <Typography mb={2} variant="small" color="text.muted">+ {t('ENTER_TWO_FACTOR_OTP')}+ </Typography>+ <Box my={2}>+ <OtpInput+ ref={otpInputRef}+ shouldAutoFocus+ value={values.otp}+ onChange={onChange(+ handleChange('otp'),+ submitForm+ )}+ numInputs={6}+ separator={'-'}+ isInputNum+ className={'otp-input'}+ />+ {errors.otp && (+ <CenteredFlex sx={{ mt: 1 }}>+ <InvalidInputMessage>+ {t('INCORRECT_CODE')}+ </InvalidInputMessage>+ </CenteredFlex>+ )}+ </Box>+ <SubmitButton+ buttonText={props.buttonText}+ loading={waiting}+ success={success}+ disabled={values.otp.length < 6}+ />+ </form>+ </VerticallyCentered>+ )}+ </Formik>+ );+}diff --git a/packages/accounts/pages/two-factor/verify/index.tsx b/packages/accounts/pages/two-factor/verify/index.tsxnew file mode 100644index 0000000000..57512fe349--- /dev/null+++ b/packages/accounts/pages/two-factor/verify/index.tsx@@ -0,0 +1,89 @@+import VerifyTwoFactor, {+ VerifyTwoFactorCallback,+} from '@ente/accounts/components/TwoFactor/VerifyForm';+import { useEffect, useState } from 'react';+import { logoutUser } from '@ente/accounts/services/user';+import { verifyTwoFactor } from '@ente/accounts/api/user';+import { PAGES } from '@ente/accounts/constants/pages';+import { User } from '@ente/shared/user/types';+import { setData, LS_KEYS, getData } from '@ente/shared/storage/localStorage';+import { t } from 'i18next';++import LinkButton from '@ente/shared/components/LinkButton';+import FormPaper from '@ente/shared/components/Form/FormPaper';+import FormTitle from '@ente/shared/components/Form/FormPaper/Title';+import FormPaperFooter from '@ente/shared/components/Form/FormPaper/Footer';+import { VerticallyCentered } from '@ente/shared/components/Container';+import InMemoryStore, { MS_KEYS } from '@ente/shared/storage/InMemoryStore';+import { ApiError } from '@ente/shared/error';+import { HttpStatusCode } from 'axios';+import { PageProps } from '@ente/shared/apps/types';++export default function TwoFactorVerify({ router }: PageProps) {+ const [sessionID, setSessionID] = useState('');++ useEffect(() => {+ const main = async () => {+ router.prefetch(PAGES.CREDENTIALS);+ const user: User = getData(LS_KEYS.USER);+ if (!user?.email || !user.twoFactorSessionID) {+ router.push(PAGES.ROOT);+ } else if (+ !user.isTwoFactorEnabled &&+ (user.encryptedToken || user.token)+ ) {+ router.push(PAGES.CREDENTIALS);+ } else {+ setSessionID(user.twoFactorSessionID);+ }+ };+ main();+ }, []);++ const onSubmit: VerifyTwoFactorCallback = async (otp) => {+ try {+ const resp = await verifyTwoFactor(otp, sessionID);+ const { keyAttributes, encryptedToken, token, id } = resp;+ setData(LS_KEYS.USER, {+ ...getData(LS_KEYS.USER),+ token,+ encryptedToken,+ id,+ });+ setData(LS_KEYS.KEY_ATTRIBUTES, keyAttributes);+ const redirectURL = InMemoryStore.get(MS_KEYS.REDIRECT_URL);+ InMemoryStore.delete(MS_KEYS.REDIRECT_URL);+ router.push(redirectURL ?? PAGES.CREDENTIALS);+ } catch (e) {+ if (+ e instanceof ApiError &&+ e.httpStatusCode === HttpStatusCode.NotFound+ ) {+ logoutUser(router);+ } else {+ throw e;+ }+ }+ };++ const logoutHandler = () => logoutUser(router);++ return (+ <VerticallyCentered>+ <FormPaper sx={{ maxWidth: '410px' }}>+ <FormTitle>{t('TWO_FACTOR')}</FormTitle>+ <VerifyTwoFactor onSubmit={onSubmit} buttonText={t('VERIFY')} />++ <FormPaperFooter style={{ justifyContent: 'space-between' }}>+ <LinkButton+ onClick={() => router.push(PAGES.TWO_FACTOR_RECOVER)}>+ {t('LOST_DEVICE')}+ </LinkButton>+ <LinkButton onClick={logoutHandler}>+ {t('CHANGE_EMAIL')}+ </LinkButton>+ </FormPaperFooter>+ </FormPaper>+ </VerticallyCentered>+ );+}diff --git a/packages/shared/utils/index.ts b/packages/shared/utils/index.tsnew file mode 100644index 0000000000..39e64cb5f5--- /dev/null+++ b/packages/shared/utils/index.ts@@ -0,0 +1,5 @@+export async function sleep(time: number) {+ await new Promise((resolve) => {+ setTimeout(() => resolve(null), time);+ });+}