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: handle session expiry properly
thecodrr2db9f215bea4
diff --git a/apps/web/src/common/dialogcontroller.js b/apps/web/src/common/dialogcontroller.jsindex 649d064d3..3db768b75 100644--- a/apps/web/src/common/dialogcontroller.js+++ b/apps/web/src/common/dialogcontroller.js@@ -341,14 +341,23 @@ export function showLoadingDialog(dialogData) {));}-export const showLogInDialog = (title, description, positiveText, skipInit) => {+export const showLogInDialog = (+ title,+ description,+ positiveText,+ email,+ skipInit,+ force+) => {return showDialog((Dialogs, perform) => (<Dialogs.LoginDialogtitle={title}description={description}positiveText={positiveText}skipInit={skipInit}- onClose={() => perform()}+ force={force}+ email={email}+ onClose={(res) => perform(res)}/>));};@@ -471,8 +480,9 @@ export function showTopicDialog() {}export function showEditTopicDialog(notebookId, topicId) {- const topic = db.notebooks.notebook(notebookId)?.topics?.topic(topicId)- ?._topic;+ const topic = db.notebooks+ .notebook(notebookId)+ ?.topics?.topic(topicId)?._topic;if (!topic) return;return showDialog((Dialogs, perform) => (<Dialogs.TopicDialogdiff --git a/apps/web/src/components/dialogs/logindialog.js b/apps/web/src/components/dialogs/logindialog.jsindex fd3974f2f..196e8b9cd 100644--- a/apps/web/src/components/dialogs/logindialog.js+++ b/apps/web/src/components/dialogs/logindialog.js@@ -4,100 +4,54 @@ import * as Icon from "../icons";import Dialog from "./dialog";import { useStore } from "../../stores/user-store";import Field from "../field";-import { Checkbox, Label } from "@rebass/forms";import { showForgotPasswordDialog } from "../../common/dialog-controller";import { hashNavigate } from "../../navigation";import useHashLocation from "../../utils/use-hash-location";-const requiredValues = ["email", "password", "remember"];+const requiredValues = ["email", "password"];function LoginDialog(props) {- const { onClose, title, description, positiveText, skipInit } = props;+ const { onClose, title, description, positiveText, email, skipInit, force } =+ props;const [error, setError] = useState();const [, queryParams] = useHashLocation();- const [credential, setCredential] = useState();- const [email, setEmail] = useState();const isLoggingIn = useStore((store) => store.isLoggingIn);const login = useStore((store) => store.login);const isLoggedIn = useStore((store) => store.isLoggedIn);useEffect(() => {- if (isLoggedIn) {+ if (isLoggedIn && !force) {onClose();if (queryParams.redirect) hashNavigate(queryParams.redirect);}- }, [isLoggedIn, queryParams, onClose]);+ }, [isLoggedIn, queryParams, force, onClose]);- useEffect(() => {- if (isLoggedIn) {- onClose();- }- }, [isLoggedIn, onClose]);-- useEffect(() => {- if (!window.PasswordCredential) return;- (async function () {- const credential = await navigator.credentials.get({- mediation: "required",- password: true,- });- if (credential) {- setCredential(credential);- if (!credential.password) {- setEmail(credential.id);- } else {- try {- await login({- password: credential.password,- email: credential.id,- remember: true,- });- onClose();- } catch (e) {- setEmail(credential.id);- setCredential();- setError(e.message);- }- }- }- })();- }, [login, onClose]);return (<DialogisOpen={true}- title={- credential?.password- ? `Signing in as ${credential.id}...`- : title || "Sign in to your account"- }+ title={title || "Sign in to your account"}description={<Flex alignItems="center">- {credential?.password ? (- <Text as="span" fontSize="body" color="gray">- Please wait...- </Text>- ) : (- <Text as="span" fontSize="body" color="gray">- {description ? (- description- ) : (- <>- Don't have an account?{" "}- <Button- variant="anchor"- sx={{ textAlign: "left" }}- fontSize="body"- onClick={() => hashNavigate("/signup")}- >- Create an account here.- </Button>- </>- )}- </Text>- )}+ <Text as="span" fontSize="body" color="gray">+ {description ? (+ description+ ) : (+ <>+ Don't have an account?{" "}+ <Button+ variant="anchor"+ sx={{ textAlign: "left" }}+ fontSize="body"+ onClick={() => hashNavigate("/signup")}+ >+ Create an account here.+ </Button>+ </>+ )}+ </Text></Flex>}icon={Icon.Login}- onClose={onClose}+ onClose={() => onClose(false)}scrollablenegativeButton={{text: "Cancel",@@ -114,77 +68,59 @@ function LoginDialog(props) {disabled: isLoggingIn,}}>- {!credential?.password && (- <Flex- id="loginForm"- as="form"- onSubmit={(e) => {- e.preventDefault();- const form = new FormData(e.target);- const data = requiredValues.reduce((prev, curr) => {- prev[curr] = form.get(curr);- return prev;- }, {});+ <Flex+ id="loginForm"+ as="form"+ onSubmit={(e) => {+ e.preventDefault();+ const form = new FormData(e.target);+ const data = requiredValues.reduce((prev, curr) => {+ prev[curr] = form.get(curr);+ return prev;+ }, {});+ setError();- setError();+ if (email) data.email = email;- login(data, skipInit)- .then(async () => {- // Instantiate PasswordCredential with the form- if (window.PasswordCredential) {- var c = new window.PasswordCredential({- id: data.email,- name: data.email,- type: "password",- password: data.password,- });- await navigator.credentials.store(c);- onClose();- } else {- onClose();- }- if (queryParams.redirect) {- hashNavigate(queryParams.redirect);- }- })- .catch((e) => setError(e.message));- }}- flexDirection="column"+ login(data, skipInit)+ .then(async () => {+ onClose(true);+ if (queryParams.redirect) {+ hashNavigate(queryParams.redirect);+ }+ })+ .catch((e) => setError(e.message));+ }}+ flexDirection="column"+ >+ <Field+ required+ id="email"+ label="Email"+ name="email"+ defaultValue={email}+ disabled={!!email}+ autoComplete="email"+ />+ <Field+ required+ id="password"+ label="Password"+ name="password"+ type="password"+ autoComplete="current-password"+ sx={{ mt: 1 }}+ />+ <Button+ type="button"+ variant="anchor"+ sx={{ alignSelf: "flex-start" }}+ onClick={showForgotPasswordDialog}>- <Field- autoFocus={!email}- required- id="email"- label="Email"- name="email"- autoComplete="email"- defaultValue={email}- />- <Field- autoFocus={!!email}- required- id="password"- label="Password"- name="password"- type="password"- autoComplete="current-password"- sx={{ mt: 1 }}- />- <Button- type="button"- variant="anchor"- sx={{ alignSelf: "flex-start" }}- onClick={showForgotPasswordDialog}- >- Forgot password?- </Button>- {error && <Text variant="error">{error}</Text>}- <Label mt={1} fontSize="body" alignItems="center" color="text">- <Checkbox id="remember" name="remember" defaultChecked />- Keep me logged in- </Label>- </Flex>- )}+ Forgot password?+ </Button>+ {error && <Text variant="error">{error}</Text>}+ </Flex></Dialog>);}diff --git a/apps/web/src/components/field/index.js b/apps/web/src/components/field/index.jsindex 369c88100..26f1bc7fd 100644--- a/apps/web/src/components/field/index.js+++ b/apps/web/src/components/field/index.js@@ -42,6 +42,7 @@ function Field(props) {onKeyDown,onChange,inputRef,+ disabled,defaultValue,placeholder,validatePassword,@@ -76,6 +77,7 @@ function Field(props) {required={required}name={name}id={id}+ disabled={disabled}placeholder={placeholder}autoComplete={autoComplete}type={type || "text"}diff --git a/apps/web/src/stores/user-store.js b/apps/web/src/stores/user-store.jsindex a06e29b7d..0d8b8b2f3 100644--- a/apps/web/src/stores/user-store.js+++ b/apps/web/src/stores/user-store.js@@ -5,10 +5,12 @@ import { store as appStore } from "./app-store";import BaseStore from "./index";import config from "../utils/config";import { EV, EVENTS } from "notes-core/common";-import { showLoadingDialog } from "../common/dialog-controller";+import { showLoadingDialog, showLogInDialog } from "../common/dialog-controller";import { Text } from "rebass";import { showToast } from "../utils/toast";import { showAccountLoggedOutNotice } from "../common/dialog-controller";+import Config from "../utils/config";+import { onPageVisibilityChanged } from "../utils/page-visibility";class UserStore extends BaseStore {isLoggedIn = false;@@ -21,12 +23,36 @@ class UserStore extends BaseStore {init = () => {EV.subscribe(EVENTS.appRefreshRequested, () => appStore.refresh());- db.user.getUser().then((user) => {+ EV.subscribe(EVENTS.userSessionExpired, async () => {+ const user = this.get().user;+ Config.set("sessionExpired", "true");+ const loginResult = await showLogInDialog(+ "Your session has expired.",+ "Please login again to continue. If you press Cancel or close the dialog, all your data will be erased.",+ "Login",+ user.email,+ true,+ true+ );+ console.log("SESSION", loginResult);+ Config.set("sessionExpired", "false");+ if (!loginResult) {+ await db.user.logout(false);+ return { result: false };+ }+ return { result: true };+ });++ db.user.getUser().then(async (user) => {if (!user) return false;+this.set((state) => {state.user = user;state.isLoggedIn = true;});++ if (Config.get("sessionExpired") === "true")+ EV.publish(EVENTS.userSessionExpired);});return db.user.fetchUser(true).then(async (user) => {if (!user) return false;@@ -45,6 +71,7 @@ class UserStore extends BaseStore {EV.subscribe(EVENTS.databaseSyncRequested, async () => {await this.sync(false);});+EV.subscribe(EVENTS.userLoggedOut, async (reason) => {this.set((state) => {state.user = {};@@ -53,15 +80,17 @@ class UserStore extends BaseStore {config.clear();await appStore.refresh();- if (window.PasswordCredential) {- await navigator.credentials.preventSilentAccess();- if (navigator.credentials.requireUserMediation)- await navigator.credentials.requireUserMediation();- }if (!!reason) {await showAccountLoggedOutNotice(reason);}});++ onPageVisibilityChanged(async (documentHidden) => {+ if (!documentHidden) {+ await db.connectSSE();+ await this.sync();+ }+ });await this.sync();return true;});@@ -70,7 +99,7 @@ class UserStore extends BaseStore {login = (form, skipInit = false) => {this.set((state) => (state.isLoggingIn = true));return db.user- .login(form.email.toLowerCase(), form.password, form.remember)+ .login(form.email.toLowerCase(), form.password).then(() => {if (skipInit) return true;return showLoadingDialog({diff --git a/apps/web/src/utils/page-visibility.js b/apps/web/src/utils/page-visibility.jsnew file mode 100644index 000000000..d25831941--- /dev/null+++ b/apps/web/src/utils/page-visibility.js@@ -0,0 +1,25 @@+var hidden, visibilityChange;+if (typeof document.hidden !== "undefined") {+ // Opera 12.10 and Firefox 18 and later support+ hidden = "hidden";+ visibilityChange = "visibilitychange";+} else if (typeof document.msHidden !== "undefined") {+ hidden = "msHidden";+ visibilityChange = "msvisibilitychange";+} else if (typeof document.webkitHidden !== "undefined") {+ hidden = "webkitHidden";+ visibilityChange = "webkitvisibilitychange";+}++// // If the page is hidden, pause the video;+// // if the page is shown, play the video+// function handleVisibilityChange() {+// if (document[hidden]) {+// } else {+// }+// }++export function onPageVisibilityChanged(handler) {+ // Handle page visibility change+ document.addEventListener(visibilityChange, () => handler(document[hidden]));+}