Skip to content

A local-first personal finance app

✨ New OpenID first login UX (#4446)

lelemm35a833ecbaf3
diff --git a/packages/component-library/src/Input.tsx b/packages/component-library/src/Input.tsx
index deb0e0a303..e7c73ba28d 100644
--- a/packages/component-library/src/Input.tsx
+++ b/packages/component-library/src/Input.tsx
@@ -6,6 +6,7 @@ import React, {
import { css, cx } from '@emotion/css';
+import { useResponsive } from './hooks/useResponsive';
import { styles, type CSSProperties } from './styles';
import { theme } from './theme';
@@ -19,7 +20,7 @@ export const defaultInputStyle = {
border: '1px solid ' + theme.formInputBorder,
};
-type InputProps = InputHTMLAttributes<HTMLInputElement> & {
+export type InputProps = InputHTMLAttributes<HTMLInputElement> & {
style?: CSSProperties;
inputRef?: Ref<HTMLInputElement>;
onEnter?: (event: KeyboardEvent<HTMLInputElement>) => void;
@@ -101,3 +102,9 @@ export function BigInput(props: InputProps) {
/>
);
}
+
+export function ResponsiveInput(props: InputProps) {
+ const { isNarrowWidth } = useResponsive();
+
+ return isNarrowWidth ? <BigInput {...props} /> : <Input {...props} />;
+}
diff --git a/packages/desktop-client/src/components/manager/subscribe/ConfirmPasswordForm.tsx b/packages/desktop-client/src/components/manager/subscribe/ConfirmPasswordForm.tsx
index 4680e9326e..49affc542f 100644
--- a/packages/desktop-client/src/components/manager/subscribe/ConfirmPasswordForm.tsx
+++ b/packages/desktop-client/src/components/manager/subscribe/ConfirmPasswordForm.tsx
@@ -94,7 +94,11 @@ export function ConfirmPasswordForm({
);
}
-export function ConfirmOldPasswordForm({ buttons, onSetPassword }) {
+export function ConfirmOldPasswordForm({
+ buttons,
+ onSetPassword,
+ style = null,
+}) {
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [loading, setLoading] = useState(false);
@@ -121,6 +125,7 @@ export function ConfirmOldPasswordForm({ buttons, onSetPassword }) {
flexDirection: 'column',
alignItems: 'stretch',
marginTop: 30,
+ ...style,
}}
>
<BigInput
diff --git a/packages/desktop-client/src/components/manager/subscribe/Login.tsx b/packages/desktop-client/src/components/manager/subscribe/Login.tsx
index 3328f6bfd7..8809d4f089 100644
--- a/packages/desktop-client/src/components/manager/subscribe/Login.tsx
+++ b/packages/desktop-client/src/components/manager/subscribe/Login.tsx
@@ -1,14 +1,15 @@
// @ts-strict-ignore
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect, useRef } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router-dom';
import { Button, ButtonWithLoading } from '@actual-app/components/button';
import { useResponsive } from '@actual-app/components/hooks/useResponsive';
import { AnimatedLoading } from '@actual-app/components/icons/AnimatedLoading';
-import { BigInput } from '@actual-app/components/input';
-import { Label } from '@actual-app/components/label';
-import { Select } from '@actual-app/components/select';
+import { SvgCheveronDown } from '@actual-app/components/icons/v1';
+import { ResponsiveInput } from '@actual-app/components/input';
+import { Menu } from '@actual-app/components/menu';
+import { Popover } from '@actual-app/components/popover';
import { styles } from '@actual-app/components/styles';
import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
@@ -21,6 +22,7 @@ import { type OpenIdConfig } from 'loot-core/types/models';
import { useNavigate } from '../../../hooks/useNavigate';
import { useDispatch } from '../../../redux';
+import { warningBackground } from '../../../style/themes/dark';
import { Link } from '../../common/Link';
import { useAvailableLoginMethods, useLoginMethod } from '../../ServerContext';
@@ -61,7 +63,7 @@ function PasswordLogin({ setError, dispatch }) {
gap: '1rem',
}}
>
- <BigInput
+ <ResponsiveInput
autoFocus={true}
placeholder={t('Password')}
type="password"
@@ -72,7 +74,11 @@ function PasswordLogin({ setError, dispatch }) {
<ButtonWithLoading
variant="primary"
isLoading={loading}
- style={{ fontSize: 15, width: isNarrowWidth ? '100%' : 170 }}
+ style={{
+ fontSize: 15,
+ width: isNarrowWidth ? '100%' : 170,
+ ...(isNarrowWidth ? { padding: 10 } : null),
+ }}
onPress={onSubmitPassword}
>
<Trans>Sign in</Trans>
@@ -82,10 +88,14 @@ function PasswordLogin({ setError, dispatch }) {
}
function OpenIdLogin({ setError }) {
+ const { t } = useTranslation();
+ const { isNarrowWidth } = useResponsive();
const [warnMasterCreation, setWarnMasterCreation] = useState(false);
const [reviewOpenIdConfiguration, setReviewOpenIdConfiguration] =
useState(false);
const navigate = useNavigate();
+ const [openIdConfig, setOpenIdConfig] = useState<OpenIdConfig | null>(null);
+ const [firstLoginPassword, setFirstLoginPassword] = useState<string>('');
async function onSetOpenId(config: OpenIdConfig) {
setError(null);
@@ -108,6 +118,7 @@ function OpenIdLogin({ setError }) {
? await window.Actual.startOAuthServer()
: window.location.origin,
loginMethod: 'openid',
+ password: firstLoginPassword,
});
if (error) {
@@ -125,18 +136,42 @@ function OpenIdLogin({ setError }) {
<View>
{!reviewOpenIdConfiguration && (
<>
- <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
+ <View
+ style={{
+ flexDirection: 'row',
+ justifyContent: 'flex-end',
+ marginTop: 5,
+ gap: '1rem',
+ }}
+ >
+ {warnMasterCreation && (
+ <ResponsiveInput
+ autoFocus={true}
+ placeholder={t('Enter server password')}
+ type="password"
+ onChangeValue={newValue => {
+ setFirstLoginPassword(newValue);
+ }}
+ style={{ flex: 1 }}
+ />
+ )}
<Button
variant="primary"
- style={{
- padding: 10,
- fontSize: 14,
- width: 170,
- marginTop: 5,
- }}
onPress={onSubmitOpenId}
+ style={
+ warningBackground && {
+ padding: 6,
+ fontSize: 14,
+ width: 170,
+ }
+ }
+ isDisabled={firstLoginPassword === '' && warnMasterCreation}
>
- <Trans>Sign in with OpenID</Trans>
+ {warnMasterCreation ? (
+ <Trans>Start using OpenID</Trans>
+ ) : (
+ <Trans>Sign in with OpenID</Trans>
+ )}
</Button>
</View>
{warnMasterCreation && (
@@ -150,8 +185,24 @@ function OpenIdLogin({ setError }) {
</label>
<Button
variant="bare"
- onPress={() => setReviewOpenIdConfiguration(true)}
- style={{ marginTop: 5 }}
+ isDisabled={firstLoginPassword === '' && warnMasterCreation}
+ onPress={() => {
+ send('get-openid-config', {
+ password: firstLoginPassword,
+ }).then(config => {
+ if ('error' in config) {
+ setError(config.error);
+ } else if ('openId' in config) {
+ setError(null);
+ setOpenIdConfig(config.openId);
+ setReviewOpenIdConfiguration(true);
+ }
+ });
+ }}
+ style={{
+ marginTop: 5,
+ ...(isNarrowWidth ? { padding: 10 } : null),
+ }}
>
<Trans>Review OpenID configuration</Trans>
</Button>
@@ -160,22 +211,42 @@ function OpenIdLogin({ setError }) {
</>
)}
{reviewOpenIdConfiguration && (
- <OpenIdForm
- loadData={true}
- otherButtons={[
- <Button
- key="cancel"
- variant="bare"
- style={{ marginRight: 10 }}
- onPress={() => setReviewOpenIdConfiguration(false)}
- >
- <Trans>Cancel</Trans>
- </Button>,
- ]}
- onSetOpenId={async config => {
- onSetOpenId(config);
- }}
- />
+ <View style={{ marginTop: 20 }}>
+ <Text
+ style={{
+ ...styles.verySmallText,
+ color: theme.pageTextLight,
+ fontWeight: 'bold ',
+ width: '100%',
+ textAlign: 'center',
+ }}
+ >
+ <Trans>Review OpenID configuration</Trans>
+ </Text>
+ <OpenIdForm
+ openIdData={openIdConfig}
+ otherButtons={[
+ <Button
+ key="cancel"
+ variant="bare"
+ style={{
+ marginRight: 10,
+ ...(isNarrowWidth && { padding: 10 }),
+ }}
+ onPress={() => {
+ setReviewOpenIdConfiguration(false);
+ setOpenIdConfig(null);
+ setFirstLoginPassword('');
+ }}
+ >
+ <Trans>Cancel</Trans>
+ </Button>,
+ ]}
+ onSetOpenId={async config => {
+ onSetOpenId(config);
+ }}
+ />
+ </View>
)}
</View>
);
@@ -211,6 +282,7 @@ function HeaderLogin({ error }) {
export function Login() {
const { t } = useTranslation();
+ const { isNarrowWidth } = useResponsive();
const dispatch = useDispatch();
const defaultLoginMethod = useLoginMethod();
@@ -219,6 +291,8 @@ export function Login() {
const [error, setError] = useState(null);
const { checked } = useBootstrapped();
const loginMethods = useAvailableLoginMethods();
+ const loginMethodRef = useRef<HTMLButtonElement>(null);
+ const [loginMethodMenuOpen, setLoginMethodMenuOpen] = useState(false);
useEffect(() => {
setMethod(defaultLoginMethod);
@@ -285,24 +359,60 @@ export function Login() {
</Text>
)}
+ {method === 'password' && (
+ <PasswordLogin setError={setError} dispatch={dispatch} />
+ )}
+
+ {method === 'openid' && <OpenIdLogin setError={setError} />}
+
+ {method === 'header' && <HeaderLogin error={error} />}
+
{loginMethods?.length > 1 && (
<View style={{ marginTop: 10 }}>
- <Label
+ <View
style={{
- ...styles.verySmallText,
- color: theme.pageTextLight,
- paddingTop: 5,
+ width: '100%',
+ flexDirection: 'row',
+ justifyContent: 'end',
}}
- title={t('Select the login method')}
- />
- <Select
- value={method}
- onChange={newValue => {
- setError(null);
- setMethod(newValue);
+ >
+ <Button
+ variant="bare"
+ ref={loginMethodRef}
+ onPress={() => setLoginMethodMenuOpen(true)}
+ style={{
+ ...styles.verySmallText,
+ color: theme.pageTextLight,
+ paddingTop: 5,
+ width: 'fit-content',
+ ...(isNarrowWidth ? { padding: 10 } : null),
+ }}
+ >
+ <Trans>Select the login method</Trans>{' '}
+ <SvgCheveronDown width={12} height={12} />
+ </Button>
+ </View>
+ <Popover
+ triggerRef={loginMethodRef}
+ onOpenChange={value => {
+ setLoginMethodMenuOpen(value);
}}
- options={loginMethods?.map(m => [m.method, m.displayName])}
- />
+ isOpen={loginMethodMenuOpen}
+ >
+ <Menu
+ items={loginMethods
+ ?.filter(f => f.method !== method)
+ .map(m => ({
+ name: m.method,
+ text: m.displayName,
+ }))}
+ onMenuSelect={selected => {
+ setError(null);
+ setMethod(selected);
+ setLoginMethodMenuOpen(false);
+ }}
+ />
+ </Popover>
</View>
)}
@@ -318,14 +428,6 @@ export function Login() {
{getErrorMessage(error)}
</Text>
)}
-
- {method === 'password' && (
- <PasswordLogin setError={setError} dispatch={dispatch} />
- )}
-
- {method === 'openid' && <OpenIdLogin setError={setError} />}
-
- {method === 'header' && <HeaderLogin error={error} />}
</View>
);
}
diff --git a/packages/desktop-client/src/components/manager/subscribe/OpenIdForm.tsx b/packages/desktop-client/src/components/manager/subscribe/OpenIdForm.tsx
index eacb3070f3..0442aa1545 100644
--- a/packages/desktop-client/src/components/manager/subscribe/OpenIdForm.tsx
+++ b/packages/desktop-client/src/components/manager/subscribe/OpenIdForm.tsx
@@ -3,7 +3,8 @@ import { Trans, useTranslation } from 'react-i18next';
import { useLocation, type Location } from 'react-router-dom';
import { ButtonWithLoading } from '@actual-app/components/button';
-import { Input } from '@actual-app/components/input';
+import { useResponsive } from '@actual-app/components/hooks/useResponsive';
+import { ResponsiveInput } from '@actual-app/components/input';
import { Menu } from '@actual-app/components/menu';
import { Select } from '@actual-app/components/select';
import { Stack } from '@actual-app/components/stack';
@@ -12,12 +13,8 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { addNotification } from 'loot-core/client/notifications/notificationsSlice';
-import { send } from 'loot-core/platform/client/fetch';
-import { type Handlers } from 'loot-core/types/handlers';
import { type OpenIdConfig } from 'loot-core/types/models';
-import { useDispatch } from '../../../redux';
import { Link } from '../../common/Link';
import { FormField, FormLabel } from '../../forms';
import { useServerURL } from '../../ServerContext';
@@ -29,7 +26,7 @@ type OnProviderChangeCallback = (provider: OpenIdProviderOption) => void;
type OpenIdFormProps = {
onSetOpenId: OpenIdCallback;
otherButtons?: ReactNode[];
- loadData?: boolean;
+ openIdData?: OpenIdConfig;
};
type OpenIdProviderOption = {
@@ -49,10 +46,10 @@ type OpenIdProviderOption = {
export function OpenIdForm({
onSetOpenId,
otherButtons,
- loadData,
+ openIdData,
}: OpenIdFormProps) {
const { t } = useTranslation();
- const dispatch = useDispatch();
+ const { isNarrowWidth } = useResponsive();
const [issuer, setIssuer] = useState('');
const [clientId, setClientId] = useState('');
const [clientSecret, setClientSecret] = useState('');
@@ -68,33 +65,13 @@ export function OpenIdForm({
const [loading, setLoading] = useState(false);
useEffect(() => {
- if (loadData) {
- send('get-openid-config').then(
- (config: Awaited<ReturnType<Handlers['get-openid-config']>>) => {
- if (!config) return;
-
- if ('error' in config) {
- dispatch(
- addNotification({
- notification: {
- type: 'error',
- id: 'error',
- title: t('Error getting OpenID config'),
- sticky: true,
- message: config.error,
- },
- }),
- );
- } else if ('openId' in config) {
- setProviderName(config?.openId?.selectedProvider ?? 'other');
- setIssuer(config?.openId?.issuer ?? '');
- setClientId(config?.openId?.client_id ?? '');
- setClientSecret(config?.openId?.client_secret ?? '');
- }
- },
- );
+ if (openIdData) {
+ setProviderName(openIdData.selectedProvider ?? 'other');
+ setIssuer(openIdData.issuer ?? '');
+ setClientId(openIdData.client_id ?? '');
+ setClientSecret(openIdData.client_secret ?? '');
}
- }, [dispatch, loadData, t]);
+ }, [openIdData]);
const handleProviderChange = (provider: OpenIdProviderOption) => {
if (provider) {
@@ -157,7 +134,7 @@ export function OpenIdForm({
<FormField style={{ flex: 1 }}>
{!submitButtonDisabled && (
<View>
- <Input
+ <ResponsiveInput
id="issuer-field"
type="text"
value={issuer}
@@ -192,7 +169,7 @@ export function OpenIdForm({
<Stack>
<FormField style={{ flex: 1 }}>
<FormLabel title={t('Client ID')} htmlFor="clientid-field" />
- <Input
+ <ResponsiveInput
type="text"
id="clientid-field"
value={clientId}
@@ -212,7 +189,7 @@ export function OpenIdForm({
</FormField>
<FormField style={{ flex: 1 }}>
<FormLabel title={t('Client secret')} htmlFor="clientsecret-field" />
- <Input
+ <ResponsiveInput
type="text"
id="clientsecret-field"
value={clientSecret}
@@ -241,6 +218,7 @@ export function OpenIdForm({
isLoading={loading}
onPress={onSubmit}
isDisabled={submitButtonDisabled}
+ style={isNarrowWidth ? { padding: 10 } : undefined}
>
OK
</ButtonWithLoading>
@@ -429,6 +407,7 @@ function OpenIdProviderSelector({
defaultValue: string;
}) {
const { t } = useTranslation();
+ const { isNarrowWidth } = useResponsive();
const handleProviderChange = (newValue: string) => {
const selectedProvider = openIdProviders.find(provider =>
@@ -449,6 +428,7 @@ function OpenIdProviderSelector({
defaultLabel={t('Select Provider')}
value={defaultValue}
onChange={handleProviderChange}
+ style={isNarrowWidth ? { padding: 10 } : undefined}
/>
</FormField>
);
diff --git a/packages/loot-core/src/server/main.ts b/packages/loot-core/src/server/main.ts
index c16ff8507e..d4b02dd418 100644
--- a/packages/loot-core/src/server/main.ts
+++ b/packages/loot-core/src/server/main.ts
@@ -868,6 +868,23 @@ handlers['get-openid-config'] = async function () {
}
};
+handlers['enable-openid'] = async function (loginConfig) {
+ try {
+ const userToken = await asyncStorage.getItem('user-token');
+
+ if (!userToken) {
+ return { error: 'unauthorized' };
+ }
+
+ await post(getServer().BASE_SERVER + '/openid/enable', loginConfig, {
+ 'X-ACTUAL-TOKEN': userToken,
+ });
+ } catch (err) {
+ return { error: err.reason || 'network-failure' };
+ }
+ return {};
+};
+
handlers['enable-password'] = async function (loginConfig) {
try {
const userToken = await asyncStorage.getItem('user-token');
@@ -885,18 +902,25 @@ handlers['enable-password'] = async function (loginConfig) {
return {};
};
-handlers['get-openid-config'] = async function () {
+handlers['get-openid-config'] = async function ({ password }) {
try {
- const res = await get(getServer().BASE_SERVER + '/openid/config');
+ const userToken = await asyncStorage.getItem('user-token');
+
+ const res = await post(
+ getServer().BASE_SERVER + '/openid/config',
+ { password },
+ {
+ 'X-ACTUAL-TOKEN': userToken,
+ },
+ );
if (res) {
- const config = JSON.parse(res) as OpenIdConfig;
- return { openId: config };
+ return res as { openId: OpenIdConfig };
}
return null;
} catch (err) {
- return { error: 'config-fetch-failed' };
+ return { error: err.reason };
}
};
diff --git a/packages/loot-core/src/types/server-handlers.d.ts b/packages/loot-core/src/types/server-handlers.d.ts
index c2d1905df4..ab2aa1499d 100644
--- a/packages/loot-core/src/types/server-handlers.d.ts
+++ b/packages/loot-core/src/types/server-handlers.d.ts
@@ -189,7 +189,7 @@ export interface ServerHandlers {
'enable-password': (arg: { password: string }) => Promise<{ error?: string }>;
- 'get-openid-config': () => Promise<
+ 'get-openid-config': (arg: { password: string }) => Promise<
| {
openId: OpenIdConfig;
}
diff --git a/packages/sync-server/src/accounts/openid.js b/packages/sync-server/src/accounts/openid.js
index 188fb771d5..f50c81e83f 100644
--- a/packages/sync-server/src/accounts/openid.js
+++ b/packages/sync-server/src/accounts/openid.js
@@ -9,6 +9,8 @@ import {
} from '../services/user-service.js';
import { TOKEN_EXPIRATION_NEVER } from '../util/validate-user.js';
+import { checkPassword } from './password.js';
+
export async function bootstrapOpenId(configParameter) {
if (!('issuer' in configParameter) && !('discoveryURL' in configParameter)) {
return { error: 'missing-issuer-or-discoveryURL' };
@@ -79,7 +81,10 @@ async function setupOpenIdClient(configParameter) {
return client;
}
-export async function loginWithOpenIdSetup(returnUrl) {
+export async function loginWithOpenIdSetup(
+ returnUrl,
+ firstTimeLoginPassword = '',
+) {
if (!returnUrl) {
return { error: 'return-url-missing' };
}
@@ -88,6 +93,19 @@ export async function loginWithOpenIdSetup(returnUrl) {
}
const accountDb = getAccountDb();
+
+ const { countUsersWithUserName } = accountDb.first(
+ 'SELECT count(*) as countUsersWithUserName FROM users WHERE user_name <> ?',
+ [''],
+ );
+ if (countUsersWithUserName === 0) {
+ const valid = checkPassword(firstTimeLoginPassword);
+
+ if (!valid) {
+ return { error: 'invalid-password' };
+ }
+ }
+
let config = accountDb.first('SELECT extra_data FROM auth WHERE method = ?', [
'openid',
]);
diff --git a/packages/sync-server/src/accounts/password.js b/packages/sync-server/src/accounts/password.js
index 6fa7762a3e..e9061dcb53 100644
--- a/packages/sync-server/src/accounts/password.js
+++ b/packages/sync-server/src/accounts/password.js
@@ -123,3 +123,27 @@ export function changePassword(newPassword) {
]);
return {};
}
+
+export function checkPassword(password) {
+ if (!isValidPassword(password)) {
+ return false;
+ }
+
+ const accountDb = getAccountDb();
+ const { extra_data: passwordHash } =
+ accountDb.first('SELECT extra_data FROM auth WHERE method = ?', [
+ 'password',
+ ]) || {};
+
+ if (!passwordHash) {
+ return false;
+ }
+
+ const confirmed = bcrypt.compareSync(password, passwordHash);
+
+ if (!confirmed) {
+ return false;
+ }
+
+ return true;
+}
diff --git a/packages/sync-server/src/app-account.js b/packages/sync-server/src/app-account.js
index 5bc978856a..bd3a61cfcc 100644
--- a/packages/sync-server/src/app-account.js
+++ b/packages/sync-server/src/app-account.js
@@ -91,7 +91,10 @@ app.post('/login', async (req, res) => {
return;
}
- const { error, url } = await loginWithOpenIdSetup(req.body.return_url);
+ const { error, url } = await loginWithOpenIdSetup(
+ req.body.return_url,
+ req.body.password,
+ );
if (error) {
res.status(400).send({ status: 'error', reason: error });
return;
diff --git a/packages/sync-server/src/app-openid.js b/packages/sync-server/src/app-openid.js
index 65f5d54a50..b5124c2255 100644
--- a/packages/sync-server/src/app-openid.js
+++ b/packages/sync-server/src/app-openid.js
@@ -5,6 +5,7 @@ import {
isValidRedirectUrl,
loginWithOpenIdFinalize,
} from './accounts/openid.js';
+import { checkPassword } from './accounts/password.js';
import * as UserService from './services/user-service.js';
import {
errorMiddleware,
@@ -56,7 +57,7 @@ app.post('/disable', validateSessionMiddleware, async (req, res) => {
res.send({ status: 'ok' });
});
-app.get('/config', async (req, res) => {
+app.post('/config', async (req, res) => {
const { cnt: ownerCount } = UserService.getOwnerCount() || {};
if (ownerCount > 0) {
@@ -64,6 +65,11 @@ app.get('/config', async (req, res) => {
return;
}
+ if (!checkPassword(req.body.password)) {
+ res.status(400).send({ status: 'error', reason: 'invalid-password' });
+ return;
+ }
+
const auth = UserService.getOpenIDConfig();
if (!auth) {
@@ -75,7 +81,7 @@ app.get('/config', async (req, res) => {
try {
const openIdConfig = JSON.parse(auth.extra_data);
- res.send({ openId: openIdConfig });
+ res.send({ status: 'ok', data: { openId: openIdConfig } });
} catch (error) {
res
.status(500)
diff --git a/upcoming-release-notes/4446.md b/upcoming-release-notes/4446.md
new file mode 100644
index 0000000000..94c18180c5
--- /dev/null
+++ b/upcoming-release-notes/4446.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [lelemm]
+---
+
+OpenID first login changed to confirm password