feat: auth, first-run setup, login
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d722c0034c
commit
23f3192cd0
28 files changed
+648
-160
No files matched your search
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 />;
|
||||
}
|
||||
@@ -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'ouverture (facultatif)</CardLabel>
|
||||
<p className="text-muted">Si l'un doit déjà de l'argent à l'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>
|
||||
);
|
||||
}
|
||||
@@ -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
@@ -1,26 +1,32 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
/* Langage visuel de la maquette validée (dashboard-v2.html). */
|
||||
@theme {
|
||||
--font-sans: var(--font-inter), system-ui, sans-serif;
|
||||
--color-page: #f5f6fa;
|
||||
--color-card: #ffffff;
|
||||
--color-line: #e5e7eb;
|
||||
--color-line-soft: #f1f2f5;
|
||||
--color-ink: #111827;
|
||||
--color-muted: #6b7280;
|
||||
--color-accent: #4f46e5;
|
||||
--color-accent-soft: #eef2ff;
|
||||
--color-pos: #059669;
|
||||
--color-pos-soft: #ecfdf5;
|
||||
--color-neg: #dc2626;
|
||||
--color-neg-soft: #fef2f2;
|
||||
--color-warn: #d97706;
|
||||
--color-warn-soft: #fffbeb;
|
||||
--color-warn-line: #fde68a;
|
||||
--radius-card: 14px;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
background: var(--color-page);
|
||||
color: var(--color-ink);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.tabular {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
+10
-24
@@ -1,34 +1,20 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import { Inter } from "next/font/google";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
const inter = Inter({ variable: "--font-inter", subsets: ["latin"] });
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
title: "Finances du foyer",
|
||||
description: "Suivi des entrées, dépenses et charges partagées du foyer",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
export const viewport: Viewport = { width: "device-width", initialScale: 1, themeColor: "#f5f6fa" };
|
||||
|
||||
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
{children}
|
||||
</body>
|
||||
<html lang="fr">
|
||||
<body className={`${inter.variable} font-sans antialiased`}>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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} />;
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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).*)"],
|
||||
};
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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 };
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user