A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
feat: add account recovery & email confirmation
thecodrr2be88cb491bc
diff --git a/apps/web/src/common/index.js b/apps/web/src/common/index.jsindex 9180ffc89..999a02d7d 100644--- a/apps/web/src/common/index.js+++ b/apps/web/src/common/index.js@@ -15,9 +15,15 @@ import Config from "../utils/config";import { store as userstore } from "../stores/user-store";export const db = new Database(StorageInterface, EventSource);+db.host({+ API_HOST: "http://192.168.10.5:5264",+ AUTH_HOST: "http://192.168.10.5:8264",+ SSE_HOST: "http://192.168.10.5:7264",+});//db.host("http://192.168.10.5:8100");// db.host();//db.host("https://api.notesnook.com");+export const COLORS = {red: "#f44336",orange: "#FF9800",diff --git a/apps/web/src/common/reminders.js b/apps/web/src/common/reminders.jsindex baca078c6..3de4379be 100644--- a/apps/web/src/common/reminders.js+++ b/apps/web/src/common/reminders.js@@ -4,6 +4,8 @@ import { store as appStore } from "../stores/app-store";import * as Icon from "../components/icons";import dayjs from "dayjs";import { showSignUpDialog } from "../components/dialogs/signupdialog";+import { showDialog } from "../components/dialogs/dialog";+import { showToast } from "../utils/toast";export async function shouldAddBackupReminder() {const backupReminderOffset = Config.get("backupReminderOffset", 0);@@ -21,6 +23,11 @@ export async function shouldAddSignupReminder() {if (!user) return true;}+export async function shouldAddConfirmEmailReminder() {+ const user = await db.user.getUser();+ return !user?.isEmailConfirmed;+}+export const Reminders = {backup: {title: "Back up your data now!",@@ -29,9 +36,17 @@ export const Reminders = {},signup: {title: "Sign up for cross-device syncing!",- action: async () => showSignUpDialog(),+ action: () => showSignUpDialog(),icon: Icon.Login,},+ email: {+ title: "Please confirm your email",+ action: async () => {+ await db.user.sendVerificationEmail();+ showToast("success", "Confirmation email sent. Please check your inbox!");+ },+ icon: Icon.Email,+ },};export async function resetReminders() {@@ -42,4 +57,7 @@ export async function resetReminders() {if (await shouldAddSignupReminder()) {appStore.addReminder("signup", "low");}+ if (await shouldAddConfirmEmailReminder()) {+ appStore.addReminder("email", "high");+ }}diff --git a/apps/web/src/components/dialogs/forgotpassworddialog.js b/apps/web/src/components/dialogs/forgotpassworddialog.jsnew file mode 100644index 000000000..974bc78ec--- /dev/null+++ b/apps/web/src/components/dialogs/forgotpassworddialog.js@@ -0,0 +1,80 @@+import React, { useState } from "react";+import { Text, Box } from "rebass";+import Dialog, { showDialog } from "./dialog";+import { useStore } from "../../stores/user-store";+import Field from "../field";+import { db } from "../../common";+import { showToast } from "../../utils/toast";++const requiredValues = ["email"];+function ForgotPasswordDialog(props) {+ const { onClose } = props;+ const [error, setError] = useState();+ const [isLoading, setIsLoading] = useState(false);++ return (+ <Dialog+ isOpen={true}+ title={"Recover your account"}+ description={+ "Forgot your password? No worries, we can help you recover your account."+ }+ onClose={onClose}+ scrollable+ negativeButton={{ text: "Cancel", onClick: onClose }}+ positiveButton={{+ props: {+ form: "signupForm",+ type: "submit",+ },+ text: "Continue",+ disabled: isLoading,+ loading: isLoading,+ }}+ >+ <Box+ id="signupForm"+ as="form"+ onSubmit={(e) => {+ e.preventDefault();+ const data = requiredValues.reduce((prev, curr) => {+ prev[curr] = e.target[curr].value;+ return prev;+ }, {});++ setError();+ setIsLoading(true);+ db.user+ .recoverAccount(data.email)+ .then(() => {+ showToast(+ "success",+ "Recovery email sent. Please check your inbox."+ );+ onClose();+ })+ .catch((e) => setError(e.message))+ .finally(() => setIsLoading(false));+ }}+ >+ <Field+ autoFocus+ required+ id="email"+ type="email"+ label="Email"+ name="email"+ autoComplete="email"+ helpText="We will email you a 6-digit code to verify that it's you."+ />+ {error && <Text variant="error">{error}</Text>}+ </Box>+ </Dialog>+ );+}++export function showForgotPasswordDialog() {+ return showDialog((perform) => (+ <ForgotPasswordDialog onClose={() => perform()} />+ ));+}diff --git a/apps/web/src/components/icons/index.js b/apps/web/src/components/icons/index.jsindex 0b2498dfa..d60f0f1f0 100644--- a/apps/web/src/components/icons/index.js+++ b/apps/web/src/components/icons/index.js@@ -65,6 +65,7 @@ export const Trash = createIcon(Icons.mdiTrashCanOutline);export const Search = createIcon(Icons.mdiMagnify);export const Menu = createIcon(Icons.mdiMenu);export const Login = createIcon(Icons.mdiLoginVariant);+export const Email = createIcon(Icons.mdiEmailAlertOutline);export const Signup = createIcon(Icons.mdiAccountPlusOutline);export const Logout = createIcon(Icons.mdiLogoutVariant);export const FocusMode = createIcon(Icons.mdiFullscreen);diff --git a/apps/web/src/index.js b/apps/web/src/index.jsindex 0dba15840..0f6f5dda9 100644--- a/apps/web/src/index.js+++ b/apps/web/src/index.js@@ -6,11 +6,10 @@ import ReactDOM from "react-dom";//import * as Sentry from "@sentry/react";//import { Integrations } from "@sentry/tracing";import "./index.css";-import App from "./App";import * as serviceWorker from "./serviceWorker";import Modal from "react-modal";-import { MotionConfig, AnimationFeature, GesturesFeature } from "framer-motion";-import Splash from "./views/splash";+import rootroutes from "./navigation/rootRoutes";+import { useRoutes } from "raviger";// Sentry.init({// dsn:@@ -28,24 +27,14 @@ import Splash from "./views/splash";// });Modal.setAppElement("#root");-ReactDOM.render(- <MotionConfig features={[AnimationFeature, GesturesFeature]}>- <Splash- onLoadingFinished={() => {- ReactDOM.render(- <MotionConfig features={[AnimationFeature, GesturesFeature]}>- <App />- </MotionConfig>,- document.getElementById("root")- );- }}- />- </MotionConfig>,- document.getElementById("root"),- () => {}-);+ReactDOM.render(<Root />, document.getElementById("root"), () => {});// If you want your app to work offline and load faster, you can change// unregister() to register() below. Note this comes with some pitfalls.// Learn more about service workers: https://bit.ly/CRA-PWAserviceWorker.register();++function Root() {+ const routeResult = useRoutes(rootroutes, { fallbackRoute: "/" });+ return routeResult;+}diff --git a/apps/web/src/navigation/rootRoutes.js b/apps/web/src/navigation/rootRoutes.jsnew file mode 100644index 000000000..33a13b251--- /dev/null+++ b/apps/web/src/navigation/rootRoutes.js@@ -0,0 +1,28 @@+import React from "react";+import ReactDOM from "react-dom";+import App from "../App";+import { MotionConfig, AnimationFeature, GesturesFeature } from "framer-motion";+import Splash from "../views/splash";+import AccountRecovery from "../views/recovery";+import EmailConfirmed from "../views/emailconfirmed";++const rootroutes = {+ "/": () => (+ <MotionConfig features={[AnimationFeature, GesturesFeature]}>+ <Splash+ onLoadingFinished={() => {+ ReactDOM.render(+ <MotionConfig features={[AnimationFeature, GesturesFeature]}>+ <App />+ </MotionConfig>,+ document.getElementById("root")+ );+ }}+ />+ </MotionConfig>+ ),+ "/accountRecovery": () => <AccountRecovery />,+ "/emailConfirmed": () => <EmailConfirmed />,+};++export default rootroutes;diff --git a/apps/web/src/stores/app-store.js b/apps/web/src/stores/app-store.jsindex 898cca114..3648a19ee 100644--- a/apps/web/src/stores/app-store.js+++ b/apps/web/src/stores/app-store.js@@ -62,7 +62,7 @@ class AppStore extends BaseStore {/***- * @param {"backup"|"signup"} type+ * @param {"backup"|"signup"|"email"} type* @param {string} title* @param {string} detail* @param {"high"|"medium"|"low"} prioritydiff --git a/apps/web/src/stores/user-store.js b/apps/web/src/stores/user-store.jsindex a1fd064a0..3e0a38695 100644--- a/apps/web/src/stores/user-store.js+++ b/apps/web/src/stores/user-store.js@@ -32,6 +32,11 @@ class UserStore extends BaseStore {};});});+ EV.subscribe("user:emailConfirmed", async () => {+ showToast("success", "Email confirmed successfully!");+ await this.sync(true);+ });+EV.subscribe("db:sync", () => this.sync(false));EV.subscribe("user:loggedOut", async () => {this.set((state) => {diff --git a/apps/web/src/views/email-confirmed.js b/apps/web/src/views/email-confirmed.jsnew file mode 100644index 000000000..4d7ee7e45--- /dev/null+++ b/apps/web/src/views/email-confirmed.js@@ -0,0 +1,50 @@+import React, { useEffect, useState } from "react";+import { Button, Flex, Text } from "rebass";+import { navigate, useQueryParams } from "raviger";+import ThemeProvider from "../components/theme-provider";+import Field from "../components/field";+import * as Icon from "../components/icons";+import { db } from "../common";+import TokenManager from "notes-core/api/tokenmanager";+import { showToast } from "../utils/toast";+import { useCallback } from "react";++function EmailConfirmed(props) {+ return (+ <ThemeProvider>+ <Flex+ flexDirection="column"+ height="100%"+ justifyContent="center"+ alignItems="center"+ >+ <Flex+ flexDirection="column"+ justifyContent="center"+ alignItems="center"+ p={2}+ >+ <Text variant="heading" color="primary">+ Notesnook+ </Text>++ <Text display="flex" variant="heading" fontSize={32}>+ <Icon.Success color="primary" size={32} sx={{ mr: 2 }} /> Email+ confirmed!+ </Text>++ <Button+ variant="secondary"+ mt={1}+ onClick={() => {+ window.location.href = "https://notesnook.com/";+ }}+ >+ Return to Notesnook+ </Button>+ </Flex>+ </Flex>+ </ThemeProvider>+ );+}+export default EmailConfirmed;diff --git a/apps/web/src/views/recovery.js b/apps/web/src/views/recovery.jsnew file mode 100644index 000000000..1f0c8d717--- /dev/null+++ b/apps/web/src/views/recovery.js@@ -0,0 +1,172 @@+import React, { useEffect, useState } from "react";+import { Button, Flex, Text } from "rebass";+import { navigate, useQueryParams } from "raviger";+import ThemeProvider from "../components/theme-provider";+import Field from "../components/field";+import * as Icon from "../components/icons";+import { db } from "../common";+import TokenManager from "notes-core/api/tokenmanager";+import { showToast } from "../utils/toast";+import { useCallback } from "react";++function AccountRecovery(props) {+ const [{ code, userId }] = useQueryParams();+ const [step, setStep] = useState(1);+ const [loading, setLoading] = useState({ isLoading: false });++ const doWorkWithLoading = useCallback(+ async (message, workCallback, onError) => {+ try {+ setLoading({ isLoading: true, message });+ await workCallback();+ } catch (e) {+ console.error(e);+ showToast("error", e.message);+ if (onError) onError(e);+ } finally {+ setLoading({ isLoading: false });+ }+ },+ []+ );++ useEffect(() => {+ if (!code || !userId) {+ navigate("/");+ return;+ }+ // http://localhost:3000/accountRecovery?userId=5fe1895d1b0636cf87b5058ecode=CfDJ8J5/rfvIUAZBidvsDZpkZcvNxUm0K2dGODHceKrSC4GUrGxtS3ZG5G2l8T7m0dvx6otZZv7djtzKBOUls0yZsjehYq+uSe0hG72M+DAMtB9gQ6df28xWdh2fx7L7Fw7s5I9unuRGYjN/A31e0BT3ryt9rzS1NM9ATnju80l1NR0Te599i76lSPLaOpnbO8qUanOqGtoQwaOa+bEMjJRGDG5NH2DkuJEsuD7VGqgXB57s4LWNJL0MvNwm5y2WImuaoQ==+ (async function () {+ setLoading({ isLoading: true, message: "Authorizing. Please wait..." });+ doWorkWithLoading(+ "Authorizing. Please wait...",+ async () => {+ await db.init();+ if (!!(await db.user.tokenManager.getAccessToken())) {+ await db.user.fetchUser(false);+ setLoading({ isLoading: false });+ return;+ }+ await db.user.tokenManager.getAccessTokenFromAuthorizationCode(+ userId,+ code.replace(/ /gm, "+")+ );+ await db.user.fetchUser(false);+ },+ () => {+ navigate("/");+ }+ );+ })();+ }, [userId, code, doWorkWithLoading]);++ return (+ <ThemeProvider>+ <Flex+ flexDirection="column"+ height="100%"+ justifyContent="center"+ alignItems="center"+ >+ <Flex+ flexDirection="column"+ justifyContent="center"+ alignItems="center"+ p={2}+ >+ <Text variant="heading" color="primary">+ Notesnook+ </Text>+ <Text variant="heading" fontSize={24} mb={2} textAlign="center">+ {step === 3+ ? "Your account has been recovered!"+ : "Account Recovery"}+ </Text>+ {loading.isLoading ? (+ <Flex flexDirection="column">+ <Icon.Loading rotate />+ <Text variant="body">{loading.message}</Text>+ </Flex>+ ) : step === 3 ? (+ <Flex flexDirection="column">+ <Button variant="secondary">Return to Notesnook</Button>+ </Flex>+ ) : (+ <Flex+ flexDirection="column"+ as="form"+ width="100%"+ onSubmit={async (e) => {+ e.preventDefault();+ var formData = new FormData(e.target);++ var recoveryKey = formData.get("recovery_key");+ if (recoveryKey) {+ const [key] = recoveryKey.split("\0");+ await doWorkWithLoading(+ "Downloading your data. This might take a bit.",+ async () => {+ const user = await db.user.getUser();+ await db.context.write(`_uk_@${user.email}@_k`, key);+ await db.sync(true, true);+ }+ );+ setStep((s) => ++s);+ }+ var newPassword = formData.get("new_password");+ if (newPassword) {+ await doWorkWithLoading(+ "Resetting account password. Please wait...",+ async () => {+ if (await db.user.resetPassword(newPassword)) {+ setStep((s) => ++s);+ }+ }+ );+ }+ }}+ >+ {step === 1 ? (+ <Field+ id="recovery_key"+ name="recovery_key"+ label="Recovery Key"+ autoFocus+ helpText="We'll use the recovery key to download & decrypt your data."+ />+ ) : (+ <Field+ id="new_password"+ name="new_password"+ type="password"+ label="New Password"+ autoFocus+ helpText="Enter new account password."+ />+ )}++ <Flex alignSelf="flex-end" mt={2}>+ {step === 1 && (+ <Button+ type="submit"+ variant="secondary"+ py={"7px"}+ px={4}+ alignSelf="flex-end"+ mr={1}+ >+ I don't have it+ </Button>+ )}+ <Button type="submit" py={"7px"} px={4}>+ Next+ </Button>+ </Flex>+ </Flex>+ )}+ </Flex>+ </Flex>+ </ThemeProvider>+ );+}+export default AccountRecovery;diff --git a/apps/web/yarn.lock b/apps/web/yarn.lockindex ac8c7ba8b..c750951d2 100644--- a/apps/web/yarn.lock+++ b/apps/web/yarn.lock@@ -8957,9 +8957,21 @@ normalize-url@^3.0.0, normalize-url@^3.0.1:resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-3.3.0.tgz#b2e1c4dc4f7c6d57743df733a4f5978d18650559"integrity sha512-U+JJi7duF1o+u2pynbp2zXDW2/PADgC30f0GsHZtRh+HOcXHnw137TrNlyxxRvWW5fjKd3bcLHPxofWuCjaeZg==+notes-core@../notes-core:+ version "5.1.0"+ dependencies:+ fast-sort "^2.0.1"+ fuzzysearch "^1.0.3"+ jshashes "^1.0.8"+ no-internet "^1.5.2"+ qclone "^1.0.4"+ quill-delta-to-html "^0.12.0"+ quill-delta-to-markdown "https://github.com/streetwriters/quill-delta-to-markdown"+ transfun "^1.0.2"+"notes-core@git+ssh://[email protected]:streetwriters/notesnook-core.git":- version "5.0.1"- resolved "git+ssh://[email protected]:streetwriters/notesnook-core.git#240c8ef83e02553f17fd1ec734b8ce175343223e"+ version "5.1.0"+ resolved "git+ssh://[email protected]:streetwriters/notesnook-core.git#98d70c891dee3d30616cb87752b7298240b1cf6d"dependencies:fast-sort "^2.0.1"fuzzysearch "^1.0.3"