Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion apps/api/src/features/recipes/recipeRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,27 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
return readRequired(client, id, userId);
});
},
async update(id: string, input: RecipeInput, userId: string) {
async update(
id: string,
input: RecipeInput,
userId: string,
expectedUpdatedAt?: string | null,
) {
return transaction(async (client) => {
await owned(client, id, userId);
// Optimistic concurrency: compare with updatedAt as the API serves
// it (milliseconds, UTC), under the row lock owned() just took.
if (expectedUpdatedAt) {
const current = await client.query<{ updatedAt: string }>(
`SELECT to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "updatedAt" FROM ${t('recipes')} WHERE id=$1`,
[id],
);
if (current.rows[0]!.updatedAt !== expectedUpdatedAt)
throw new GraphQLError(
'This recipe was changed after you opened it.',
{ extensions: { code: 'CONFLICT' } },
);
}
await validateImageReference(
client,
schema,
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/features/recipes/recipeResolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export function createRecipeResolvers(repository: RecipeRepository) {
recipeId(args.id),
validate(recipeInputSchema, args.input),
userId,
validate(z.string().max(40).nullish(), args.expectedUpdatedAt),
);
},
deleteRecipe: (_parent, args, context) =>
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export type MutationCreateRecipeArgs = {
export type MutationUpdateRecipeArgs = {
id: Scalars['ID']['input'];
input: RecipeInput;
expectedUpdatedAt?: InputMaybe<Scalars['String']['input']>;
};

export type MutationDeleteRecipeArgs = {
Expand Down
5 changes: 4 additions & 1 deletion apps/api/src/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ type Query {

type Mutation {
createRecipe(input: RecipeInput!): Recipe!
updateRecipe(id: ID!, input: RecipeInput!): Recipe!
# expectedUpdatedAt: the recipe's updatedAt when the editor loaded it. If
# the recipe has changed since, the update fails with code CONFLICT
# instead of overwriting the newer version.
updateRecipe(id: ID!, input: RecipeInput!, expectedUpdatedAt: String): Recipe!
deleteRecipe(id: ID!): Boolean!
saveRecipe(id: ID!): Recipe!
unsaveRecipe(id: ID!): Boolean!
Expand Down
88 changes: 87 additions & 1 deletion apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import '@testing-library/jest-dom/vitest';
import { render, screen, waitFor } from '@testing-library/react';
import { render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter } from 'react-router-dom';

import { signOutUser } from '../../../features/auth/authApi';
import {
countUserDrafts,
saveDraft,
type RecipeDraftFields,
} from '../../../lib/recipeDrafts';
import { useUnsavedChanges } from '../../../lib/unsavedChanges';
import { useAppStore } from '../../../store';
import SiteHeader from './SiteHeader';

Expand Down Expand Up @@ -128,3 +134,83 @@ describe('SiteHeader authentication', () => {
expect(useAppStore.getState().currentUser).toEqual(authenticatedUser);
});
});

describe('SiteHeader sign-out warning', () => {
const fields = { title: 'Draft' } as RecipeDraftFields;
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
useUnsavedChanges.setState({ unsaved: false });
useAppStore.setState({
currentUser: authenticatedUser,
sessionStatus: 'authenticated',
});
vi.mocked(signOutUser).mockResolvedValue(true);
});

it('warns that drafts and unsaved editor changes will be lost', async () => {
saveDraft(authenticatedUser.id, 'new', { baseUpdatedAt: null, fields });
saveDraft(authenticatedUser.id, 'recipe-1', {
baseUpdatedAt: null,
fields,
});
saveDraft('someone-else', 'new', { baseUpdatedAt: null, fields });
useUnsavedChanges.setState({ unsaved: true });
const user = userEvent.setup();
renderHeader();

await user.click(screen.getByRole('button', { name: 'Sign out' }));
const dialog = screen.getByRole('dialog');
expect(dialog).toHaveTextContent(
'Your unsaved changes in the recipe editor will be lost.',
);
expect(dialog).toHaveTextContent(
'Your 2 saved drafts in this browser will be deleted.',
);
await user.click(
within(dialog).getByRole('button', { name: 'Stay signed in' }),
);
expect(signOutUser).not.toHaveBeenCalled();
expect(countUserDrafts(authenticatedUser.id)).toBe(2);

await user.click(screen.getByRole('button', { name: 'Sign out' }));
await user.click(
within(screen.getByRole('dialog')).getByRole('button', {
name: 'Sign out',
}),
);
await waitFor(() => expect(signOutUser).toHaveBeenCalledOnce());
await waitFor(() => expect(countUserDrafts(authenticatedUser.id)).toBe(0));
expect(countUserDrafts('someone-else')).toBe(1);
// The editor must not ask again about the changes just given up.
expect(useUnsavedChanges.getState().unsaved).toBe(false);
});

it('protects the unsaved changes again when signing out fails', async () => {
useUnsavedChanges.setState({ unsaved: true });
vi.mocked(signOutUser).mockRejectedValueOnce(new Error('Offline'));
const user = userEvent.setup();
renderHeader();
await user.click(screen.getByRole('button', { name: 'Sign out' }));
await user.click(
within(screen.getByRole('dialog')).getByRole('button', {
name: 'Sign out',
}),
);
expect(await screen.findByRole('alert')).toHaveTextContent(
'Unable to sign out',
);
expect(useUnsavedChanges.getState().unsaved).toBe(true);
});

it('names a single draft in the singular', async () => {
saveDraft(authenticatedUser.id, 'new', { baseUpdatedAt: null, fields });
const user = userEvent.setup();
renderHeader();
await user.click(screen.getByRole('button', { name: 'Sign out' }));
expect(screen.getByRole('dialog')).toHaveTextContent(
'Your saved draft in this browser will be deleted.',
);
expect(screen.getByRole('dialog')).not.toHaveTextContent('unsaved');
});
});
55 changes: 54 additions & 1 deletion apps/web/src/components/shell/SiteHeader/SiteHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ import './SiteHeader.css';
import LogoMark from '../../brand/LogoMark/LogoMark';
import LinkButton from '../../ui/LinkButton/LinkButton';
import { Icon } from '../../ui/Icon/Icon';
import ConfirmationDialog from '../../ui/ConfirmationDialog/ConfirmationDialog';
import { countUserDrafts } from '../../../lib/recipeDrafts';
import { useUnsavedChanges } from '../../../lib/unsavedChanges';

const pages = [
{ to: '/', label: 'Explore', icon: HomeIcon },
Expand All @@ -33,14 +36,40 @@ function SiteHeader() {

const closeMenu = () => setMenuOpen(false);

/*
* Signing out deletes this user's drafts (shared computers) and closes
* the recipe editor, so say what would be lost and ask first.
*/
const [signOutLoss, setSignOutLoss] = useState<{
drafts: number;
unsaved: boolean;
} | null>(null);
const requestSignOut = () => {
const drafts = currentUser ? countUserDrafts(currentUser.id) : 0;
const { unsaved } = useUnsavedChanges.getState();
if (drafts || unsaved) setSignOutLoss({ drafts, unsaved });
else void handleSignOut();
};
const confirmSignOut = async () => {
const unsaved = Boolean(signOutLoss?.unsaved);
setSignOutLoss(null);
// The user gave up the editor's changes: the editor must not ask again
// as sign-out closes it. If signing out fails, the editor stays open
// and its changes are protected again.
useUnsavedChanges.setState({ unsaved: false });
if (!(await handleSignOut())) useUnsavedChanges.setState({ unsaved });
};

const handleSignOut = async () => {
setLogoutError('');
try {
await signOut();
closeMenu();
navigate('/');
return true;
} catch {
setLogoutError('Unable to sign out. Please try again.');
return false;
}
};

Expand Down Expand Up @@ -108,7 +137,7 @@ function SiteHeader() {
<span>{currentUser.name}</span>
</span>

<Button size="sm" variant="secondary" onClick={handleSignOut}>
<Button size="sm" variant="secondary" onClick={requestSignOut}>
Sign out
</Button>
</>
Expand Down Expand Up @@ -144,6 +173,30 @@ function SiteHeader() {
</div>
</div>
</div>
<ConfirmationDialog
open={signOutLoss !== null}
title="Sign out?"
description="Signing out removes your work that is only in this browser."
confirmLabel="Sign out"
cancelLabel="Stay signed in"
tone="warning"
onConfirm={() => void confirmSignOut()}
onCancel={() => setSignOutLoss(null)}
>
<ul>
{signOutLoss?.unsaved && (
<li>Your unsaved changes in the recipe editor will be lost.</li>
)}
{Boolean(signOutLoss?.drafts) && (
<li>
{signOutLoss?.drafts === 1
? 'Your saved draft'
: `Your ${signOutLoss?.drafts} saved drafts`}{' '}
in this browser will be deleted.
</li>
)}
</ul>
</ConfirmationDialog>
</header>
);
}
Expand Down
8 changes: 7 additions & 1 deletion apps/web/src/features/auth/RequireAuth.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,14 @@ describe('protected routes with session restoration', () => {
'redirects a logged-out visitor from %s',
async (path) => {
renderApp(path);
// Log in is lazy-loaded; the first import in a test run can take
// over a second on the CI runner.
expect(
await screen.findByRole('heading', { name: 'Log in' }),
await screen.findByRole(
'heading',
{ name: 'Log in' },
{ timeout: 5000 },
),
).toBeInTheDocument();
expect(screen.getByTestId('location')).toHaveTextContent('/login');
},
Expand Down
18 changes: 12 additions & 6 deletions apps/web/src/features/auth/authNavigation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,19 @@ describe('authentication return navigation', () => {
{ from: '//example.com' },
{ from: '/login' },
{ from: '/cookbook\\evil' },
{ from: '/recipes/abc/edit' },
{ from: '/recipes/11111111-1111-4111-8111-111111111111/editor' },
{ from: '/recipes/11111111-1111-4111-8111-111111111111/edit/../../x' },
{ from: '//example.com/recipes/11111111-1111-4111-8111-111111111111/edit' },
{ from: '/recipes/11111111-1111-4111-8111-111111111111' },
])('falls back for unsafe or unsupported state %j', (state) => {
expect(getAuthReturnPath(state)).toBe('/');
});
it.each(['/cookbook?view=saved#recipes', '/recipes/new'])(
'preserves protected destination %s',
(from) => {
expect(getAuthReturnPath({ from })).toBe(from);
},
);
it.each([
'/cookbook?view=saved#recipes',
'/recipes/new',
'/recipes/11111111-1111-4111-8111-111111111111/edit',
])('preserves protected destination %s', (from) => {
expect(getAuthReturnPath({ from })).toBe(from);
});
});
12 changes: 10 additions & 2 deletions apps/web/src/features/auth/authNavigation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
// The recipe editor of one recipe id; nothing else under /recipes/.
const EDIT_ROUTE =
/^\/recipes\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\/edit$/;

// Only return to known protected routes. Never navigate to a supplied origin.
export function getAuthReturnPath(state: unknown): string {
if (typeof state !== 'object' || state === null || !('from' in state))
return '/';
const from = state.from;
if (typeof from !== 'string' || from.includes('\\')) return '/';
const pathname = from.split(/[?#]/)[0];
return pathname === '/cookbook' || pathname === '/recipes/new' ? from : '/';
const pathname = from.split(/[?#]/)[0] ?? '';
return pathname === '/cookbook' ||
pathname === '/recipes/new' ||
EDIT_ROUTE.test(pathname)
? from
: '/';
}
Loading