mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-10-15 01:54:43 +00:00
Refactor authentication and account management with modular UI components (#242)
This commit is contained in:
267
web/frontend/app/features/auth/auth.server.ts
Normal file
267
web/frontend/app/features/auth/auth.server.ts
Normal file
@@ -0,0 +1,267 @@
|
||||
import { createCookieSessionStorage, redirect } from 'react-router';
|
||||
|
||||
const API_BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080';
|
||||
|
||||
export interface AuthTokens {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
userAccountId: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
interface ApiResponse<T> {
|
||||
message: string;
|
||||
payload: T;
|
||||
}
|
||||
|
||||
interface LoginPayload {
|
||||
userAccountId: string;
|
||||
username: string;
|
||||
refreshToken: string;
|
||||
accessToken: string;
|
||||
}
|
||||
|
||||
interface RegistrationPayload extends LoginPayload {
|
||||
confirmationEmailSent: boolean;
|
||||
}
|
||||
|
||||
interface UpdateUsernamePayload {
|
||||
userAccountId: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
interface UpdateEmailPayload {
|
||||
userAccountId: string;
|
||||
email: string;
|
||||
emailConfirmed: boolean;
|
||||
}
|
||||
|
||||
interface UpdateProfilePayload {
|
||||
userAccountId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
dateOfBirth: string;
|
||||
}
|
||||
|
||||
interface UpdatePasswordPayload {
|
||||
userAccountId: string;
|
||||
changedAt: string;
|
||||
}
|
||||
|
||||
export interface UserAccountDetails {
|
||||
username: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
dateOfBirth: string;
|
||||
}
|
||||
|
||||
const sessionStorage = createCookieSessionStorage({
|
||||
cookie: {
|
||||
name: '__session',
|
||||
httpOnly: true,
|
||||
maxAge: 60 * 60 * 24 * 21, // 21 days (matches refresh token)
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
secrets: [process.env.SESSION_SECRET || 'dev-secret-change-me'],
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
},
|
||||
});
|
||||
|
||||
export const getSession = async (request: Request) => {
|
||||
return sessionStorage.getSession(request.headers.get('Cookie'));
|
||||
};
|
||||
|
||||
export const commitSession = async (session: Awaited<ReturnType<typeof getSession>>) => {
|
||||
return sessionStorage.commitSession(session);
|
||||
};
|
||||
|
||||
export const destroySession = async (session: Awaited<ReturnType<typeof getSession>>) => {
|
||||
return sessionStorage.destroySession(session);
|
||||
};
|
||||
|
||||
export const requireAuth = async (request: Request): Promise<AuthTokens> => {
|
||||
const session = await getSession(request);
|
||||
const accessToken = session.get('accessToken');
|
||||
const refreshToken = session.get('refreshToken');
|
||||
|
||||
if (!accessToken || !refreshToken) {
|
||||
throw redirect('/login');
|
||||
}
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
userAccountId: session.get('userAccountId'),
|
||||
username: session.get('username'),
|
||||
};
|
||||
};
|
||||
|
||||
export const getOptionalAuth = async (request: Request): Promise<AuthTokens | null> => {
|
||||
const session = await getSession(request);
|
||||
const accessToken = session.get('accessToken');
|
||||
|
||||
if (!accessToken) return null;
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken: session.get('refreshToken'),
|
||||
userAccountId: session.get('userAccountId'),
|
||||
username: session.get('username'),
|
||||
};
|
||||
};
|
||||
|
||||
export const login = async (username: string, password: string) => {
|
||||
const res = await fetch(`${API_BASE_URL}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(text || `Login failed (${res.status})`);
|
||||
}
|
||||
|
||||
const data: ApiResponse<LoginPayload> = await res.json();
|
||||
return data.payload;
|
||||
};
|
||||
|
||||
export const register = async (body: {
|
||||
username: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
dateOfBirth: string;
|
||||
password: string;
|
||||
}) => {
|
||||
const res = await fetch(`${API_BASE_URL}/api/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(text || `Registration failed (${res.status})`);
|
||||
}
|
||||
|
||||
const data: ApiResponse<RegistrationPayload> = await res.json();
|
||||
return data.payload;
|
||||
};
|
||||
|
||||
export const refreshTokens = async (refreshToken: string) => {
|
||||
const res = await fetch(`${API_BASE_URL}/api/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: { 'X-Refresh-Token': refreshToken },
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error('Token refresh failed');
|
||||
}
|
||||
|
||||
const data: ApiResponse<LoginPayload> = await res.json();
|
||||
return data.payload;
|
||||
};
|
||||
|
||||
export const getUserAccount = async (userAccountId: string): Promise<UserAccountDetails> => {
|
||||
const res = await fetch(`${API_BASE_URL}/api/user/${userAccountId}`);
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(text || `Failed to load account details (${res.status})`);
|
||||
}
|
||||
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const confirmEmail = async (token: string, accessToken: string) => {
|
||||
const res = await fetch(`${API_BASE_URL}/api/auth/confirm?token=${encodeURIComponent(token)}`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(text || `Confirmation failed (${res.status})`);
|
||||
}
|
||||
|
||||
const data: ApiResponse<{ userAccountId: string; confirmedDate: string }> = await res.json();
|
||||
return data.payload;
|
||||
};
|
||||
|
||||
const authorizedRequest = async <T>(
|
||||
path: string,
|
||||
accessToken: string,
|
||||
init: { method: string; body?: unknown },
|
||||
): Promise<T> => {
|
||||
const res = await fetch(`${API_BASE_URL}${path}`, {
|
||||
method: init.method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
...(init.body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: init.body ? JSON.stringify(init.body) : undefined,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(text || `Request failed (${res.status})`);
|
||||
}
|
||||
|
||||
const data: ApiResponse<T> = await res.json();
|
||||
return data.payload;
|
||||
};
|
||||
|
||||
export const updateUsername = async (accessToken: string, newUsername: string) => {
|
||||
return authorizedRequest<UpdateUsernamePayload>('/api/auth/username', accessToken, {
|
||||
method: 'PATCH',
|
||||
body: { newUsername },
|
||||
});
|
||||
};
|
||||
|
||||
export const updateEmail = async (accessToken: string, newEmail: string) => {
|
||||
return authorizedRequest<UpdateEmailPayload>('/api/auth/email', accessToken, {
|
||||
method: 'PATCH',
|
||||
body: { newEmail },
|
||||
});
|
||||
};
|
||||
|
||||
export const updateProfile = async (
|
||||
accessToken: string,
|
||||
firstName: string,
|
||||
lastName: string,
|
||||
dateOfBirth: string,
|
||||
) => {
|
||||
return authorizedRequest<UpdateProfilePayload>('/api/auth/profile', accessToken, {
|
||||
method: 'PATCH',
|
||||
body: { firstName, lastName, dateOfBirth },
|
||||
});
|
||||
};
|
||||
|
||||
export const updatePassword = async (
|
||||
accessToken: string,
|
||||
currentPassword: string,
|
||||
newPassword: string,
|
||||
) => {
|
||||
return authorizedRequest<UpdatePasswordPayload>('/api/auth/password', accessToken, {
|
||||
method: 'PATCH',
|
||||
body: { currentPassword, newPassword },
|
||||
});
|
||||
};
|
||||
|
||||
export const deleteAccount = async (accessToken: string) => {
|
||||
await authorizedRequest<null>('/api/auth/account', accessToken, { method: 'DELETE' });
|
||||
};
|
||||
|
||||
export const createAuthSession = async (payload: LoginPayload, redirectTo: string) => {
|
||||
const session = await sessionStorage.getSession();
|
||||
session.set('accessToken', payload.accessToken);
|
||||
session.set('refreshToken', payload.refreshToken);
|
||||
session.set('userAccountId', payload.userAccountId);
|
||||
session.set('username', payload.username);
|
||||
|
||||
return redirect(redirectTo, {
|
||||
headers: { 'Set-Cookie': await commitSession(session) },
|
||||
});
|
||||
};
|
||||
25
web/frontend/app/features/auth/components/ConfirmFailure.tsx
Normal file
25
web/frontend/app/features/auth/components/ConfirmFailure.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import { Link } from 'react-router';
|
||||
|
||||
interface ConfirmFailureProps {
|
||||
error: string;
|
||||
}
|
||||
|
||||
const ConfirmFailure = ({ error }: ConfirmFailureProps) => (
|
||||
<>
|
||||
<div className="text-error text-6xl">✕</div>
|
||||
<h1 className="card-title text-2xl">Confirmation Failed</h1>
|
||||
<div role="alert" className="alert alert-error alert-soft w-full">
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
<p className="text-base-content/70 text-sm">
|
||||
The confirmation link may have expired (valid for 30 minutes) or already been used.
|
||||
</p>
|
||||
<div className="card-actions w-full pt-2 flex-col gap-2">
|
||||
<Link to="/dashboard" className="btn btn-primary w-full">
|
||||
Back to Dashboard
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
export default ConfirmFailure;
|
||||
26
web/frontend/app/features/auth/components/ConfirmSuccess.tsx
Normal file
26
web/frontend/app/features/auth/components/ConfirmSuccess.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Link } from 'react-router';
|
||||
|
||||
interface ConfirmSuccessProps {
|
||||
confirmedDate: string;
|
||||
}
|
||||
|
||||
const ConfirmSuccess = ({ confirmedDate }: ConfirmSuccessProps) => (
|
||||
<>
|
||||
<div className="text-success text-6xl">✓</div>
|
||||
<h1 className="card-title text-2xl">Email Confirmed!</h1>
|
||||
<p className="text-base-content/70">Your email address has been successfully verified.</p>
|
||||
<div className="bg-base-200 rounded-box w-full p-3 text-sm text-left">
|
||||
<span className="text-base-content/50 text-xs uppercase tracking-widest font-semibold">
|
||||
Confirmed at
|
||||
</span>
|
||||
<p className="font-mono mt-1">{new Date(confirmedDate).toLocaleString()}</p>
|
||||
</div>
|
||||
<div className="card-actions w-full pt-2">
|
||||
<Link to="/dashboard" className="btn btn-primary w-full">
|
||||
Go to Dashboard
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
export default ConfirmSuccess;
|
||||
18
web/frontend/app/features/auth/components/LoginCallout.tsx
Normal file
18
web/frontend/app/features/auth/components/LoginCallout.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
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/60">
|
||||
Back to home
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
export default LoginCallout;
|
||||
44
web/frontend/app/features/auth/components/LoginForm.tsx
Normal file
44
web/frontend/app/features/auth/components/LoginForm.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { BaseSyntheticEvent } 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';
|
||||
|
||||
interface LoginFormProps {
|
||||
onSubmit: (e?: BaseSyntheticEvent) => Promise<Awaited<void> | undefined>;
|
||||
formState: FormState<LoginSchema>;
|
||||
register: UseFormRegister<{ username: string; password: string }>;
|
||||
submitting: boolean;
|
||||
}
|
||||
|
||||
const LoginForm = (props: LoginFormProps) => (
|
||||
<form onSubmit={props.onSubmit} className="space-y-3">
|
||||
<FormField
|
||||
id="username"
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
placeholder="your_username"
|
||||
label="Username"
|
||||
error={props.formState.errors.username?.message}
|
||||
{...props.register('username')}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
placeholder="••••••••"
|
||||
label="Password"
|
||||
error={props.formState.errors.password?.message}
|
||||
{...props.register('password')}
|
||||
/>
|
||||
|
||||
<SubmitButton
|
||||
isSubmitting={props.submitting}
|
||||
idleText="Sign In"
|
||||
submittingText="Signing in..."
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
|
||||
export default LoginForm;
|
||||
@@ -0,0 +1,23 @@
|
||||
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/60 inline-flex items-center gap-1"
|
||||
>
|
||||
<HomeSimpleDoor className="size-4" aria-hidden="true" />
|
||||
Back to home
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
export default RegisterCallout;
|
||||
97
web/frontend/app/features/auth/components/RegisterForm.tsx
Normal file
97
web/frontend/app/features/auth/components/RegisterForm.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import { BaseSyntheticEvent } 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 { RegisterSchema } from '../schemas';
|
||||
|
||||
interface RegisterFormProps {
|
||||
onSubmit: (e?: BaseSyntheticEvent) => Promise<Awaited<void> | undefined>;
|
||||
formState: FormState<RegisterSchema>;
|
||||
register: UseFormRegister<RegisterSchema>;
|
||||
submitting: boolean;
|
||||
}
|
||||
|
||||
const RegisterForm = (props: RegisterFormProps) => (
|
||||
<form onSubmit={props.onSubmit} className="space-y-3">
|
||||
<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')}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<FormField
|
||||
id="firstName"
|
||||
type="text"
|
||||
autoComplete="given-name"
|
||||
placeholder="Jane"
|
||||
label="First Name"
|
||||
error={props.formState.errors.firstName?.message}
|
||||
{...props.register('firstName')}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
id="lastName"
|
||||
type="text"
|
||||
autoComplete="family-name"
|
||||
placeholder="Doe"
|
||||
label="Last Name"
|
||||
error={props.formState.errors.lastName?.message}
|
||||
{...props.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')}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
placeholder="••••••••"
|
||||
label="Password"
|
||||
hint="8+ chars: uppercase, lowercase, digit, special character"
|
||||
error={props.formState.errors.password?.message}
|
||||
{...props.register('password')}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
placeholder="••••••••"
|
||||
label="Confirm Password"
|
||||
error={props.formState.errors.confirmPassword?.message}
|
||||
{...props.register('confirmPassword')}
|
||||
/>
|
||||
|
||||
<SubmitButton
|
||||
isSubmitting={props.submitting}
|
||||
idleText="Create Account"
|
||||
submittingText="Creating account..."
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
|
||||
export default RegisterForm;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useEffect } from 'react';
|
||||
import { showErrorToast } from '../../../components/ui/toast/toast';
|
||||
|
||||
export const useActionErrorToast = (error: string | undefined | null) => {
|
||||
useEffect(() => {
|
||||
if (error) showErrorToast(error);
|
||||
}, [error]);
|
||||
};
|
||||
49
web/frontend/app/features/auth/routes/confirm.tsx
Normal file
49
web/frontend/app/features/auth/routes/confirm.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import { confirmEmail, requireAuth } from '../auth.server';
|
||||
import ConfirmFailure from '../components/ConfirmFailure';
|
||||
import ConfirmSuccess from '../components/ConfirmSuccess';
|
||||
import type { Route } from './+types/confirm';
|
||||
|
||||
export const meta = ({}: Route.MetaArgs) => {
|
||||
return [{ title: 'Confirm Email | The Biergarten App' }];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: Route.LoaderArgs) => {
|
||||
const auth = await requireAuth(request);
|
||||
const url = new URL(request.url);
|
||||
const token = url.searchParams.get('token');
|
||||
|
||||
if (!token) {
|
||||
return { success: false as const, error: 'Missing confirmation token.' };
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await confirmEmail(token, auth.accessToken);
|
||||
return {
|
||||
success: true as const,
|
||||
confirmedDate: payload.confirmedDate,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
success: false as const,
|
||||
error: err instanceof Error ? err.message : 'Confirmation failed.',
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const Confirm = ({ loaderData }: Route.ComponentProps) => {
|
||||
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 items-center text-center gap-4">
|
||||
{loaderData.success ? (
|
||||
<ConfirmSuccess confirmedDate={loaderData.confirmedDate} />
|
||||
) : (
|
||||
<ConfirmFailure error={loaderData.error} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Confirm;
|
||||
88
web/frontend/app/features/auth/routes/login.tsx
Normal file
88
web/frontend/app/features/auth/routes/login.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
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 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';
|
||||
|
||||
export const meta = ({}: Route.MetaArgs) => {
|
||||
return [{ title: 'Login | The Biergarten App' }];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: Route.LoaderArgs) => {
|
||||
const auth = await getOptionalAuth(request);
|
||||
if (auth) throw redirect('/dashboard');
|
||||
return null;
|
||||
};
|
||||
|
||||
export const action = async ({ request }: Route.ActionArgs) => {
|
||||
const formData = await request.formData();
|
||||
const result = loginSchema.safeParse({
|
||||
username: formData.get('username'),
|
||||
password: formData.get('password'),
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
return { error: result.error.issues[0].message };
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await login(result.data.username, result.data.password);
|
||||
return createAuthSession(payload, '/dashboard');
|
||||
} catch (err) {
|
||||
return { error: err instanceof Error ? err.message : 'Login failed.' };
|
||||
}
|
||||
};
|
||||
|
||||
const Login = ({ actionData }: Route.ComponentProps) => {
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const isSubmitting = navigation.state === 'submitting';
|
||||
|
||||
const { register, handleSubmit, formState } = useForm<LoginSchema>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit((data) => {
|
||||
submit(data, { method: 'post' });
|
||||
});
|
||||
|
||||
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>
|
||||
|
||||
{actionData?.error && (
|
||||
<div role="alert" className="alert alert-error alert-soft">
|
||||
<span>{actionData.error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<LoginForm
|
||||
onSubmit={onSubmit}
|
||||
formState={formState}
|
||||
register={register}
|
||||
submitting={isSubmitting}
|
||||
/>
|
||||
|
||||
<RegisterCallout />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
10
web/frontend/app/features/auth/routes/logout.tsx
Normal file
10
web/frontend/app/features/auth/routes/logout.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { redirect } from 'react-router';
|
||||
import { destroySession, getSession } from '../auth.server';
|
||||
import type { Route } from './+types/logout';
|
||||
|
||||
export const loader = async ({ request }: Route.LoaderArgs) => {
|
||||
const session = await getSession(request);
|
||||
return redirect('/', {
|
||||
headers: { 'Set-Cookie': await destroySession(session) },
|
||||
});
|
||||
};
|
||||
106
web/frontend/app/features/auth/routes/register.tsx
Normal file
106
web/frontend/app/features/auth/routes/register.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { redirect, useNavigation, useSubmit } from 'react-router';
|
||||
import { createAuthSession, getOptionalAuth, register } from '../auth.server';
|
||||
import LoginCallout from '../components/LoginCallout';
|
||||
import RegisterForm from '../components/RegisterForm';
|
||||
import { useActionErrorToast } from '../hooks/useActionErrorToast';
|
||||
import { registerSchema, type RegisterSchema } from '../schemas';
|
||||
import type { Route } from './+types/register';
|
||||
|
||||
export const meta = ({}: Route.MetaArgs) => {
|
||||
return [{ title: 'Register | The Biergarten App' }];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: Route.LoaderArgs) => {
|
||||
const auth = await getOptionalAuth(request);
|
||||
if (auth) throw redirect('/dashboard');
|
||||
return null;
|
||||
};
|
||||
|
||||
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'),
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
const fieldErrors = result.error.flatten().fieldErrors as Record<
|
||||
keyof RegisterSchema,
|
||||
string[] | undefined
|
||||
>;
|
||||
return { error: null, 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 payload = await register(body);
|
||||
return createAuthSession(payload, '/dashboard');
|
||||
} catch (err) {
|
||||
return {
|
||||
error: err instanceof Error ? err.message : 'Registration failed.',
|
||||
fieldErrors: null,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const Register = ({ actionData }: Route.ComponentProps) => {
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const isSubmitting = navigation.state === 'submitting';
|
||||
|
||||
const {
|
||||
register: field,
|
||||
handleSubmit,
|
||||
formState,
|
||||
} = useForm<RegisterSchema>({ resolver: zodResolver(registerSchema) });
|
||||
|
||||
const onSubmit = handleSubmit((data) => {
|
||||
submit(data, { method: 'post' });
|
||||
});
|
||||
|
||||
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}
|
||||
/>
|
||||
|
||||
<LoginCallout />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Register;
|
||||
33
web/frontend/app/features/auth/schemas.ts
Normal file
33
web/frontend/app/features/auth/schemas.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const loginSchema = z.object({
|
||||
username: z.string().min(1, 'Username is required'),
|
||||
password: z.string().min(1, 'Password is required'),
|
||||
});
|
||||
|
||||
export type LoginSchema = z.infer<typeof loginSchema>;
|
||||
|
||||
export const registerSchema = z
|
||||
.object({
|
||||
username: z
|
||||
.string()
|
||||
.min(3, 'Username must be at least 3 characters')
|
||||
.max(20, 'Username must be at most 20 characters'),
|
||||
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'),
|
||||
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'),
|
||||
confirmPassword: z.string().min(1, 'Please confirm your password'),
|
||||
})
|
||||
.refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Passwords must match',
|
||||
path: ['confirmPassword'],
|
||||
});
|
||||
|
||||
export type RegisterSchema = z.infer<typeof registerSchema>;
|
||||
Reference in New Issue
Block a user