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
mobile: add session expired login flow
ammarahm-edec699e8ef40f
diff --git a/apps/mobile/app/common/database/index.js b/apps/mobile/app/common/database/index.jsindex 6460e5618..3e5db2303 100644--- a/apps/mobile/app/common/database/index.js+++ b/apps/mobile/app/common/database/index.js@@ -49,16 +49,16 @@ export var db = new Database(db.host(__DEV__? {- // API_HOST: "https://api.notesnook.com",- // AUTH_HOST: "https://auth.streetwriters.co",- // SSE_HOST: "https://events.streetwriters.co",- // SUBSCRIPTIONS_HOST: "https://subscriptions.streetwriters.co",- // ISSUES_HOST: "https://issues.streetwriters.co"- API_HOST: "http://192.168.8.109:5264",- AUTH_HOST: "http://192.168.8.109:8264",- SSE_HOST: "http://192.168.8.109:7264",- SUBSCRIPTIONS_HOST: "http://192.168.8.109:9264",- ISSUES_HOST: "http://192.168.8.109:2624"+ API_HOST: "https://api.notesnook.com",+ AUTH_HOST: "https://auth.streetwriters.co",+ SSE_HOST: "https://events.streetwriters.co",+ SUBSCRIPTIONS_HOST: "https://subscriptions.streetwriters.co",+ ISSUES_HOST: "https://issues.streetwriters.co"+ // API_HOST: "http://192.168.8.109:5264",+ // AUTH_HOST: "http://192.168.8.109:8264",+ // SSE_HOST: "http://192.168.8.109:7264",+ // SUBSCRIPTIONS_HOST: "http://192.168.8.109:9264",+ // ISSUES_HOST: "http://192.168.8.109:2624"}: {API_HOST: "https://api.notesnook.com",diff --git a/apps/mobile/app/components/auth/login.js b/apps/mobile/app/components/auth/login.jsindex 7c370b67e..0702472e4 100644--- a/apps/mobile/app/components/auth/login.js+++ b/apps/mobile/app/components/auth/login.js@@ -17,19 +17,13 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import React, { useEffect, useRef, useState } from "react";+import React, { useEffect, useState } from "react";import { View } from "react-native";import { SheetManager } from "react-native-actions-sheet";import Animated, { FadeInDown, FadeOutUp } from "react-native-reanimated";-import { db } from "../../common/database";import { DDS } from "../../services/device-detection";-import { eSendEvent, ToastEvent } from "../../services/event-manager";-import { clearMessage } from "../../services/message";-import PremiumService from "../../services/premium";-import SettingsService from "../../services/settings";+import { eSendEvent } from "../../services/event-manager";import { useThemeStore } from "../../stores/use-theme-store";-import { useUserStore } from "../../stores/use-user-store";-import { eCloseSheet } from "../../utils/events";import { SIZE } from "../../utils/size";import { sleep } from "../../utils/time";import BaseDialog from "../dialog/base-dialog";@@ -43,7 +37,7 @@ import Paragraph from "../ui/typography/paragraph";import { SVG } from "./background";import { hideAuth } from "./common";import { ForgotPassword } from "./forgot-password";-import TwoFactorVerification from "./two-factor";+import { useLogin } from "./use-login";const LoginSteps = {emailAuth: 1,@@ -53,34 +47,24 @@ const LoginSteps = {export const Login = ({ changeMode }) => {const colors = useThemeStore((state) => state.colors);- const [step, setStep] = useState(LoginSteps.emailAuth);- const email = useRef();- const emailInputRef = useRef();- const passwordInputRef = useRef();- const password = useRef();const [focused, setFocused] = useState(false);- const [error, setError] = useState(false);- const [loading, setLoading] = useState(false);-- const setUser = useUserStore((state) => state.setUser);-- const validateInfo = () => {- if (- (!password.current && step === LoginSteps.passwordAuth) ||- (!email.current && step === LoginSteps.emailAuth)- ) {- ToastEvent.show({- heading: "All fields required",- message: "Fill all the fields and try again",- type: "error",- context: "local"- });-- return false;- }-- return true;- };+ const {+ step,+ setStep,+ password,+ email,+ emailInputRef,+ passwordInputRef,+ loading,+ setLoading,+ setError,+ login+ } = useLogin(undefined, async () => {+ hideAuth();+ eSendEvent("userLoggedIn", true);+ await sleep(500);+ Progress.present();+ });useEffect(() => {async () => {@@ -92,87 +76,9 @@ export const Login = ({ changeMode }) => {return () => {setStep(LoginSteps.emailAuth);};+ // eslint-disable-next-line react-hooks/exhaustive-deps}, []);- const login = async () => {- if (!validateInfo() || error) return;- try {- setLoading(true);- switch (step) {- case LoginSteps.emailAuth: {- const mfaInfo = await db.user.authenticateEmail(email.current);- if (mfaInfo) {- TwoFactorVerification.present(async (mfa, callback) => {- try {- const success = await db.user.authenticateMultiFactorCode(- mfa.code,- mfa.method- );- if (success) {- setStep(LoginSteps.passwordAuth);- setLoading(false);- setTimeout(() => {- passwordInputRef.current?.focus();- }, 1);- callback && callback(true);- }- callback && callback(false);- } catch (e) {- callback && callback(false);- if (e.message === "invalid_grant") {- eSendEvent(eCloseSheet, "two_factor_verify");- setLoading(false);- }- }- }, mfaInfo);- }- break;- }- case LoginSteps.passwordAuth: {- await db.user.authenticatePassword(email.current, password.current);- finishLogin();- break;- }- }- setLoading(false);- } catch (e) {- finishWithError(e);- }- };-- const finishWithError = async (e) => {- setLoading(false);- ToastEvent.show({- heading: "Login failed",- message: e.message,- type: "error",- context: "local"- });- };-- const finishLogin = async () => {- const user = await db.user.getUser();- if (!user) throw new Error("Email or password incorrect!");- PremiumService.setPremiumStatus();- setUser(user);- clearMessage();- ToastEvent.show({- heading: "Login successful",- message: `Logged in as ${user.email}`,- type: "success",- context: "global"- });- hideAuth();- SettingsService.set({- sessionExpired: false,- userEmailConfirmed: user?.isEmailConfirmed- });- eSendEvent("userLoggedIn", true);- await sleep(500);- Progress.present();- setLoading(false);- };-return (<><ForgotPassword />diff --git a/apps/mobile/app/components/auth/session-expired.js b/apps/mobile/app/components/auth/session-expired.jsindex a280d14a2..5b0df720b 100644--- a/apps/mobile/app/components/auth/session-expired.js+++ b/apps/mobile/app/components/auth/session-expired.js@@ -17,37 +17,32 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import React, { useEffect, useRef, useState } from "react";+import React, { useEffect, useState } from "react";import { Modal, View } from "react-native";import { db } from "../../common/database";import BiometricService from "../../services/biometrics";import {- eSendEvent,eSubscribeEvent,eUnSubscribeEvent,ToastEvent} from "../../services/event-manager";-import { clearMessage } from "../../services/message";-import PremiumService from "../../services/premium";import SettingsService from "../../services/settings";import Sync from "../../services/sync";import { useThemeStore } from "../../stores/use-theme-store";-import { useUserStore } from "../../stores/use-user-store";import { SIZE } from "../../utils/size";import { sleep } from "../../utils/time";import { Dialog } from "../dialog";import { presentDialog } from "../dialog/functions";import SheetProvider from "../sheet-provider";-import { Progress } from "../sheets/progress";import { Toast } from "../toast";import { Button } from "../ui/button";import { IconButton } from "../ui/icon-button";import Input from "../ui/input";import Heading from "../ui/typography/heading";import Paragraph from "../ui/typography/paragraph";-import TwoFactorVerification from "./two-factor";+import { LoginSteps, useLogin } from "./use-login";-function getEmail(email) {+function getObfuscatedEmail(email) {if (!email) return null;return email.replace(/(.{2})(.*)(?=@)/, function (gp1, gp2, gp3) {for (let i = 0; i < gp3.length; i++) {@@ -59,15 +54,14 @@ function getEmail(email) {export const SessionExpired = () => {const colors = useThemeStore((state) => state.colors);- const email = useRef();- const passwordInputRef = useRef();- const password = useRef();const [visible, setVisible] = useState(false);const [focused, setFocused] = useState(false);-- const setUser = useUserStore((state) => state.setUser);-- const [loading, setLoading] = useState(false);+ const { step, password, email, passwordInputRef, loading, login } = useLogin(+ undefined,+ () => {+ setVisible(false);+ }+ );const logout = async () => {try {@@ -92,9 +86,9 @@ export const SessionExpired = () => {eUnSubscribeEvent("session_expired", open);setFocused(false);};- }, [visible]);+ }, [visible, open]);- const open = async () => {+ const open = React.useCallback(async () => {try {let res = await db.user.tokenManager.getToken();if (!res) throw new Error("no token found");@@ -120,64 +114,8 @@ export const SessionExpired = () => {email.current = user.email;setVisible(true);}- };+ }, [email]);- const login = async (mfa, callback) => {- setLoading(true);- let user;- try {- if (mfa) {- await db.user.mfaLogin(- email.current.toLowerCase(),- password.current,- mfa- );- } else {- await db.user.login(email.current.toLowerCase(), password.current);- }- callback && callback(true);- setVisible(false);- user = await db.user.getUser();- if (!user) throw new Error("Email or password incorrect!");- PremiumService.setPremiumStatus();- setUser(user);- clearMessage();- ToastEvent.show({- heading: "Login successful",- message: `Logged in as ${user.email}`,- type: "success",- context: "global"- });- await SettingsService.set({- sessionExpired: false,- userEmailConfirmed: user?.isEmailConfirmed- });- eSendEvent("userLoggedIn", true);- await sleep(500);- Progress.present();- setLoading(false);- } catch (e) {- callback && callback(false);- if (e.message === "Multifactor authentication required.") {- TwoFactorVerification.present(async (mfa) => {- if (mfa) {- await login(mfa);- } else {- setLoading(false);- }- }, e.data);- } else {- console.log(e.stack);- setLoading(false);- ToastEvent.show({- heading: user ? "Failed to sync" : "Login failed",- message: e.message,- type: "error",- context: "local"- });- }- }- };return (visible && (<Modal@@ -194,7 +132,8 @@ export const SessionExpired = () => {width: focused ? "100%" : "99.9%",padding: 12,justifyContent: "center",- flex: 1+ flex: 1,+ backgroundColor: colors.bg}}><View@@ -225,29 +164,32 @@ export const SessionExpired = () => {}}>Your session on this device has expired. Please enter password for{" "}- {getEmail(email.current)} to continue.+ {getObfuscatedEmail(email.current)} to continue.</Paragraph></View>- <Input- fwdRef={passwordInputRef}- onChangeText={(value) => {- password.current = value;- }}- returnKeyLabel="Next"- returnKeyType="next"- secureTextEntry- autoComplete="password"- autoCapitalize="none"- autoCorrect={false}- placeholder="Password"- onSubmit={() => login()}- />+ {step === LoginSteps.passwordAuth ? (+ <Input+ fwdRef={passwordInputRef}+ onChangeText={(value) => {+ password.current = value;+ }}+ returnKeyLabel="Next"+ returnKeyType="next"+ secureTextEntry+ autoComplete="password"+ autoCapitalize="none"+ autoCorrect={false}+ placeholder="Password"+ onSubmit={() => login()}+ />+ ) : null}<Buttonstyle={{marginTop: 10,- width: "100%"+ width: 250,+ borderRadius: 100}}loading={loading}onPress={() => login()}diff --git a/apps/mobile/app/components/auth/use-login.js b/apps/mobile/app/components/auth/use-login.jsnew file mode 100644index 000000000..25dbf0c5a--- /dev/null+++ b/apps/mobile/app/components/auth/use-login.js@@ -0,0 +1,156 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2022 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import { useRef, useState } from "react";+import { db } from "../../common/database";+import { eSendEvent, ToastEvent } from "../../services/event-manager";+import { clearMessage } from "../../services/message";+import PremiumService from "../../services/premium";+import SettingsService from "../../services/settings";+import { useUserStore } from "../../stores/use-user-store";+import { eCloseSheet } from "../../utils/events";+import { sleep } from "../../utils/time";+import { Progress } from "../sheets/progress";+import { hideAuth } from "./common";+import TwoFactorVerification from "./two-factor";++export const LoginSteps = {+ emailAuth: 1,+ mfaAuth: 2,+ passwordAuth: 3+};++export const useLogin = (defaultEmail, onFinishLogin) => {+ const [error, setError] = useState(false);+ const [loading, setLoading] = useState(false);+ const setUser = useUserStore((state) => state.setUser);+ const [step, setStep] = useState(LoginSteps.emailAuth);+ const email = useRef(defaultEmail);+ const password = useRef();+ const emailInputRef = useRef();+ const passwordInputRef = useRef();++ const validateInfo = () => {+ if (+ (!password.current && step === LoginSteps.passwordAuth) ||+ (!email.current && step === LoginSteps.emailAuth)+ ) {+ ToastEvent.show({+ heading: "All fields required",+ message: "Fill all the fields and try again",+ type: "error",+ context: "local"+ });++ return false;+ }++ return true;+ };++ const login = async () => {+ if (!validateInfo() || error) return;+ try {+ setLoading(true);+ switch (step) {+ case LoginSteps.emailAuth: {+ const mfaInfo = await db.user.authenticateEmail(email.current);+ if (mfaInfo) {+ TwoFactorVerification.present(async (mfa, callback) => {+ try {+ const success = await db.user.authenticateMultiFactorCode(+ mfa.code,+ mfa.method+ );+ if (success) {+ setStep(LoginSteps.passwordAuth);+ setLoading(false);+ setTimeout(() => {+ passwordInputRef.current?.focus();+ }, 1);+ callback && callback(true);+ }+ callback && callback(false);+ } catch (e) {+ callback && callback(false);+ if (e.message === "invalid_grant") {+ eSendEvent(eCloseSheet, "two_factor_verify");+ setLoading(false);+ }+ }+ }, mfaInfo);+ }+ break;+ }+ case LoginSteps.passwordAuth: {+ await db.user.authenticatePassword(email.current, password.current);+ finishLogin();+ break;+ }+ }+ setLoading(false);+ } catch (e) {+ finishWithError(e);+ }+ };++ const finishWithError = async (e) => {+ setLoading(false);+ ToastEvent.show({+ heading: "Login failed",+ message: e.message,+ type: "error",+ context: "local"+ });+ };++ const finishLogin = async () => {+ const user = await db.user.getUser();+ if (!user) throw new Error("Email or password incorrect!");+ PremiumService.setPremiumStatus();+ setUser(user);+ clearMessage();+ ToastEvent.show({+ heading: "Login successful",+ message: `Logged in as ${user.email}`,+ type: "success",+ context: "global"+ });+ SettingsService.set({+ sessionExpired: false,+ userEmailConfirmed: user?.isEmailConfirmed+ });+ onFinishLogin?.();+ setLoading(false);+ };++ return {+ login,+ step,+ setStep,+ email,+ password,+ passwordInputRef,+ emailInputRef,+ loading,+ setLoading,+ error,+ setError+ };+};