mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-10-14 17:54:42 +00:00
Compare commits
11 Commits
main
...
feat/auth-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5028a43f4b | ||
|
|
fffbe68dc2 | ||
|
|
e6240bc889 | ||
|
|
4a5abd4639 | ||
|
|
d02f31b55c | ||
|
|
e961ce4042 | ||
|
|
dfb67bcdfa | ||
|
|
0ecc9a830e | ||
|
|
5ac55b8be0 | ||
|
|
19791df6a5 | ||
|
|
0780349a79 |
|
Before Width: | Height: | Size: 203 KiB After Width: | Height: | Size: 203 KiB |
@@ -21,19 +21,26 @@ const FormField = ({
|
||||
}: FormFieldProps) => {
|
||||
return (
|
||||
<Field className={className ?? 'space-y-1'}>
|
||||
<Label htmlFor={inputProps.id} className={labelClassName ?? 'label font-medium'}>
|
||||
<Label
|
||||
htmlFor={inputProps.id}
|
||||
className={labelClassName ?? 'label text-sm font-semibold text-base-content'}
|
||||
>
|
||||
{label}
|
||||
</Label>
|
||||
|
||||
<input
|
||||
{...inputProps}
|
||||
className={inputClassName ?? `input w-full ${error ? 'input-error' : ''}`}
|
||||
className={
|
||||
inputClassName ?? `input h-11 w-full text-base ${error ? 'input-error' : ''}`
|
||||
}
|
||||
/>
|
||||
|
||||
{error ? (
|
||||
<Description className={hintClassName ?? 'label text-error'}>{error}</Description>
|
||||
<Description className={hintClassName ?? 'text-xs text-error'}>{error}</Description>
|
||||
) : hint ? (
|
||||
<Description className={hintClassName ?? 'label'}>{hint}</Description>
|
||||
<Description className={hintClassName ?? 'text-xs text-[var(--color-muted)]'}>
|
||||
{hint}
|
||||
</Description>
|
||||
) : null}
|
||||
</Field>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Disclosure, DisclosureButton, DisclosurePanel } from '@headlessui/react';
|
||||
import { Link } from 'react-router';
|
||||
import { Link, useLocation } from 'react-router';
|
||||
import NavLinks from './NavLinks';
|
||||
import UserMenu from './UserMenu';
|
||||
|
||||
@@ -12,7 +12,12 @@ interface NavbarProps {
|
||||
} | null;
|
||||
}
|
||||
|
||||
const Navbar = ({ auth }: NavbarProps) => (
|
||||
const Navbar = ({ auth }: NavbarProps) => {
|
||||
const { pathname } = useLocation();
|
||||
const onAuthRoute = pathname === '/login' || pathname === '/register';
|
||||
const showAuthActions = !auth && !onAuthRoute;
|
||||
|
||||
return (
|
||||
<Disclosure
|
||||
as="nav"
|
||||
className="sticky top-0 z-50 border-b border-base-300 bg-base-100 shadow-md"
|
||||
@@ -54,10 +59,10 @@ const Navbar = ({ auth }: NavbarProps) => (
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<NavLinks variant="desktop" showRegister={!auth} />
|
||||
<NavLinks variant="desktop" showRegister={showAuthActions} />
|
||||
|
||||
<div className="navbar-end gap-2">
|
||||
{!auth && (
|
||||
{showAuthActions && (
|
||||
<Link
|
||||
to="/register"
|
||||
className="btn btn-ghost btn-sm hidden sm:inline-flex"
|
||||
@@ -78,19 +83,22 @@ const Navbar = ({ auth }: NavbarProps) => (
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
!onAuthRoute && (
|
||||
<Link to="/login" className="btn btn-primary btn-sm">
|
||||
Login
|
||||
</Link>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DisclosurePanel className="border-t border-base-300 bg-base-100 px-4 py-3 lg:hidden">
|
||||
<NavLinks variant="mobile" showRegister={!auth} />
|
||||
<NavLinks variant="mobile" showRegister={showAuthActions} />
|
||||
</DisclosurePanel>
|
||||
</>
|
||||
)}
|
||||
</Disclosure>
|
||||
);
|
||||
};
|
||||
|
||||
export default Navbar;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
interface AuthCardHeadingProps {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
}
|
||||
|
||||
const AuthCardHeading = ({ title, subtitle }: AuthCardHeadingProps) => (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<h1 className="text-[1.875rem]">{title}</h1>
|
||||
<p className="text-[var(--color-muted)]">{subtitle}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default AuthCardHeading;
|
||||
21
web/frontend/app/features/auth/components/AuthErrorAlert.tsx
Normal file
21
web/frontend/app/features/auth/components/AuthErrorAlert.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
interface AuthErrorAlertProps {
|
||||
message: string;
|
||||
/** Per-field messages to list beneath the summary. */
|
||||
details?: readonly string[];
|
||||
}
|
||||
|
||||
const AuthErrorAlert = ({ message, details }: AuthErrorAlertProps) => (
|
||||
<div role="alert" className="alert alert-error alert-soft flex-col items-start">
|
||||
<span>{message}</span>
|
||||
|
||||
{details?.length ? (
|
||||
<ul className="list-inside list-disc text-sm">
|
||||
{details.map((detail) => (
|
||||
<li key={detail}>{detail}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
export default AuthErrorAlert;
|
||||
@@ -0,0 +1,151 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { expect, fireEvent, userEvent, within } from 'storybook/test';
|
||||
import AuthCardHeading from './AuthCardHeading';
|
||||
import AuthErrorAlert from './AuthErrorAlert';
|
||||
import AuthSplitLayout from './AuthSplitLayout';
|
||||
import AuthSwitchPrompt from './AuthSwitchPrompt';
|
||||
import LoginForm from './LoginForm';
|
||||
import RegisterForm from './RegisterForm';
|
||||
import RegisterStepProgress from './RegisterStepProgress';
|
||||
import { useRegisterWizard } from '../hooks/useRegisterWizard';
|
||||
import { loginSchema, type LoginSchema } from '../schemas';
|
||||
|
||||
const noop = () => undefined;
|
||||
|
||||
const authSplitLayoutDescription = `The shared split-screen shell behind /login and /register: a full-bleed bar photo carrying the hero headline, and a solid card holding the page's own heading, form, and switch prompt. The grid splits 6fr/5fr from 820px up and stacks hero over card below it. Both stories compose the real forms, so they show the production layout at any viewport.`;
|
||||
|
||||
const LoginPanel = ({ error }: { error?: string }) => {
|
||||
const form = useForm<LoginSchema>({ resolver: zodResolver(loginSchema) });
|
||||
|
||||
return (
|
||||
<>
|
||||
<AuthCardHeading title="Sign in" subtitle="Sign in to your Biergarten account" />
|
||||
|
||||
{error ? <AuthErrorAlert message={error} /> : null}
|
||||
|
||||
<LoginForm
|
||||
onSubmit={form.handleSubmit(noop)}
|
||||
formState={form.formState}
|
||||
register={form.register}
|
||||
submitting={false}
|
||||
/>
|
||||
|
||||
<AuthSwitchPrompt lead="New to Biergarten?" to="/register" label="Create an account" />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const RegisterPanel = () => {
|
||||
const wizard = useRegisterWizard(noop);
|
||||
|
||||
return (
|
||||
<>
|
||||
<RegisterStepProgress
|
||||
step={wizard.step}
|
||||
totalSteps={wizard.totalSteps}
|
||||
name={wizard.name}
|
||||
/>
|
||||
|
||||
<AuthCardHeading title={wizard.title} subtitle={wizard.subtitle} />
|
||||
|
||||
<RegisterForm wizard={wizard} submitting={false} />
|
||||
|
||||
<AuthSwitchPrompt lead="Already have an account?" to="/login" label="Sign in" />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const meta = {
|
||||
title: 'Layout/AuthSplitLayout',
|
||||
component: AuthSplitLayout,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
layout: 'fullscreen',
|
||||
docs: {
|
||||
description: {
|
||||
component: authSplitLayoutDescription,
|
||||
},
|
||||
},
|
||||
},
|
||||
} satisfies Meta<typeof AuthSplitLayout>;
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
const loginArgs = {
|
||||
headline: 'Good to see you again.',
|
||||
blurb: 'Sign in to pick up where you left off with our partner breweries.',
|
||||
};
|
||||
|
||||
const registerArgs = {
|
||||
headline: 'Pull up a chair.',
|
||||
blurb: 'Create an account to explore partner breweries and their beers.',
|
||||
};
|
||||
|
||||
export const Login: Story = {
|
||||
args: {
|
||||
...loginArgs,
|
||||
children: <LoginPanel />,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByRole('heading', { name: 'Sign in' })).toBeInTheDocument();
|
||||
await expect(canvas.getByRole('button', { name: /show password/i })).toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const LoginWithServerError: Story = {
|
||||
args: {
|
||||
...loginArgs,
|
||||
children: <LoginPanel error="Invalid username or password." />,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByRole('alert')).toHaveTextContent('Invalid username or password.');
|
||||
},
|
||||
};
|
||||
|
||||
export const Register: Story = {
|
||||
args: {
|
||||
...registerArgs,
|
||||
children: <RegisterPanel />,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByText(/step 1 of 3 · account/i)).toBeInTheDocument();
|
||||
await expect(canvas.getByRole('button', { name: /continue/i })).toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const RegisterFinalStep: Story = {
|
||||
args: Register.args,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.type(canvas.getByLabelText(/^username$/i), 'jane_doe');
|
||||
await userEvent.type(canvas.getByLabelText(/^email$/i), 'jane@example.com');
|
||||
await userEvent.click(canvas.getByRole('button', { name: /continue/i }));
|
||||
|
||||
await userEvent.type(await canvas.findByLabelText(/first name/i), 'Jane');
|
||||
await userEvent.type(canvas.getByLabelText(/last name/i), 'Doe');
|
||||
await fireEvent.change(canvas.getByLabelText(/date of birth/i), {
|
||||
target: { value: '2000-01-15' },
|
||||
});
|
||||
await userEvent.click(canvas.getByRole('button', { name: /continue/i }));
|
||||
|
||||
await expect(
|
||||
await canvas.findByRole('heading', { name: 'Secure your account' }),
|
||||
).toBeInTheDocument();
|
||||
await expect(canvas.getByRole('button', { name: /create account/i })).toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const RegisterMobile: Story = {
|
||||
args: Register.args,
|
||||
parameters: {
|
||||
viewport: {
|
||||
defaultViewport: 'mobile1',
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import barBackground from '../../../assets/bar-background.jpg';
|
||||
|
||||
interface AuthSplitLayoutProps {
|
||||
headline: string;
|
||||
blurb: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
const AuthSplitLayout = ({ headline, blurb, children }: AuthSplitLayoutProps) => (
|
||||
<div className="relative flex flex-1 bg-base-200">
|
||||
<div
|
||||
className="absolute inset-0 bg-base-300 bg-cover bg-center"
|
||||
style={{ backgroundImage: `url(${barBackground})` }}
|
||||
/>
|
||||
|
||||
{/* Darkens the photo from the bottom up so the white hero text stays legible */}
|
||||
<div className="pointer-events-none absolute inset-0 bg-[linear-gradient(0deg,#000000b3_30%,#ffffff44_100%)]" />
|
||||
|
||||
<div className="relative mx-auto grid w-full max-w-7xl grid-cols-1 content-between gap-6 min-[820px]:grid-cols-[minmax(0,6fr)_minmax(0,5fr)]">
|
||||
<section className="flex flex-col justify-end gap-4 px-5 pt-8 pb-2 text-white min-[820px]:px-10 min-[820px]:py-14">
|
||||
<h2 className="text-[2rem] leading-[1.1] text-balance [text-shadow:0_2px_24px_#0006] min-[820px]:text-[3.25rem]">
|
||||
{headline}
|
||||
</h2>
|
||||
|
||||
<p className="max-w-[27.5rem] text-base leading-[1.5] min-[820px]:text-[1.1875rem]">
|
||||
{blurb}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<main className="flex items-center justify-center px-4 pt-4 pb-7 min-[820px]:py-10 min-[820px]:pr-10 min-[820px]:pl-0">
|
||||
<div className="flex w-full max-w-[27.5rem] flex-col gap-4 rounded-box bg-base-100 px-5 py-6 shadow-[0_20px_50px_#0005] min-[820px]:p-8">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default AuthSplitLayout;
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Link } from 'react-router';
|
||||
|
||||
interface AuthSwitchPromptProps {
|
||||
lead: string;
|
||||
to: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
const AuthSwitchPrompt = ({ lead, to, label }: AuthSwitchPromptProps) => (
|
||||
<p className="text-center text-[0.9375rem] text-[var(--color-muted)]">
|
||||
{lead}{' '}
|
||||
<Link to={to} className="font-semibold text-secondary hover:text-primary">
|
||||
{label}
|
||||
</Link>
|
||||
</p>
|
||||
);
|
||||
|
||||
export default AuthSwitchPrompt;
|
||||
@@ -1,18 +0,0 @@
|
||||
import { Link } from 'react-router';
|
||||
|
||||
const LoginCallout = () => (
|
||||
<>
|
||||
<div className="divider text-xs">Already have an account?</div>
|
||||
|
||||
<div className="text-center space-y-2">
|
||||
<Link to="/login" className="btn btn-outline btn-sm w-full">
|
||||
Sign in
|
||||
</Link>
|
||||
<Link to="/" className="link link-hover text-sm text-base-content/70">
|
||||
Back to home
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
export default LoginCallout;
|
||||
@@ -1,8 +1,9 @@
|
||||
import { BaseSyntheticEvent } from 'react';
|
||||
import { BaseSyntheticEvent, useState } from 'react';
|
||||
import { FormState, UseFormRegister } from 'react-hook-form';
|
||||
import FormField from '../../../components/ui/forms/FormField';
|
||||
import SubmitButton from '../../../components/ui/forms/SubmitButton';
|
||||
import type { LoginSchema } from '../schemas';
|
||||
import ShowPasswordToggle from './ShowPasswordToggle';
|
||||
|
||||
interface LoginFormProps {
|
||||
onSubmit: (e?: BaseSyntheticEvent) => Promise<Awaited<void> | undefined>;
|
||||
@@ -11,13 +12,15 @@ interface LoginFormProps {
|
||||
submitting: boolean;
|
||||
}
|
||||
|
||||
const LoginForm = (props: LoginFormProps) => (
|
||||
<form onSubmit={props.onSubmit} className="space-y-3">
|
||||
const LoginForm = (props: LoginFormProps) => {
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
|
||||
return (
|
||||
<form onSubmit={props.onSubmit} className="flex flex-col gap-4">
|
||||
<FormField
|
||||
id="username"
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
placeholder="your_username"
|
||||
label="Username"
|
||||
error={props.formState.errors.username?.message}
|
||||
{...props.register('username')}
|
||||
@@ -25,20 +28,26 @@ const LoginForm = (props: LoginFormProps) => (
|
||||
|
||||
<FormField
|
||||
id="password"
|
||||
type="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
autoComplete="current-password"
|
||||
placeholder="••••••••"
|
||||
label="Password"
|
||||
error={props.formState.errors.password?.message}
|
||||
{...props.register('password')}
|
||||
/>
|
||||
|
||||
<ShowPasswordToggle
|
||||
shown={showPassword}
|
||||
onToggle={() => setShowPassword((shown) => !shown)}
|
||||
/>
|
||||
|
||||
<SubmitButton
|
||||
isSubmitting={props.submitting}
|
||||
idleText="Sign In"
|
||||
submittingText="Signing in..."
|
||||
idleText="Sign in"
|
||||
submittingText="Signing in…"
|
||||
className="btn btn-primary min-h-12 w-full"
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginForm;
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { HomeSimpleDoor, UserPlus } from 'iconoir-react';
|
||||
import { Link } from 'react-router';
|
||||
|
||||
const RegisterCallout = () => (
|
||||
<>
|
||||
<div className="divider text-xs">New here?</div>
|
||||
<div className="text-center space-y-2">
|
||||
<Link to="/register" className="btn btn-outline btn-sm w-full gap-2">
|
||||
<UserPlus className="size-4" aria-hidden="true" />
|
||||
Create an account
|
||||
</Link>
|
||||
<Link
|
||||
to="/"
|
||||
className="link link-hover text-sm text-base-content/70 inline-flex items-center gap-1"
|
||||
>
|
||||
<HomeSimpleDoor className="size-4" aria-hidden="true" />
|
||||
Back to home
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
export default RegisterCallout;
|
||||
@@ -1,25 +1,30 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { expect, fireEvent, userEvent, within } from 'storybook/test';
|
||||
import AuthCardHeading from './AuthCardHeading';
|
||||
import RegisterForm from './RegisterForm';
|
||||
import { registerSchema, type RegisterSchema } from '../schemas';
|
||||
import RegisterStepProgress from './RegisterStepProgress';
|
||||
import { useRegisterWizard } from '../hooks/useRegisterWizard';
|
||||
import { type RegisterSchema } from '../schemas';
|
||||
|
||||
const registerFormDescription = `Renders the real \`RegisterForm\` component wired to the real \`registerSchema\` (zod) through the same react-hook-form setup used on the register page, including its cross-field rule that the confirmation must match the password, so these stories validate actual client-side validation behavior rather than a re-implemented form.`;
|
||||
const registerFormDescription = `Renders the real \`RegisterForm\` driven by the real \`useRegisterWizard\` hook, so these stories exercise the production three-step flow: each step validates its own fields through \`registerSchema\` (zod) before the next one opens, entered values survive going back, and only the final step submits.`;
|
||||
|
||||
const RegisterFormHarness = () => {
|
||||
const [submitted, setSubmitted] = useState<RegisterSchema | null>(null);
|
||||
const form = useForm<RegisterSchema>({ resolver: zodResolver(registerSchema) });
|
||||
const wizard = useRegisterWizard(setSubmitted);
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-lg space-y-3 rounded-box bg-base-100 p-6 shadow-lg">
|
||||
<RegisterForm
|
||||
onSubmit={form.handleSubmit((values) => setSubmitted(values))}
|
||||
formState={form.formState}
|
||||
register={form.register}
|
||||
submitting={false}
|
||||
<div className="flex w-full max-w-md flex-col gap-4 rounded-box bg-base-100 p-6 shadow-lg">
|
||||
<RegisterStepProgress
|
||||
step={wizard.step}
|
||||
totalSteps={wizard.totalSteps}
|
||||
name={wizard.name}
|
||||
/>
|
||||
|
||||
<AuthCardHeading title={wizard.title} subtitle={wizard.subtitle} />
|
||||
|
||||
<RegisterForm wizard={wizard} submitting={false} />
|
||||
|
||||
{submitted ? <p data-testid="submit-result">Registered {submitted.username}</p> : null}
|
||||
</div>
|
||||
);
|
||||
@@ -42,75 +47,120 @@ const meta = {
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Empty: Story = {};
|
||||
type Canvas = ReturnType<typeof within>;
|
||||
|
||||
const fillValidRegistration = async (canvas: ReturnType<typeof within>) => {
|
||||
const adultDateOfBirth = '2000-01-15';
|
||||
|
||||
const underageDateOfBirth = () => {
|
||||
const tenYearsAgo = new Date();
|
||||
tenYearsAgo.setFullYear(tenYearsAgo.getFullYear() - 10);
|
||||
return tenYearsAgo.toISOString().slice(0, 10);
|
||||
};
|
||||
|
||||
const completeAccountStep = async (canvas: Canvas) => {
|
||||
await userEvent.type(canvas.getByLabelText(/^username$/i), 'jane_doe');
|
||||
await userEvent.type(canvas.getByLabelText(/^email$/i), 'jane@example.com');
|
||||
await userEvent.click(canvas.getByRole('button', { name: /continue/i }));
|
||||
await canvas.findByLabelText(/first name/i);
|
||||
};
|
||||
|
||||
const completeDetailsStep = async (canvas: Canvas, dateOfBirth = adultDateOfBirth) => {
|
||||
await userEvent.type(canvas.getByLabelText(/first name/i), 'Jane');
|
||||
await userEvent.type(canvas.getByLabelText(/last name/i), 'Doe');
|
||||
await userEvent.type(canvas.getByLabelText(/^email$/i), 'jane@example.com');
|
||||
await fireEvent.change(canvas.getByLabelText(/date of birth/i), {
|
||||
target: { value: '2000-01-15' },
|
||||
target: { value: dateOfBirth },
|
||||
});
|
||||
await userEvent.type(canvas.getByLabelText('Password'), 'StrongPass1!');
|
||||
await userEvent.type(canvas.getByLabelText(/confirm password/i), 'StrongPass1!');
|
||||
await userEvent.click(canvas.getByRole('button', { name: /continue/i }));
|
||||
};
|
||||
|
||||
export const RejectsEmptySubmission: Story = {
|
||||
export const Empty: Story = {};
|
||||
|
||||
export const BlocksAdvanceOnInvalidAccount: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole('button', { name: /create account/i }));
|
||||
await userEvent.click(canvas.getByRole('button', { name: /continue/i }));
|
||||
await expect(
|
||||
canvas.getByText(/username must be at least 3 characters/i),
|
||||
await canvas.findByText(/username must be at least 3 characters/i),
|
||||
).toBeInTheDocument();
|
||||
await expect(canvas.getByText(/first name is required/i)).toBeInTheDocument();
|
||||
await expect(canvas.queryByTestId('submit-result')).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const RejectsInvalidEmail: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await fillValidRegistration(canvas);
|
||||
await userEvent.clear(canvas.getByLabelText(/^email$/i));
|
||||
await userEvent.type(canvas.getByLabelText(/^email$/i), 'jane@example');
|
||||
await userEvent.click(canvas.getByRole('button', { name: /create account/i }));
|
||||
await expect(canvas.getByText(/invalid email address/i)).toBeInTheDocument();
|
||||
await expect(canvas.queryByTestId('submit-result')).not.toBeInTheDocument();
|
||||
await expect(canvas.getByText(/step 1 of 3/i)).toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const RejectsWeakPassword: Story = {
|
||||
export const ClearsFieldErrorOnEdit: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await fillValidRegistration(canvas);
|
||||
await userEvent.clear(canvas.getByLabelText('Password'));
|
||||
await userEvent.type(canvas.getByLabelText('Password'), 'weakpassword');
|
||||
await userEvent.clear(canvas.getByLabelText(/confirm password/i));
|
||||
await userEvent.type(canvas.getByLabelText(/confirm password/i), 'weakpassword');
|
||||
await userEvent.click(canvas.getByRole('button', { name: /create account/i }));
|
||||
await expect(canvas.getByText(/uppercase letter/i)).toBeInTheDocument();
|
||||
await expect(canvas.queryByTestId('submit-result')).not.toBeInTheDocument();
|
||||
await userEvent.click(canvas.getByRole('button', { name: /continue/i }));
|
||||
await canvas.findByText(/username must be at least 3 characters/i);
|
||||
|
||||
await userEvent.type(canvas.getByLabelText(/^username$/i), 'jane_doe');
|
||||
await expect(
|
||||
canvas.queryByText(/username must be at least 3 characters/i),
|
||||
).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const AdvancesToPersonalDetails: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await completeAccountStep(canvas);
|
||||
await expect(canvas.getByRole('heading', { name: 'About you' })).toBeInTheDocument();
|
||||
await expect(canvas.getByText(/step 2 of 3 · personal details/i)).toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const KeepsValuesWhenGoingBack: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await completeAccountStep(canvas);
|
||||
await userEvent.click(canvas.getByRole('button', { name: /back/i }));
|
||||
await expect(await canvas.findByLabelText(/^username$/i)).toHaveValue('jane_doe');
|
||||
await expect(canvas.getByLabelText(/^email$/i)).toHaveValue('jane@example.com');
|
||||
},
|
||||
};
|
||||
|
||||
export const RejectsUnderageDateOfBirth: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await completeAccountStep(canvas);
|
||||
await completeDetailsStep(canvas, underageDateOfBirth());
|
||||
await expect(await canvas.findByText(/at least 19 years old/i)).toBeInTheDocument();
|
||||
await expect(canvas.getByText(/step 2 of 3/i)).toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const RejectsMismatchedConfirmPassword: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await fillValidRegistration(canvas);
|
||||
await userEvent.clear(canvas.getByLabelText(/confirm password/i));
|
||||
await completeAccountStep(canvas);
|
||||
await completeDetailsStep(canvas);
|
||||
await userEvent.type(await canvas.findByLabelText('Password'), 'StrongPass1!');
|
||||
await userEvent.type(canvas.getByLabelText(/confirm password/i), 'Different1!');
|
||||
await userEvent.click(canvas.getByRole('button', { name: /create account/i }));
|
||||
await expect(canvas.getByText(/passwords must match/i)).toBeInTheDocument();
|
||||
await expect(await canvas.findByText(/passwords must match/i)).toBeInTheDocument();
|
||||
await expect(canvas.queryByTestId('submit-result')).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const RevealsBothPasswords: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await completeAccountStep(canvas);
|
||||
await completeDetailsStep(canvas);
|
||||
await userEvent.click(await canvas.findByRole('button', { name: /show password/i }));
|
||||
await expect(canvas.getByLabelText('Password')).toHaveAttribute('type', 'text');
|
||||
await expect(canvas.getByLabelText(/confirm password/i)).toHaveAttribute('type', 'text');
|
||||
},
|
||||
};
|
||||
|
||||
export const AcceptsValidRegistration: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await fillValidRegistration(canvas);
|
||||
await completeAccountStep(canvas);
|
||||
await completeDetailsStep(canvas);
|
||||
await userEvent.type(await canvas.findByLabelText('Password'), 'StrongPass1!');
|
||||
await userEvent.type(canvas.getByLabelText(/confirm password/i), 'StrongPass1!');
|
||||
await userEvent.click(canvas.getByRole('button', { name: /create account/i }));
|
||||
await expect(canvas.getByTestId('submit-result')).toHaveTextContent('jane_doe');
|
||||
await expect(await canvas.findByTestId('submit-result')).toHaveTextContent('jane_doe');
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,97 +1,129 @@
|
||||
import { BaseSyntheticEvent } from 'react';
|
||||
import { FormState, UseFormRegister } from 'react-hook-form';
|
||||
import { Button } from '@headlessui/react';
|
||||
import { useState } from 'react';
|
||||
import FormField from '../../../components/ui/forms/FormField';
|
||||
import SubmitButton from '../../../components/ui/forms/SubmitButton';
|
||||
import type { RegisterSchema } from '../schemas';
|
||||
import type { RegisterWizard } from '../hooks/useRegisterWizard';
|
||||
import { minimumAgeYears } from '../schemas';
|
||||
import ShowPasswordToggle from './ShowPasswordToggle';
|
||||
|
||||
interface RegisterFormProps {
|
||||
onSubmit: (e?: BaseSyntheticEvent) => Promise<Awaited<void> | undefined>;
|
||||
formState: FormState<RegisterSchema>;
|
||||
register: UseFormRegister<RegisterSchema>;
|
||||
wizard: RegisterWizard;
|
||||
submitting: boolean;
|
||||
}
|
||||
|
||||
const RegisterForm = (props: RegisterFormProps) => (
|
||||
<form onSubmit={props.onSubmit} className="space-y-3">
|
||||
const RegisterForm = ({ wizard, submitting }: RegisterFormProps) => {
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const { step, isLastStep, canGoBack, register, formState } = wizard;
|
||||
const { errors } = formState;
|
||||
|
||||
return (
|
||||
<form onSubmit={wizard.onSubmit} className="flex flex-col gap-4" noValidate>
|
||||
{step === 1 && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<FormField
|
||||
id="username"
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
placeholder="your_username"
|
||||
label="Username"
|
||||
hint="3-64 characters, alphanumeric and . _ -"
|
||||
error={props.formState.errors.username?.message}
|
||||
{...props.register('username')}
|
||||
error={errors.username?.message}
|
||||
{...register('username')}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<FormField
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
label="Email"
|
||||
error={errors.email?.message}
|
||||
{...register('email')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="grid grid-cols-1 gap-3.5 min-[420px]:grid-cols-2">
|
||||
<FormField
|
||||
id="firstName"
|
||||
type="text"
|
||||
autoComplete="given-name"
|
||||
placeholder="Jane"
|
||||
label="First Name"
|
||||
error={props.formState.errors.firstName?.message}
|
||||
{...props.register('firstName')}
|
||||
label="First name"
|
||||
error={errors.firstName?.message}
|
||||
{...register('firstName')}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
id="lastName"
|
||||
type="text"
|
||||
autoComplete="family-name"
|
||||
placeholder="Doe"
|
||||
label="Last Name"
|
||||
error={props.formState.errors.lastName?.message}
|
||||
{...props.register('lastName')}
|
||||
label="Last name"
|
||||
error={errors.lastName?.message}
|
||||
{...register('lastName')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder="jane@example.com"
|
||||
label="Email"
|
||||
error={props.formState.errors.email?.message}
|
||||
{...props.register('email')}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
id="dateOfBirth"
|
||||
type="date"
|
||||
label="Date of Birth"
|
||||
hint="Must be 19 years or older"
|
||||
error={props.formState.errors.dateOfBirth?.message}
|
||||
{...props.register('dateOfBirth')}
|
||||
label="Date of birth"
|
||||
hint={`Must be ${minimumAgeYears} years or older.`}
|
||||
error={errors.dateOfBirth?.message}
|
||||
{...register('dateOfBirth')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<FormField
|
||||
id="password"
|
||||
type="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
placeholder="••••••••"
|
||||
label="Password"
|
||||
hint="8+ chars: uppercase, lowercase, digit, special character"
|
||||
error={props.formState.errors.password?.message}
|
||||
{...props.register('password')}
|
||||
error={errors.password?.message}
|
||||
{...register('password')}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
autoComplete="new-password"
|
||||
placeholder="••••••••"
|
||||
label="Confirm Password"
|
||||
error={props.formState.errors.confirmPassword?.message}
|
||||
{...props.register('confirmPassword')}
|
||||
label="Confirm password"
|
||||
error={errors.confirmPassword?.message}
|
||||
{...register('confirmPassword')}
|
||||
/>
|
||||
|
||||
<SubmitButton
|
||||
isSubmitting={props.submitting}
|
||||
idleText="Create Account"
|
||||
submittingText="Creating account..."
|
||||
<ShowPasswordToggle
|
||||
shown={showPassword}
|
||||
onToggle={() => setShowPassword((shown) => !shown)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3">
|
||||
{canGoBack && (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={wizard.back}
|
||||
className="btn btn-outline min-h-12"
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="flex-1">
|
||||
<SubmitButton
|
||||
isSubmitting={submitting}
|
||||
idleText={isLastStep ? 'Create account' : 'Continue'}
|
||||
submittingText="Creating account…"
|
||||
className="btn btn-primary min-h-12 w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
export default RegisterForm;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
interface RegisterStepProgressProps {
|
||||
step: number;
|
||||
totalSteps: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
const RegisterStepProgress = ({ step, totalSteps, name }: RegisterStepProgressProps) => (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex gap-1.5" aria-hidden="true">
|
||||
{Array.from({ length: totalSteps }, (_, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`h-1 flex-1 rounded ${index < step ? 'bg-primary' : 'bg-base-300'}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="text-[0.8125rem] font-semibold text-[var(--color-muted)]">
|
||||
Step {step} of {totalSteps} · {name}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default RegisterStepProgress;
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Button } from '@headlessui/react';
|
||||
|
||||
interface ShowPasswordToggleProps {
|
||||
shown: boolean;
|
||||
onToggle: () => void;
|
||||
}
|
||||
|
||||
const ShowPasswordToggle = ({ shown, onToggle }: ShowPasswordToggleProps) => (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
className="inline-flex min-h-11 items-center self-start text-[0.9375rem] font-semibold text-secondary hover:underline"
|
||||
>
|
||||
{shown ? 'Hide password' : 'Show password'}
|
||||
</Button>
|
||||
);
|
||||
|
||||
export default ShowPasswordToggle;
|
||||
87
web/frontend/app/features/auth/hooks/useRegisterWizard.ts
Normal file
87
web/frontend/app/features/auth/hooks/useRegisterWizard.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useForm, type FieldErrors, type Resolver } from 'react-hook-form';
|
||||
import { earliestStepForFields, lastRegisterStepIndex, registerSteps } from '../registerSteps';
|
||||
import { registerSchema, type RegisterSchema } from '../schemas';
|
||||
|
||||
const resolveRegisterSchema = zodResolver(registerSchema);
|
||||
|
||||
/**
|
||||
* Drives the multi-step register form: one react-hook-form instance spans every
|
||||
* step so values survive going back and forward, and each step validates its own
|
||||
* fields before the next one opens.
|
||||
*/
|
||||
export const useRegisterWizard = (onValid: (values: RegisterSchema) => void) => {
|
||||
const [stepIndex, setStepIndex] = useState(0);
|
||||
|
||||
const currentStep = registerSteps[stepIndex];
|
||||
const isLastStep = stepIndex === lastRegisterStepIndex;
|
||||
|
||||
// Every step submits through `handleSubmit`, so each one has to report only its
|
||||
// own fields: resolve the whole schema, then keep the errors this step owns. The
|
||||
// last step keeps all of them, which is also what runs the password-match
|
||||
// refinement across steps.
|
||||
const resolver: Resolver<RegisterSchema> = async (values, context, options) => {
|
||||
const result = await resolveRegisterSchema(values, context, options);
|
||||
if (isLastStep) return result;
|
||||
|
||||
const errors = Object.fromEntries(
|
||||
Object.entries(result.errors).filter(([name]) =>
|
||||
currentStep.fields.includes(name as keyof RegisterSchema),
|
||||
),
|
||||
) as FieldErrors<RegisterSchema>;
|
||||
|
||||
return Object.keys(errors).length ? { values: {}, errors } : { values, errors: {} };
|
||||
};
|
||||
|
||||
const { register, handleSubmit, formState, setFocus } = useForm<RegisterSchema>({
|
||||
resolver,
|
||||
mode: 'onTouched',
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(
|
||||
(values) => {
|
||||
if (isLastStep) {
|
||||
onValid(values);
|
||||
return;
|
||||
}
|
||||
|
||||
setStepIndex((index) => index + 1);
|
||||
},
|
||||
// The last step validates fields from earlier steps too, so open whichever
|
||||
// step owns the problem rather than reporting it out of sight.
|
||||
(errors: FieldErrors<RegisterSchema>) => {
|
||||
const step = earliestStepForFields(Object.keys(errors) as (keyof RegisterSchema)[]);
|
||||
if (step !== null) setStepIndex(step);
|
||||
},
|
||||
);
|
||||
|
||||
// Move focus into each new step, which otherwise swaps out from under the
|
||||
// keyboard while focus sits on the button that opened it.
|
||||
const isInitialStep = useRef(true);
|
||||
useEffect(() => {
|
||||
if (isInitialStep.current) {
|
||||
isInitialStep.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const [firstField] = registerSteps[stepIndex].fields;
|
||||
if (firstField) setFocus(firstField);
|
||||
}, [stepIndex, setFocus]);
|
||||
|
||||
return {
|
||||
step: stepIndex + 1,
|
||||
totalSteps: registerSteps.length,
|
||||
name: currentStep.name,
|
||||
title: currentStep.title,
|
||||
subtitle: currentStep.subtitle,
|
||||
isLastStep,
|
||||
canGoBack: stepIndex > 0,
|
||||
back: () => setStepIndex((index) => Math.max(index - 1, 0)),
|
||||
onSubmit,
|
||||
register,
|
||||
formState,
|
||||
};
|
||||
};
|
||||
|
||||
export type RegisterWizard = ReturnType<typeof useRegisterWizard>;
|
||||
49
web/frontend/app/features/auth/registerSteps.ts
Normal file
49
web/frontend/app/features/auth/registerSteps.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import type { z } from 'zod';
|
||||
import { registerFields, type RegisterSchema } from './schemas';
|
||||
|
||||
interface RegisterStep {
|
||||
name: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
/** The slice of the register schema this step collects. */
|
||||
schema: z.ZodObject;
|
||||
fields: readonly (keyof RegisterSchema)[];
|
||||
}
|
||||
|
||||
const defineStep = (step: Omit<RegisterStep, 'fields'>): RegisterStep => ({
|
||||
...step,
|
||||
fields: Object.keys(step.schema.shape) as (keyof RegisterSchema)[],
|
||||
});
|
||||
|
||||
export const registerSteps: readonly RegisterStep[] = [
|
||||
defineStep({
|
||||
name: 'Account',
|
||||
title: 'Create your account',
|
||||
subtitle: 'Choose how you will sign in.',
|
||||
schema: registerFields.pick({ username: true, email: true }),
|
||||
}),
|
||||
defineStep({
|
||||
name: 'Personal details',
|
||||
title: 'About you',
|
||||
subtitle: 'Tell us a little about yourself.',
|
||||
schema: registerFields.pick({ firstName: true, lastName: true, dateOfBirth: true }),
|
||||
}),
|
||||
defineStep({
|
||||
name: 'Password',
|
||||
title: 'Secure your account',
|
||||
subtitle: 'Pick a strong password.',
|
||||
schema: registerFields.pick({ password: true, confirmPassword: true }),
|
||||
}),
|
||||
];
|
||||
|
||||
export const lastRegisterStepIndex = registerSteps.length - 1;
|
||||
|
||||
/** The step a field belongs to, so an error can open the step that owns it. */
|
||||
export const stepIndexForField = (field: keyof RegisterSchema) =>
|
||||
registerSteps.findIndex((step) => step.fields.includes(field));
|
||||
|
||||
/** The earliest step owning any of `fields`, or `null` when none of them do. */
|
||||
export const earliestStepForFields = (fields: readonly (keyof RegisterSchema)[]) => {
|
||||
const indexes = fields.map(stepIndexForField).filter((index) => index >= 0);
|
||||
return indexes.length ? Math.min(...indexes) : null;
|
||||
};
|
||||
@@ -1,10 +1,12 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { LogIn } from 'iconoir-react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { redirect, useNavigation, useSubmit } from 'react-router';
|
||||
import { createAuthSession, getOptionalAuth, login } from '../auth.server';
|
||||
import AuthCardHeading from '../components/AuthCardHeading';
|
||||
import AuthErrorAlert from '../components/AuthErrorAlert';
|
||||
import AuthSplitLayout from '../components/AuthSplitLayout';
|
||||
import AuthSwitchPrompt from '../components/AuthSwitchPrompt';
|
||||
import LoginForm from '../components/LoginForm';
|
||||
import RegisterCallout from '../components/RegisterCallout';
|
||||
import { useActionErrorToast } from '../hooks/useActionErrorToast';
|
||||
import { loginSchema, type LoginSchema } from '../schemas';
|
||||
import type { Route } from './+types/login';
|
||||
@@ -54,22 +56,13 @@ const Login = ({ actionData }: Route.ComponentProps) => {
|
||||
useActionErrorToast(actionData?.error);
|
||||
|
||||
return (
|
||||
<div className="hero min-h-screen bg-base-200">
|
||||
<div className="card w-full max-w-md bg-base-100 shadow-xl">
|
||||
<div className="card-body gap-4">
|
||||
<div className="text-center">
|
||||
<h1 className="card-title text-3xl justify-center gap-2">
|
||||
<LogIn className="size-7" aria-hidden="true" />
|
||||
Login
|
||||
</h1>
|
||||
<p className="text-base-content/70">Sign in to your Biergarten account</p>
|
||||
</div>
|
||||
<AuthSplitLayout
|
||||
headline="Good to see you again."
|
||||
blurb="Sign in to pick up where you left off with our partner breweries."
|
||||
>
|
||||
<AuthCardHeading title="Sign in" subtitle="Sign in to your Biergarten account" />
|
||||
|
||||
{actionData?.error && (
|
||||
<div role="alert" className="alert alert-error alert-soft">
|
||||
<span>{actionData.error}</span>
|
||||
</div>
|
||||
)}
|
||||
{actionData?.error && <AuthErrorAlert message={actionData.error} />}
|
||||
|
||||
<LoginForm
|
||||
onSubmit={onSubmit}
|
||||
@@ -78,10 +71,8 @@ const Login = ({ actionData }: Route.ComponentProps) => {
|
||||
submitting={isSubmitting}
|
||||
/>
|
||||
|
||||
<RegisterCallout />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<AuthSwitchPrompt lead="New to Biergarten?" to="/register" label="Create an account" />
|
||||
</AuthSplitLayout>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { redirect, useNavigation, useSubmit } from 'react-router';
|
||||
import { z } from 'zod';
|
||||
import { createAuthSession, getOptionalAuth, register } from '../auth.server';
|
||||
import LoginCallout from '../components/LoginCallout';
|
||||
import AuthCardHeading from '../components/AuthCardHeading';
|
||||
import AuthErrorAlert from '../components/AuthErrorAlert';
|
||||
import AuthSplitLayout from '../components/AuthSplitLayout';
|
||||
import AuthSwitchPrompt from '../components/AuthSwitchPrompt';
|
||||
import RegisterForm from '../components/RegisterForm';
|
||||
import RegisterStepProgress from '../components/RegisterStepProgress';
|
||||
import { useActionErrorToast } from '../hooks/useActionErrorToast';
|
||||
import { registerSchema, type RegisterSchema } from '../schemas';
|
||||
import { useRegisterWizard } from '../hooks/useRegisterWizard';
|
||||
import { registerSchema } from '../schemas';
|
||||
import type { Route } from './+types/register';
|
||||
|
||||
export const meta = ({}: Route.MetaArgs) => {
|
||||
@@ -20,33 +24,14 @@ export const loader = async ({ request }: Route.LoaderArgs) => {
|
||||
|
||||
export const action = async ({ request }: Route.ActionArgs) => {
|
||||
const formData = await request.formData();
|
||||
const result = registerSchema.safeParse({
|
||||
username: formData.get('username'),
|
||||
firstName: formData.get('firstName'),
|
||||
lastName: formData.get('lastName'),
|
||||
email: formData.get('email'),
|
||||
dateOfBirth: formData.get('dateOfBirth'),
|
||||
password: formData.get('password'),
|
||||
confirmPassword: formData.get('confirmPassword'),
|
||||
});
|
||||
const result = registerSchema.safeParse(Object.fromEntries(formData));
|
||||
|
||||
if (!result.success) {
|
||||
const fieldErrors = result.error.flatten().fieldErrors as Record<
|
||||
keyof RegisterSchema,
|
||||
string[] | undefined
|
||||
>;
|
||||
return { error: null, fieldErrors };
|
||||
return { error: null, fieldErrors: z.flattenError(result.error).fieldErrors };
|
||||
}
|
||||
|
||||
try {
|
||||
const body = {
|
||||
username: result.data.username,
|
||||
firstName: result.data.firstName,
|
||||
lastName: result.data.lastName,
|
||||
email: result.data.email,
|
||||
dateOfBirth: result.data.dateOfBirth,
|
||||
password: result.data.password,
|
||||
};
|
||||
const { confirmPassword: _confirmPassword, ...body } = result.data;
|
||||
const payload = await register(body);
|
||||
return createAuthSession(payload, '/dashboard');
|
||||
} catch (err) {
|
||||
@@ -62,44 +47,44 @@ const Register = ({ actionData }: Route.ComponentProps) => {
|
||||
const submit = useSubmit();
|
||||
const isSubmitting = navigation.state === 'submitting';
|
||||
|
||||
const {
|
||||
register: field,
|
||||
handleSubmit,
|
||||
formState,
|
||||
} = useForm<RegisterSchema>({ resolver: zodResolver(registerSchema) });
|
||||
|
||||
const onSubmit = handleSubmit((data) => {
|
||||
const wizard = useRegisterWizard((data) => {
|
||||
submit(data, { method: 'post' });
|
||||
});
|
||||
|
||||
// A request that reached the action without passing client validation, so the
|
||||
// rejected fields may well sit on a step other than the one on screen.
|
||||
const rejectedFields = Object.values(actionData?.fieldErrors ?? {}).flatMap(
|
||||
(messages) => messages ?? [],
|
||||
);
|
||||
|
||||
useActionErrorToast(actionData?.error);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-base-200 flex items-center justify-center p-4">
|
||||
<div className="card w-full max-w-lg bg-base-100 shadow-xl">
|
||||
<div className="card-body gap-4">
|
||||
<div className="text-center">
|
||||
<h1 className="card-title text-3xl justify-center">Register</h1>
|
||||
<p className="text-base-content/70">Create your Biergarten account</p>
|
||||
</div>
|
||||
|
||||
{actionData?.error && (
|
||||
<div role="alert" className="alert alert-error alert-soft">
|
||||
<span>{actionData.error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<RegisterForm
|
||||
onSubmit={onSubmit}
|
||||
formState={formState}
|
||||
register={field}
|
||||
submitting={isSubmitting}
|
||||
<AuthSplitLayout
|
||||
headline="Pull up a chair."
|
||||
blurb="Create an account to explore partner breweries and their beers."
|
||||
>
|
||||
<RegisterStepProgress
|
||||
step={wizard.step}
|
||||
totalSteps={wizard.totalSteps}
|
||||
name={wizard.name}
|
||||
/>
|
||||
|
||||
<LoginCallout />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<AuthCardHeading title={wizard.title} subtitle={wizard.subtitle} />
|
||||
|
||||
{actionData?.error && <AuthErrorAlert message={actionData.error} />}
|
||||
|
||||
{rejectedFields.length > 0 && (
|
||||
<AuthErrorAlert
|
||||
message="Check these details before creating your account."
|
||||
details={rejectedFields}
|
||||
/>
|
||||
)}
|
||||
|
||||
<RegisterForm wizard={wizard} submitting={isSubmitting} />
|
||||
|
||||
<AuthSwitchPrompt lead="Already have an account?" to="/login" label="Sign in" />
|
||||
</AuthSplitLayout>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -7,27 +7,53 @@ export const loginSchema = z.object({
|
||||
|
||||
export type LoginSchema = z.infer<typeof loginSchema>;
|
||||
|
||||
export const registerSchema = z
|
||||
.object({
|
||||
export const minimumAgeYears = 19;
|
||||
|
||||
const isOldEnough = (value: string) => {
|
||||
const dateOfBirth = new Date(value);
|
||||
if (Number.isNaN(dateOfBirth.getTime())) return false;
|
||||
|
||||
const comingOfAge = new Date(
|
||||
dateOfBirth.getFullYear() + minimumAgeYears,
|
||||
dateOfBirth.getMonth(),
|
||||
dateOfBirth.getDate(),
|
||||
);
|
||||
|
||||
return comingOfAge <= new Date();
|
||||
};
|
||||
|
||||
export const registerFields = z.object({
|
||||
username: z
|
||||
.string()
|
||||
.min(3, 'Username must be at least 3 characters')
|
||||
.max(20, 'Username must be at most 20 characters'),
|
||||
.max(64, 'Username must be at most 64 characters')
|
||||
.regex(
|
||||
/^[A-Za-z0-9._-]+$/,
|
||||
'Username can only contain letters, numbers, dots, underscores and hyphens',
|
||||
),
|
||||
firstName: z.string().min(1, 'First name is required'),
|
||||
lastName: z.string().min(1, 'Last name is required'),
|
||||
email: z.string().email('Invalid email address'),
|
||||
dateOfBirth: z.string().min(1, 'Date of birth is required'),
|
||||
email: z.email('Invalid email address'),
|
||||
dateOfBirth: z
|
||||
.string()
|
||||
.min(1, 'Date of birth is required')
|
||||
.refine(isOldEnough, `You must be at least ${minimumAgeYears} years old to register`),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, 'Password must be at least 8 characters')
|
||||
.regex(/[A-Z]/, 'Password must contain an uppercase letter')
|
||||
.regex(/[a-z]/, 'Password must contain a lowercase letter')
|
||||
.regex(/[0-9]/, 'Password must contain a number'),
|
||||
.regex(/[0-9]/, 'Password must contain a number')
|
||||
.regex(/[^A-Za-z0-9]/, 'Password must contain a special character'),
|
||||
confirmPassword: z.string().min(1, 'Please confirm your password'),
|
||||
})
|
||||
.refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Passwords must match',
|
||||
path: ['confirmPassword'],
|
||||
});
|
||||
|
||||
export const registerSchema = registerFields.refine(
|
||||
(data) => data.password === data.confirmPassword,
|
||||
{
|
||||
message: 'Passwords must match',
|
||||
path: ['confirmPassword'],
|
||||
},
|
||||
);
|
||||
|
||||
export type RegisterSchema = z.infer<typeof registerSchema>;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link } from 'react-router';
|
||||
import barBackground from '../assets/bar-background.jpg';
|
||||
import barBackground from '../../../assets/bar-background.jpg';
|
||||
|
||||
const HeroSection = () => (
|
||||
<section className="mx-auto max-w-7xl px-5 pt-18 pb-16">
|
||||
|
||||
@@ -63,12 +63,14 @@ export const Layout = ({ children }: { children: React.ReactNode }) => {
|
||||
const App = ({ loaderData }: Route.ComponentProps) => {
|
||||
const { auth } = loaderData;
|
||||
return (
|
||||
<>
|
||||
<div className="flex min-h-screen flex-col">
|
||||
<Navbar auth={auth} />
|
||||
<ToastProvider />
|
||||
<AiDisclosureDialog />
|
||||
<div className="flex flex-1 flex-col">
|
||||
<Outlet />
|
||||
</>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user