feat: auth, first-run setup, login

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
YugonitoandClaude Opus 5.5 committed 2026-10-27 18:12:41 +01:00
1 parent d722c0034c
commit 23f3192cd0
28 files changed
+648 -160

No files matched your search

+30
View File
@@ -27,6 +27,7 @@
"@types/react-dom": "^19", "@types/react-dom": "^19",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "15.5.28", "eslint-config-next": "15.5.28",
"playwright": "^1.64.1",
"tailwindcss": "^4", "tailwindcss": "^4",
"tsx": "^4.23.15", "tsx": "^4.23.15",
"typescript": "^5", "typescript": "^5",
@@ -6808,6 +6809,35 @@
"integrity": "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA==", "integrity": "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/playwright": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz",
"integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.64.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",
"integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/possible-typed-array-names": { "node_modules/possible-typed-array-names": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
+1
View File
@@ -31,6 +31,7 @@
"@types/react-dom": "^19", "@types/react-dom": "^19",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "15.5.28", "eslint-config-next": "15.5.28",
"playwright": "^1.64.1",
"tailwindcss": "^4", "tailwindcss": "^4",
"tsx": "^4.23.15", "tsx": "^4.23.15",
"typescript": "^5", "typescript": "^5",
-1
View File
@@ -1 +0,0 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

Before

Width:  |  Height:  |  Size: 391 B

-1
View File
@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

-1
View File
@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

Before

Width:  |  Height:  |  Size: 128 B

-1
View File
@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

Before

Width:  |  Height:  |  Size: 385 B

+26
View File
@@ -0,0 +1,26 @@
// Réinitialise le mot de passe d'un compte : node dist/reset-password.js <identifiant> <nouveau mot de passe>
import bcrypt from "bcryptjs";
import { PrismaClient } from "@prisma/client";
async function main() {
const [login, password] = process.argv.slice(2);
if (!login || !password || password.length < 8) {
console.error("Usage : reset-password <identifiant> <nouveau mot de passe (8 caractères min.)>");
process.exit(1);
}
const prisma = new PrismaClient();
try {
const user = await prisma.user.update({
where: { login: login.toLowerCase() },
data: { passwordHash: await bcrypt.hash(password, 10) },
});
console.log(`Mot de passe de ${user.firstName} (${user.login}) mis à jour.`);
} catch {
console.error(`Aucun compte avec l'identifiant « ${login} ».`);
process.exitCode = 1;
} finally {
await prisma.$disconnect();
}
}
main();
+12
View File
@@ -0,0 +1,12 @@
import { requireUser } from "@/server/auth";
import { logoutAction } from "@/server/actions/auth";
export default async function DashboardPage() {
const user = await requireUser();
return (
<main className="p-8">
<p>Bonjour {user.firstName}</p>
<form action={logoutAction}><button>Déconnexion</button></form>
</main>
);
}
+12
View File
@@ -0,0 +1,12 @@
import { Logo } from "@/components/Logo";
export default function PublicLayout({ children }: { children: React.ReactNode }) {
return (
<main className="flex min-h-dvh flex-col items-center justify-center px-4 py-10">
<div className="mb-6">
<Logo />
</div>
{children}
</main>
);
}
+28
View File
@@ -0,0 +1,28 @@
"use client";
import { useActionState } from "react";
import { loginAction } from "@/server/actions/auth";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { Field, FormError, Input } from "@/components/ui/Field";
export function LoginForm() {
const [state, action, pending] = useActionState(loginAction, { error: null });
return (
<Card className="w-full max-w-sm p-6 shadow-sm">
<h1 className="mb-5 text-xl font-bold">Connexion</h1>
<form action={action} className="space-y-4">
<Field label="Identifiant">
<Input name="login" defaultValue={state.values?.login} autoComplete="username" autoCapitalize="none" required autoFocus />
</Field>
<Field label="Mot de passe">
<Input name="password" type="password" autoComplete="current-password" required />
</Field>
<FormError message={state.error} />
<Button type="submit" className="w-full" disabled={pending}>
{pending ? "Connexion…" : "Se connecter"}
</Button>
</form>
</Card>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { redirect } from "next/navigation";
import { isSetupDone } from "@/server/auth";
import { LoginForm } from "./LoginForm";
export const dynamic = "force-dynamic";
export default async function LoginPage() {
if (!(await isSetupDone())) redirect("/setup");
return <LoginForm />;
}
+82
View File
@@ -0,0 +1,82 @@
"use client";
import { useActionState, useState } from "react";
import { setupAction } from "@/server/actions/auth";
import { Button } from "@/components/ui/Button";
import { Card, CardLabel } from "@/components/ui/Card";
import { Field, FormError, Input, Select } from "@/components/ui/Field";
function PersonBlock({ i, defaultColor, title, values }: { i: number; defaultColor: string; title: string; values?: Record<string, string> }) {
return (
<div className="space-y-3 rounded-card border border-line p-4">
<CardLabel>{title}</CardLabel>
<div className="flex gap-3">
<Field label="Prénom">
<Input name={`firstName${i}`} defaultValue={values?.[`firstName${i}`]} required />
</Field>
<Field label="Couleur">
<Input name={`color${i}`} type="color" defaultValue={values?.[`color${i}`] ?? defaultColor} className="h-[42px] w-16 p-1" />
</Field>
</div>
<Field label="Identifiant">
<Input name={`login${i}`} defaultValue={values?.[`login${i}`]} autoCapitalize="none" required />
</Field>
<Field label="Mot de passe" hint="8 caractères minimum">
<Input name={`password${i}`} type="password" autoComplete="new-password" required minLength={8} />
</Field>
<Field label="Confirmation">
<Input name={`passwordConfirm${i}`} type="password" autoComplete="new-password" required minLength={8} />
</Field>
</div>
);
}
export function SetupForm() {
const [state, action, pending] = useActionState(setupAction, { error: null });
const [percent, setPercent] = useState("50");
return (
<Card className="w-full max-w-3xl p-6 shadow-sm">
<h1 className="text-xl font-bold">Bienvenue 👋</h1>
<p className="mb-6 mt-1 text-muted">Créons vos deux comptes. Tout reste modifiable ensuite dans les Réglages.</p>
<form action={action} className="space-y-6">
<div className="grid gap-4 md:grid-cols-2">
<PersonBlock i={0} defaultColor="#4f46e5" title="Personne 1" values={state.values} />
<PersonBlock i={1} defaultColor="#db2777" title="Personne 2" values={state.values} />
</div>
<div className="space-y-3 rounded-card border border-line p-4">
<CardLabel>Répartition par défaut des dépenses</CardLabel>
<div className="flex items-center gap-3">
<Input
name="defaultPercentFirst"
value={percent}
onChange={(e) => setPercent(e.target.value)}
inputMode="decimal"
className="w-24"
/>
<span className="text-muted">
% pour la personne 1, {Math.max(0, 100 - (Number(percent.replace(",", ".")) || 0))} % pour la personne 2
</span>
</div>
</div>
<div className="space-y-3 rounded-card border border-line p-4">
<CardLabel>Solde d&apos;ouverture (facultatif)</CardLabel>
<p className="text-muted">Si l&apos;un doit déjà de l&apos;argent à l&apos;autre au démarrage.</p>
<div className="flex flex-wrap gap-3">
<Select name="openingDirection" defaultValue={state.values?.openingDirection} className="w-auto">
<option value="second-owes-first">La personne 2 doit à la personne 1</option>
<option value="first-owes-second">La personne 1 doit à la personne 2</option>
</Select>
<Input name="openingAmount" defaultValue={state.values?.openingAmount} placeholder="0,00 €" inputMode="decimal" className="w-32" />
</div>
</div>
<FormError message={state.error} />
<Button type="submit" className="w-full md:w-auto" disabled={pending}>
{pending ? "Création…" : "Créer le foyer"}
</Button>
</form>
</Card>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { redirect } from "next/navigation";
import { isSetupDone } from "@/server/auth";
import { SetupForm } from "./SetupForm";
export const dynamic = "force-dynamic";
export default async function SetupPage() {
if (await isSetupDone()) redirect("/login");
return <SetupForm />;
}
+26 -20
View File
@@ -1,26 +1,32 @@
@import "tailwindcss"; @import "tailwindcss";
:root { /* Langage visuel de la maquette validée (dashboard-v2.html). */
--background: #ffffff; @theme {
--foreground: #171717; --font-sans: var(--font-inter), system-ui, sans-serif;
} --color-page: #f5f6fa;
--color-card: #ffffff;
@theme inline { --color-line: #e5e7eb;
--color-background: var(--background); --color-line-soft: #f1f2f5;
--color-foreground: var(--foreground); --color-ink: #111827;
--font-sans: var(--font-geist-sans); --color-muted: #6b7280;
--font-mono: var(--font-geist-mono); --color-accent: #4f46e5;
} --color-accent-soft: #eef2ff;
--color-pos: #059669;
@media (prefers-color-scheme: dark) { --color-pos-soft: #ecfdf5;
:root { --color-neg: #dc2626;
--background: #0a0a0a; --color-neg-soft: #fef2f2;
--foreground: #ededed; --color-warn: #d97706;
} --color-warn-soft: #fffbeb;
--color-warn-line: #fde68a;
--radius-card: 14px;
} }
body { body {
background: var(--background); background: var(--color-page);
color: var(--foreground); color: var(--color-ink);
font-family: Arial, Helvetica, sans-serif; font-size: 14px;
}
.tabular {
font-variant-numeric: tabular-nums;
} }
+10 -24
View File
@@ -1,34 +1,20 @@
import type { Metadata } from "next"; import type { Metadata, Viewport } from "next";
import { Geist, Geist_Mono } from "next/font/google"; import { Inter } from "next/font/google";
import "./globals.css"; import "./globals.css";
const geistSans = Geist({ const inter = Inter({ variable: "--font-inter", subsets: ["latin"] });
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Create Next App", title: "Finances du foyer",
description: "Generated by create next app", description: "Suivi des entrées, dépenses et charges partagées du foyer",
}; };
export default function RootLayout({ export const viewport: Viewport = { width: "device-width", initialScale: 1, themeColor: "#f5f6fa" };
children,
}: Readonly<{ export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
children: React.ReactNode;
}>) {
return ( return (
<html lang="en"> <html lang="fr">
<body <body className={`${inter.variable} font-sans antialiased`}>{children}</body>
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html> </html>
); );
} }
-103
View File
@@ -1,103 +0,0 @@
import Image from "next/image";
export default function Home() {
return (
<div className="font-sans grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20">
<main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="font-mono list-inside list-decimal text-sm/6 text-center sm:text-left">
<li className="mb-2 tracking-[-.01em]">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] font-mono font-semibold px-1 py-0.5 rounded">
src/app/page.tsx
</code>
.
</li>
<li className="tracking-[-.01em]">
Save and see your changes instantly.
</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 w-full sm:w-auto md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-[24px] flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org →
</a>
</footer>
</div>
);
}
+8
View File
@@ -0,0 +1,8 @@
export function Logo() {
return (
<div className="flex items-center gap-2 text-base font-bold">
<span className="grid h-7 w-7 place-items-center rounded-lg bg-accent text-sm text-white">€</span>
Finances
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import type { ButtonHTMLAttributes } from "react";
type Variant = "primary" | "ghost" | "danger" | "subtle";
const VARIANTS: Record<Variant, string> = {
primary: "bg-accent text-white hover:bg-indigo-700",
ghost: "border border-line bg-white text-ink hover:bg-gray-50",
danger: "border border-red-200 bg-white text-neg hover:bg-neg-soft",
subtle: "text-accent hover:bg-accent-soft",
};
export function Button({
variant = "primary",
className = "",
...props
}: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: Variant }) {
return (
<button
className={`inline-flex items-center justify-center gap-2 rounded-[10px] px-4 py-2.5 text-sm font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${VARIANTS[variant]} ${className}`}
{...props}
/>
);
}
+9
View File
@@ -0,0 +1,9 @@
import type { HTMLAttributes } from "react";
export function Card({ className = "", ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={`rounded-card border border-line bg-card p-[18px] ${className}`} {...props} />;
}
export function CardLabel({ className = "", ...props }: HTMLAttributes<HTMLDivElement>) {
return <div className={`text-xs font-semibold uppercase tracking-wide text-muted ${className}`} {...props} />;
}
+34
View File
@@ -0,0 +1,34 @@
import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes, TextareaHTMLAttributes } from "react";
/** Largeur pleine par défaut, sauf si l'appelant fixe une largeur. */
const width = (className: string) => (/(^|\s)w-/.test(className) ? "" : "w-full");
const control =
"rounded-[10px] border border-line bg-white px-3 py-2.5 text-sm text-ink outline-none transition focus:border-accent focus:ring-2 focus:ring-accent/20";
export function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {
return (
<label className="block">
<span className="mb-1.5 block text-xs font-semibold text-muted">{label}</span>
{children}
{hint && <span className="mt-1 block text-xs text-muted">{hint}</span>}
</label>
);
}
export function Input({ className = "", ...props }: InputHTMLAttributes<HTMLInputElement>) {
return <input className={`${control} ${width(className)} ${className}`} {...props} />;
}
export function Select({ className = "", ...props }: SelectHTMLAttributes<HTMLSelectElement>) {
return <select className={`${control} ${width(className)} ${className}`} {...props} />;
}
export function Textarea({ className = "", ...props }: TextareaHTMLAttributes<HTMLTextAreaElement>) {
return <textarea className={`${control} ${width(className)} ${className}`} {...props} />;
}
export function FormError({ message }: { message?: string | null }) {
if (!message) return null;
return <p className="rounded-[10px] border border-red-200 bg-neg-soft px-3 py-2 text-sm text-neg">{message}</p>;
}
+12
View File
@@ -0,0 +1,12 @@
import { NextResponse, type NextRequest } from "next/server";
// Garde légère : sans cookie de session, on renvoie vers /login.
// La vérification complète (session valide, installation faite) se fait dans requireUser().
export function middleware(req: NextRequest) {
if (!req.cookies.has("hcl_fin")) return NextResponse.redirect(new URL("/login", req.url));
return NextResponse.next();
}
export const config = {
matcher: ["/((?!login|setup|_next|favicon.ico).*)"],
};
+60
View File
@@ -0,0 +1,60 @@
"use server";
import { redirect } from "next/navigation";
import { createHousehold, getSession, isSetupDone, verifyPassword, type PersonInput } from "@/server/auth";
import { prisma } from "@/server/db";
export type FormState = { error: string | null; values?: Record<string, string> };
/** Valeurs renvoyées au formulaire après une erreur (React réinitialise le formulaire), sans les mots de passe. */
const keepValues = (fd: FormData) =>
Object.fromEntries([...fd.entries()].filter(([k, v]) => typeof v === "string" && !k.startsWith("$") && !k.startsWith("password")).map(([k, v]) => [k, String(v)]));
const str = (fd: FormData, key: string) => String(fd.get(key) ?? "");
function person(fd: FormData, i: number): PersonInput {
return {
firstName: str(fd, `firstName${i}`),
login: str(fd, `login${i}`),
password: str(fd, `password${i}`),
passwordConfirm: str(fd, `passwordConfirm${i}`),
color: str(fd, `color${i}`) || (i === 0 ? "#4f46e5" : "#db2777"),
};
}
export async function setupAction(_prev: FormState, fd: FormData): Promise<FormState> {
if (await isSetupDone()) redirect("/login");
let firstUserId: string;
try {
const { users } = await createHousehold({
people: [person(fd, 0), person(fd, 1)],
defaultPercentFirst: str(fd, "defaultPercentFirst") || "50",
openingAmount: str(fd, "openingAmount"),
openingDirection: str(fd, "openingDirection") === "first-owes-second" ? "first-owes-second" : "second-owes-first",
});
firstUserId = users[0].id;
} catch (e) {
return { error: e instanceof Error ? e.message : "Erreur inattendue.", values: keepValues(fd) };
}
const session = await getSession();
session.userId = firstUserId;
await session.save();
redirect("/");
}
export async function loginAction(_prev: FormState, fd: FormData): Promise<FormState> {
const user = await prisma.user.findUnique({ where: { login: str(fd, "login").trim().toLowerCase() } });
if (!user || !(await verifyPassword(str(fd, "password"), user.passwordHash))) {
return { error: "Identifiant ou mot de passe incorrect.", values: keepValues(fd) };
}
const session = await getSession();
session.userId = user.id;
await session.save();
redirect("/");
}
export async function logoutAction() {
const session = await getSession();
session.destroy();
redirect("/login");
}
+122
View File
@@ -0,0 +1,122 @@
import bcrypt from "bcryptjs";
import { getIronSession, type SessionOptions } from "iron-session";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { cache } from "react";
import { todayParis, fromIsoDate } from "@/lib/dates";
import { decimalFromCents, parseEuro, percentToBp } from "@/domain/money";
import { prisma } from "./db";
export interface SessionData {
userId?: string;
}
const sessionOptions = (): SessionOptions => ({
password: process.env.SESSION_SECRET ?? "",
cookieName: "hcl_fin",
// Accès LAN en HTTP : pas de cookie "secure".
cookieOptions: { secure: false, httpOnly: true, sameSite: "lax", maxAge: 60 * 60 * 24 * 90 },
ttl: 60 * 60 * 24 * 90,
});
export function hashPassword(p: string): Promise<string> {
return bcrypt.hash(p, 10);
}
export function verifyPassword(p: string, h: string): Promise<boolean> {
return bcrypt.compare(p, h);
}
export async function getSession() {
return getIronSession<SessionData>(await cookies(), sessionOptions());
}
export async function isSetupDone(): Promise<boolean> {
return (await prisma.user.count()) > 0;
}
/** Utilisateur connecté, sinon redirection vers l'installation ou la connexion. */
export const requireUser = cache(async () => {
const session = await getSession();
const user = session.userId ? await prisma.user.findUnique({ where: { id: session.userId } }) : null;
if (user) return user;
redirect((await isSetupDone()) ? "/login" : "/setup");
});
export interface PersonInput {
firstName: string;
login: string;
password: string;
passwordConfirm: string;
color: string;
}
export interface HouseholdInput {
people: [PersonInput, PersonInput];
defaultPercentFirst: string;
openingAmount: string;
openingDirection: "second-owes-first" | "first-owes-second";
}
export function validatePassword(password: string, confirm: string): string | null {
if (password.length < 8) return "Le mot de passe doit faire au moins 8 caractères.";
if (password !== confirm) return "Les mots de passe ne correspondent pas.";
return null;
}
/** Création du foyer au premier lancement (comptes, répartition par défaut, solde d'ouverture). */
export async function createHousehold(input: HouseholdInput) {
if (await isSetupDone()) throw new Error("Installation déjà effectuée");
for (const p of input.people) {
if (!p.firstName.trim()) throw new Error("Le prénom est obligatoire.");
if (!/^[a-z0-9._-]+$/i.test(p.login.trim())) throw new Error("Identifiant invalide (lettres, chiffres, . _ -).");
const pwError = validatePassword(p.password, p.passwordConfirm);
if (pwError) throw new Error(pwError);
}
if (input.people[0].login.trim().toLowerCase() === input.people[1].login.trim().toLowerCase()) {
throw new Error("Les deux identifiants doivent être différents.");
}
const firstBp = percentToBp(input.defaultPercentFirst);
if (firstBp === null) throw new Error("Répartition par défaut invalide.");
const opening = input.openingAmount.trim() ? parseEuro(input.openingAmount) : null;
if (input.openingAmount.trim() && opening === null) throw new Error("Montant du solde d'ouverture invalide.");
const hashes = await Promise.all(input.people.map((p) => hashPassword(p.password)));
return prisma.$transaction(async (tx) => {
const users = [];
for (const [i, p] of input.people.entries()) {
users.push(
await tx.user.create({
data: {
firstName: p.firstName.trim(),
login: p.login.trim().toLowerCase(),
passwordHash: hashes[i],
color: p.color,
// createdAt distincts pour garder l'ordre des personnes.
createdAt: new Date(Date.now() + i),
},
}),
);
}
await tx.setting.upsert({
where: { id: 1 },
update: { defaultSplit: { [users[0].id]: firstBp, [users[1].id]: 10000 - firstBp } },
create: { id: 1, defaultSplit: { [users[0].id]: firstBp, [users[1].id]: 10000 - firstBp } },
});
if (opening !== null) {
const [from, to] = input.openingDirection === "second-owes-first" ? [users[1], users[0]] : [users[0], users[1]];
await tx.settlement.create({
data: {
fromUserId: from.id,
toUserId: to.id,
amount: decimalFromCents(opening),
date: fromIsoDate(todayParis()),
note: "Solde d'ouverture",
},
});
}
return { users };
});
}
+9
View File
@@ -0,0 +1,9 @@
import { execSync } from "node:child_process";
import { loadEnv } from "vite";
/** Applique les migrations sur la base de test avant la suite. */
export default function setup() {
const url = loadEnv("test", process.cwd(), "").TEST_DATABASE_URL;
if (!url?.includes("_test")) throw new Error("TEST_DATABASE_URL doit pointer vers une base *_test");
execSync("npx prisma migrate deploy", { stdio: "ignore", env: { ...process.env, DATABASE_URL: url } });
}
+80
View File
@@ -0,0 +1,80 @@
import { beforeEach, describe, expect, it } from "vitest";
import { createHousehold, hashPassword, verifyPassword } from "@/server/auth";
import { prisma } from "@/server/db";
import { resetDb } from "./helpers";
const person = (firstName: string, login: string, color: string) => ({
firstName,
login,
password: "motdepasse",
passwordConfirm: "motdepasse",
color,
});
describe("passwords", () => {
it("verifies the right password and rejects a wrong one", async () => {
const hash = await hashPassword("secret-123");
expect(await verifyPassword("secret-123", hash)).toBe(true);
expect(await verifyPassword("nope", hash)).toBe(false);
});
});
describe("createHousehold", () => {
beforeEach(resetDb);
it("creates both people, the default split and an opening balance", async () => {
const { users } = await createHousehold({
people: [person("Hugues", "hugues", "#4f46e5"), person("Léa", "lea", "#db2777")],
defaultPercentFirst: "60",
openingAmount: "150",
openingDirection: "second-owes-first",
});
expect(await prisma.user.count()).toBe(2);
const setting = await prisma.setting.findUniqueOrThrow({ where: { id: 1 } });
expect(setting.defaultSplit).toEqual({ [users[0].id]: 6000, [users[1].id]: 4000 });
const s = await prisma.settlement.findFirstOrThrow();
expect(s.fromUserId).toBe(users[1].id);
expect(s.toUserId).toBe(users[0].id);
expect(s.amount.toString()).toBe("150");
});
it("skips the opening balance when empty", async () => {
await createHousehold({
people: [person("A", "a", "#4f46e5"), person("B", "b", "#db2777")],
defaultPercentFirst: "50",
openingAmount: "",
openingDirection: "second-owes-first",
});
expect(await prisma.settlement.count()).toBe(0);
});
it("refuses to run twice", async () => {
const input = {
people: [person("A", "a", "#4f46e5"), person("B", "b", "#db2777")] as [ReturnType<typeof person>, ReturnType<typeof person>],
defaultPercentFirst: "50",
openingAmount: "",
openingDirection: "second-owes-first" as const,
};
await createHousehold(input);
await expect(createHousehold(input)).rejects.toThrow("Installation déjà effectuée");
});
it("validates passwords and logins", async () => {
await expect(
createHousehold({
people: [{ ...person("A", "a", "#4f46e5"), password: "court", passwordConfirm: "court" }, person("B", "b", "#db2777")],
defaultPercentFirst: "50",
openingAmount: "",
openingDirection: "second-owes-first",
}),
).rejects.toThrow("Le mot de passe doit faire au moins 8 caractères.");
await expect(
createHousehold({
people: [person("A", "same", "#4f46e5"), person("B", "same", "#db2777")],
defaultPercentFirst: "50",
openingAmount: "",
openingDirection: "second-owes-first",
}),
).rejects.toThrow("Les deux identifiants doivent être différents.");
});
});
+27
View File
@@ -0,0 +1,27 @@
import { prisma } from "@/server/db";
import { seed } from "../../prisma/seed";
const TABLES = [
"OperationSplit", "Operation", "RecurringSplit", "Recurring", "LoanSplit", "Loan",
"Settlement", "Budget", "Category", "Setting", "User",
];
/** Vide la base de test et remet les catégories de départ. */
export async function resetDb() {
if (!process.env.DATABASE_URL?.includes("_test")) throw new Error("resetDb refuse de tourner hors base de test");
await prisma.$executeRawUnsafe("SET FOREIGN_KEY_CHECKS = 0");
for (const t of TABLES) await prisma.$executeRawUnsafe(`TRUNCATE TABLE \`${t}\``);
await prisma.$executeRawUnsafe("SET FOREIGN_KEY_CHECKS = 1");
await seed(prisma);
}
export async function makeUsers() {
const h = await prisma.user.create({ data: { firstName: "H", login: "h", passwordHash: "x", color: "#4f46e5" } });
const c = await prisma.user.create({ data: { firstName: "C", login: "c", passwordHash: "x", color: "#db2777" } });
await prisma.setting.update({ where: { id: 1 }, data: { defaultSplit: { [h.id]: 5000, [c.id]: 5000 } } });
return { h, c };
}
export async function categoryId(name: string) {
return (await prisma.category.findFirstOrThrow({ where: { name } })).id;
}
+17 -8
View File
@@ -1,12 +1,21 @@
import { defineConfig } from "vitest/config"; import { defineConfig } from "vitest/config";
import { loadEnv } from "vite";
import path from "node:path"; import path from "node:path";
export default defineConfig({ export default defineConfig(({ mode }) => {
resolve: { alias: { "@": path.resolve(import.meta.dirname, "src") } }, const env = loadEnv(mode, process.cwd(), "");
test: { return {
environment: "node", resolve: { alias: { "@": path.resolve(import.meta.dirname, "src") } },
include: ["tests/**/*.test.ts"], test: {
// Server tests share one MariaDB test database: run files sequentially. environment: "node",
fileParallelism: false, include: ["tests/**/*.test.ts"],
}, // Les tests serveur partagent une base MariaDB de test : fichiers exécutés en série.
fileParallelism: false,
globalSetup: ["tests/global-setup.ts"],
env: {
DATABASE_URL: env.TEST_DATABASE_URL ?? "",
SESSION_SECRET: env.SESSION_SECRET ?? "test-secret-test-secret-test-secret-xx",
},
},
};
}); });