inserimento Login e modifica App.tsx
All checks were successful
Deploy to VPS / build (push) Successful in 22s
Deploy to VPS / deploy (push) Successful in 23s

This commit is contained in:
AV77web 2026-07-13 23:42:26 +02:00
parent 3e1f6743c6
commit 948cdb8765
16 changed files with 1026 additions and 390 deletions

60
package-lock.json generated
View file

@ -9,7 +9,8 @@
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"react": "^19.2.7", "react": "^19.2.7",
"react-dom": "^19.2.7" "react-dom": "^19.2.7",
"react-router-dom": "^7.18.1"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
@ -1306,6 +1307,19 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/cookie": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/cross-spawn": { "node_modules/cross-spawn": {
"version": "7.0.6", "version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@ -2370,6 +2384,44 @@
"react": "^19.2.7" "react": "^19.2.7"
} }
}, },
"node_modules/react-router": {
"version": "7.18.1",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.1.tgz",
"integrity": "sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg==",
"license": "MIT",
"dependencies": {
"cookie": "^1.0.1",
"set-cookie-parser": "^2.6.0"
},
"engines": {
"node": ">=20.0.0"
},
"peerDependencies": {
"react": ">=18",
"react-dom": ">=18"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
}
},
"node_modules/react-router-dom": {
"version": "7.18.1",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.1.tgz",
"integrity": "sha512-KaZh+X/6UtEp28x51AUYZDMg9NGoz2ja3dNHa+ta/tk40vCzKhQ/RypCWBMLbmDr6//E24Vv5uPsrqXFozdkAg==",
"license": "MIT",
"dependencies": {
"react-router": "7.18.1"
},
"engines": {
"node": ">=20.0.0"
},
"peerDependencies": {
"react": ">=18",
"react-dom": ">=18"
}
},
"node_modules/rolldown": { "node_modules/rolldown": {
"version": "1.1.5", "version": "1.1.5",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz",
@ -2420,6 +2472,12 @@
"semver": "bin/semver.js" "semver": "bin/semver.js"
} }
}, },
"node_modules/set-cookie-parser": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
"license": "MIT"
},
"node_modules/shebang-command": { "node_modules/shebang-command": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",

View file

@ -11,7 +11,8 @@
}, },
"dependencies": { "dependencies": {
"react": "^19.2.7", "react": "^19.2.7",
"react-dom": "^19.2.7" "react-dom": "^19.2.7",
"react-router-dom": "^7.18.1"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",

View file

@ -1,184 +1,161 @@
.counter { .layout {
font-size: 16px; min-height: 100vh;
padding: 5px 10px; display: flex;
border-radius: 5px; flex-direction: column;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
} }
.hero { .header {
position: relative; background: #1e3a5f;
color: #fff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.base, .header-inner {
.framework, max-width: 1100px;
.vite {
inset-inline: 0;
margin: 0 auto; margin: 0 auto;
} padding: 0.75rem 1.5rem;
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex; display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center; align-items: center;
gap: 8px; gap: 1.5rem;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap; flex-wrap: wrap;
justify-content: center; }
li { .logo {
flex: 1 1 calc(50% - 8px); color: #fff;
} font-weight: 700;
font-size: 1.1rem;
text-decoration: none;
}
a { .header nav {
display: flex;
gap: 1rem;
flex: 1;
}
.header nav a {
color: #cbd5e1;
text-decoration: none;
font-size: 0.95rem;
}
.header nav a:hover {
color: #fff;
}
.user-bar {
display: flex;
align-items: center;
gap: 1rem;
font-size: 0.9rem;
}
.user-bar button {
background: transparent;
border: 1px solid #94a3b8;
color: #fff;
padding: 0.35rem 0.75rem;
border-radius: 6px;
cursor: pointer;
}
.user-bar button:hover {
background: rgba(255, 255, 255, 0.1);
}
.main {
flex: 1;
max-width: 1100px;
width: 100%; width: 100%;
margin: 0 auto;
padding: 2rem 1.5rem;
}
.page h1 {
margin: 0 0 0.5rem;
color: #1e293b;
}
.auth-page {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center; justify-content: center;
box-sizing: border-box; padding: 2rem;
} background: linear-gradient(135deg, #f0f4f8 0%, #e2e8f0 100%);
}
} }
#spacer { .auth-card {
height: 88px; background: #fff;
border-top: 1px solid var(--border); padding: 2rem;
@media (max-width: 1024px) { border-radius: 12px;
height: 48px; box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
}
}
.ticks {
position: relative;
width: 100%; width: 100%;
max-width: 420px;
&::before, display: flex;
&::after { flex-direction: column;
content: ''; gap: 1rem;
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
} }
.auth-card h1 {
margin: 0;
color: #1e3a5f;
}
.auth-link {
text-align: center;
font-size: 0.9rem;
color: #64748b;
}
label {
display: flex;
flex-direction: column;
gap: 0.35rem;
font-size: 0.9rem;
font-weight: 500;
color: #334155;
}
input {
padding: 0.6rem 0.75rem;
border: 1px solid #cbd5e1;
border-radius: 6px;
font-size: 1rem;
font-family: inherit;
}
input:focus {
outline: 2px solid #3b82f6;
outline-offset: 1px;
}
.btn {
display: inline-block;
padding: 0.6rem 1.2rem;
border-radius: 6px;
font-size: 0.95rem;
font-weight: 500;
text-decoration: none;
border: none;
cursor: pointer;
text-align: center;
}
.btn-primary {
background: #2563eb;
color: #fff;
}
.btn-primary:hover:not(:disabled) {
background: #1d4ed8;
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.error { color: #dc2626; margin: 0; }
.muted { color: #64748b; }
.loading { color: #64748b; font-style: italic; }

View file

@ -1,122 +1,25 @@
import { useState } from 'react' import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import reactLogo from './assets/react.svg' import GuestRoute from "./components/GuestRoute";
import viteLogo from './assets/vite.svg' import Layout from "./components/Layout";
import heroImg from './assets/hero.png' import ProtectedRoute from "./components/ProtectedRoute";
import './App.css' import { AuthProvider } from "./context/AuthContext";
import Dashboard from "./pages/Dashboard";
function App() { import Login from "./pages/Login";
const [count, setCount] = useState(0) import "./App.css";
export default function App() {
return ( return (
<> <AuthProvider>
<section id="center"> <BrowserRouter>
<div className="hero"> <Routes>
<img src={heroImg} className="base" width="170" height="179" alt="" /> <Route path="/login" element={<GuestRoute><Login /></GuestRoute>} />
<img src={reactLogo} className="framework" alt="React logo" /> <Route element={<ProtectedRoute><Layout /></ProtectedRoute>}>
<img src={viteLogo} className="vite" alt="Vite logo" /> <Route path="/dashboard" element={<Dashboard />} />
</div> </Route>
<div> <Route path="/" element={<Navigate to="/login" replace />} />
<h1>Get started</h1> <Route path="*" element={<Navigate to="/login" replace />} />
<p> </Routes>
Edit <code>src/App.tsx</code> and save to test <code>HMR</code> </BrowserRouter>
</p> </AuthProvider>
</div> );
<button
type="button"
className="counter"
onClick={() => setCount((count) => count + 1)}
>
Count is {count}
</button>
</section>
<div className="ticks"></div>
<section id="next-steps">
<div id="docs">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#documentation-icon"></use>
</svg>
<h2>Documentation</h2>
<p>Your questions, answered</p>
<ul>
<li>
<a href="https://vite.dev/" target="_blank">
<img className="logo" src={viteLogo} alt="" />
Explore Vite
</a>
</li>
<li>
<a href="https://react.dev/" target="_blank">
<img className="button-icon" src={reactLogo} alt="" />
Learn more
</a>
</li>
</ul>
</div>
<div id="social">
<svg className="icon" role="presentation" aria-hidden="true">
<use href="/icons.svg#social-icon"></use>
</svg>
<h2>Connect with us</h2>
<p>Join the Vite community</p>
<ul>
<li>
<a href="https://github.com/vitejs/vite" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#github-icon"></use>
</svg>
GitHub
</a>
</li>
<li>
<a href="https://chat.vite.dev/" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#discord-icon"></use>
</svg>
Discord
</a>
</li>
<li>
<a href="https://x.com/vite_js" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#x-icon"></use>
</svg>
X.com
</a>
</li>
<li>
<a href="https://bsky.app/profile/vite.dev" target="_blank">
<svg
className="button-icon"
role="presentation"
aria-hidden="true"
>
<use href="/icons.svg#bluesky-icon"></use>
</svg>
Bluesky
</a>
</li>
</ul>
</div>
</section>
<div className="ticks"></div>
<section id="spacer"></section>
</>
)
} }
export default App

115
src/api/client.ts Normal file
View file

@ -0,0 +1,115 @@
import type {
Ruolo,
Utente,
} from "../types";
const API_URL = import.meta.env.VITE_API_URL ?? "";
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const response = await fetch(`${API_URL}${path}`, {
credentials: "include",
headers: {
"Content-Type": "application/json",
...(options.headers ?? {}),
},
...options,
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(data.error ?? `Errore ${response.status}`);
}
return data as T;
}
export async function fetchHealth(): Promise<{ status: string }> {
return request("/api/health");
}
export async function getCsrfToken(): Promise<string> {
const data = await request<{ csrfToken: string }>("/api/auth/csrf");
return data.csrfToken;
}
export async function login(email: string, password: string): Promise<void> {
const csrfToken = await getCsrfToken();
const body = new URLSearchParams({
csrfToken,
email,
password,
redirect: "false",
});
const response = await fetch(`${API_URL}/api/auth/callback/credentials`, {
method: "POST",
credentials: "include",
redirect: "manual",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Auth-Return-Redirect": "1",
},
body,
});
if (response.type === "opaqueredirect" || response.status === 302) {
throw new Error("Login non riuscito: frontend non aggiornato o configurazione Auth errata");
}
const data = await response.json().catch(() => ({})) as { url?: string };
if (!response.ok || data.url?.includes("error=")) {
throw new Error("Credenziali non valide");
}
}
export async function logout(): Promise<void> {
const csrfToken = await getCsrfToken();
const body = new URLSearchParams({ csrfToken });
await fetch(`${API_URL}/api/auth/signout`, {
method: "POST",
credentials: "include",
redirect: "manual",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Auth-Return-Redirect": "1",
},
body,
});
}
interface MeResponse {
id: number;
email: string;
name: string;
ruolo: Ruolo;
}
export async function getMe(): Promise<Utente> {
const data = await request<MeResponse>("/api/me");
const nameParts = data.name.trim().split(/\s+/);
const nome = nameParts[0] ?? "";
const cognome = nameParts.slice(1).join(" ");
return {
id: data.id,
nome,
cognome,
email: data.email,
ruolo: data.ruolo,
};
}
export async function register(data: {
nome: string;
cognome: string;
email: string;
password: string;
confermaPassword: string;
ruolo: Ruolo;
}): Promise<void> {
await request("/api/utenti/register", {
method: "POST",
body: JSON.stringify(data),
});
}

View file

@ -0,0 +1,11 @@
import { Navigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
export default function GuestRoute({ children }: { children: React.ReactNode }) {
const { user, loading } = useAuth();
if (loading) return <p className="loading">Caricamento...</p>;
if (user) return <Navigate to="/dashboard" replace />;
return <>{children}</>;
}

34
src/components/Layout.tsx Normal file
View file

@ -0,0 +1,34 @@
import { Link, Outlet, useNavigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
export default function Layout() {
const { user, logout } = useAuth();
const navigate = useNavigate();
const handleLogout = async () => {
await logout();
navigate("/login");
};
return (
<div className="layout">
<header className="header">
<div className="header-inner">
<Link to="/dashboard" className="logo">
Esame ITS 24-26
</Link>
<nav>
<Link to="/dashboard">Dashboard</Link>
</nav>
<div className="user-bar">
<span>{user?.nome} {user?.cognome}</span>
<button type="button" onClick={handleLogout}>Esci</button>
</div>
</div>
</header>
<main className="main">
<Outlet />
</main>
</div>
);
}

View file

@ -0,0 +1,27 @@
import { Navigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
import type { Ruolo } from "../types";
export default function ProtectedRoute({
children,
roles,
}: {
children: React.ReactNode;
roles?: Ruolo[];
}) {
const { user, loading } = useAuth();
if (loading) return <p className="loading">Caricamento...</p>;
if (!user) return <Navigate to="/login" replace />;
if (roles && !roles.includes(user.ruolo)) {
return (
<Navigate
to="/dashboard"
replace
state={{ denied: "Non hai i permessi per accedere a questa sezione." }}
/>
);
}
return <>{children}</>;
}

View file

@ -0,0 +1,53 @@
import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from "react";
import { getMe, login as apiLogin, logout as apiLogout } from "../api/client";
import type { Utente } from "../types";
interface AuthContextValue {
user: Utente | null;
loading: boolean;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
refresh: () => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<Utente | null>(null);
const [loading, setLoading] = useState(true);
const refresh = useCallback(async () => {
try {
const me = await getMe();
setUser(me);
} catch {
setUser(null);
}
}, []);
useEffect(() => {
refresh().finally(() => setLoading(false));
}, [refresh]);
const login = async (email: string, password: string) => {
await apiLogin(email, password);
await refresh();
};
const logout = async () => {
await apiLogout();
setUser(null);
};
return (
<AuthContext.Provider value={{ user, loading, login, logout, refresh }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error("useAuth deve essere usato dentro AuthProvider");
return ctx;
}

View file

@ -1,111 +1,21 @@
:root { *,
--text: #6b6375; *::before,
--text-h: #08060d; *::after {
--bg: #fff;
--border: #e5e4e7;
--code-bg: #f4f3ec;
--accent: #aa3bff;
--accent-bg: rgba(170, 59, 255, 0.1);
--accent-border: rgba(170, 59, 255, 0.5);
--social-bg: rgba(244, 243, 236, 0.5);
--shadow:
rgba(0, 0, 0, 0.1) 0 10px 15px -3px, rgba(0, 0, 0, 0.05) 0 4px 6px -2px;
--sans: system-ui, 'Segoe UI', Roboto, sans-serif;
--heading: system-ui, 'Segoe UI', Roboto, sans-serif;
--mono: ui-monospace, Consolas, monospace;
font: 18px/145% var(--sans);
letter-spacing: 0.18px;
color-scheme: light dark;
color: var(--text);
background: var(--bg);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@media (max-width: 1024px) {
font-size: 16px;
}
}
@media (prefers-color-scheme: dark) {
:root {
--text: #9ca3af;
--text-h: #f3f4f6;
--bg: #16171d;
--border: #2e303a;
--code-bg: #1f2028;
--accent: #c084fc;
--accent-bg: rgba(192, 132, 252, 0.15);
--accent-border: rgba(192, 132, 252, 0.5);
--social-bg: rgba(47, 48, 58, 0.5);
--shadow:
rgba(0, 0, 0, 0.4) 0 10px 15px -3px, rgba(0, 0, 0, 0.25) 0 4px 6px -2px;
}
#social .button-icon {
filter: invert(1) brightness(2);
}
}
#root {
width: 1126px;
max-width: 100%;
margin: 0 auto;
text-align: center;
border-inline: 1px solid var(--border);
min-height: 100svh;
display: flex;
flex-direction: column;
box-sizing: border-box; box-sizing: border-box;
} }
body { body {
margin: 0; margin: 0;
font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
background: #f1f5f9;
color: #1e293b;
line-height: 1.5;
} }
h1, #root {
h2 { min-height: 100vh;
font-family: var(--heading);
font-weight: 500;
color: var(--text-h);
} }
h1 { a {
font-size: 56px; color: #2563eb;
letter-spacing: -1.68px;
margin: 32px 0;
@media (max-width: 1024px) {
font-size: 36px;
margin: 20px 0;
}
}
h2 {
font-size: 24px;
line-height: 118%;
letter-spacing: -0.24px;
margin: 0 0 8px;
@media (max-width: 1024px) {
font-size: 20px;
}
}
p {
margin: 0;
}
code,
.counter {
font-family: var(--mono);
display: inline-flex;
border-radius: 4px;
color: var(--text-h);
}
code {
font-size: 15px;
line-height: 135%;
padding: 4px 8px;
background: var(--code-bg);
} }

31
src/pages/Dashboard.tsx Normal file
View file

@ -0,0 +1,31 @@
import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
export default function Dashboard() {
const { user } = useAuth();
const location = useLocation();
const navigate = useNavigate();
const isAdmin = user?.ruolo === "Amministratore";
const [deniedMessage, setDeniedMessage] = useState<string | null>(null);
useEffect(() => {
const denied = (location.state as { denied?: string } | null)?.denied;
if (denied) {
setDeniedMessage(denied);
navigate(location.pathname, { replace: true, state: {} });
}
}, [location, navigate]);
return (
<div className="page">
<h1>Dashboard</h1>
{deniedMessage && <p className="error">{deniedMessage}</p>}
<p>
Benvenuto, <strong>{user?.nome} {user?.cognome}</strong>
</p>
<p className="muted">Ruolo: {isAdmin ? "Amministratore" : "Operatore"}</p>
<p className="muted">Email: {user?.email}</p>
</div>
);
}

46
src/pages/Login.tsx Normal file
View file

@ -0,0 +1,46 @@
import { useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
export default function Login() {
const { login } = useAuth();
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
setError(null);
setLoading(true);
try {
await login(email, password);
navigate("/dashboard");
} catch (err) {
setError(err instanceof Error ? err.message : "Errore di accesso");
} finally {
setLoading(false);
}
};
return (
<div className="auth-page">
<form className="auth-card" onSubmit={handleSubmit}>
<h1>Accedi</h1>
{error && <p className="error">{error}</p>}
<label>
Email
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
</label>
<label>
Password
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
</label>
<button type="submit" className="btn btn-primary" disabled={loading}>
{loading ? "Accesso..." : "Accedi"}
</button>
</form>
</div>
);
}

11
src/types/index.ts Normal file
View file

@ -0,0 +1,11 @@
export type Ruolo = "Operatore" | "Amministratore";
export interface Utente {
id: number;
nome: string;
cognome: string;
email: string;
ruolo: Ruolo;
}

View file

@ -0,0 +1,39 @@
//===================================================
// File: constraints.ts
// Vincoli derivati da initdb/01_schema.sql.
// author: "villari.andrea@libero.it"
// version: "1.0.0 2026-06-24"
//===================================================
export const UTENTE_CONSTRAINTS = {
nome: { maxLength: 100, required: true },
cognome: { maxLength: 100, required: true },
email: { maxLength: 255, required: true },
password: { minLength: 8, maxLength: 72, required: true },
ruolo: {
allowedValues: ["Operatore", "Amministratore"],
required: true,
},
} as const;
export const CLIENTE_CONSTRAINTS = {
nome: { maxLength: 100, required: true },
cognome: { maxLength: 100, required: true },
via: { maxLength: 100, required: true },
comune: { maxLength: 100, required: true },
provincia: { maxLength: 2, required: true },
telefono: { maxLength: 30, required: true },
email: { maxLength: 255, required: true },
note: { required: false },
} as const;
export const CONSEGNA_CONSTRAINTS = {
dataRitiro: { required: false },
dataConsegna: { required: false },
stato: {
allowedValues: ["da ritirare", "in consegna", "in giacenza", "in deposito"],
required: true,
},
chiaveConsegna: { maxLength: 8, required: true },
clienteId: { required: true },
} as const;

View file

@ -0,0 +1,200 @@
//==========================================
// File: primitives.ts
// Funzioni di validazione dei dati prmitivi
// author: "villari.andrea@libero.it"
// version: "1.0.0 2026-06-18"
//==========================================
export type FieldErrors = Record<string, string>;
export type ValidationResult<T> =
| { success: true; data: T }
| { success: false; errors: FieldErrors };
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
export function normalizeString(value: unknown): string {
if (value == null) return "";
return value.toString().trim();
}
export function normalizeEmail(value: unknown): string {
return normalizeString(value).toLowerCase();
}
export function normalizeBoolean(value: unknown, defaultValue = false): boolean {
if (value === true || value === "true") return true;
if (value === false || value === "false") return false;
return defaultValue;
}
export function normalizeDecimal(value: unknown): number {
if (typeof value === "number") return value;
const normalized = value?.toString().trim().replace(",", ".") ?? "";
if (!normalized) return Number.NaN;
return Number(normalized);
}
export function normalizePositiveInt(value: unknown): number {
if (typeof value === "number") return value;
const parsed = Number(value);
return Number.isInteger(parsed) && parsed > 0 ? parsed : Number.NaN;
}
export function normalizeTime(value: unknown): string {
const str = normalizeString(value);
if (!str) return "";
if (/^\d{2}:\d{2}$/.test(str)) return `${str}:00`;
return str;
}
export function validateRequired(
errors: FieldErrors,
field: string,
value: string,
message: string
): void {
if (!value) errors[field] = message;
}
export function validateMaxLength(
errors: FieldErrors,
field: string,
value: string,
maxLength: number,
label: string
): void {
if (value.length > maxLength) {
errors[field] = `${label} deve contenere al massimo ${maxLength} caratteri`;
}
}
export function validateMinLength(
errors: FieldErrors,
field: string,
value: string,
minLength: number,
label: string
): void {
if (value && value.length < minLength) {
errors[field] = `${label} deve contenere almeno ${minLength} caratteri`;
}
}
export function validateEmailFormat(
errors: FieldErrors,
field: string,
value: string
): void {
if (value && !EMAIL_REGEX.test(value)) {
errors[field] = "Formato email non valido";
}
}
export function validateEnum(
errors: FieldErrors,
field: string,
value: string,
allowedValues: readonly string[],
label: string
): void {
if (value && !allowedValues.includes(value)) {
errors[field] = `${label} non valido`;
}
}
export function validateBoolean(
errors: FieldErrors,
field: string,
value: unknown,
label: string
): void {
if (value === undefined || value === null || value === "") return;
if (
value !== true &&
value !== false &&
value !== "true" &&
value !== "false"
) {
errors[field] = `${label} non valido`;
}
}
const DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
const TIME_REGEX = /^\d{2}:\d{2}:\d{2}$/;
export function validateDate(
errors: FieldErrors,
field: string,
value: string,
label: string
): void {
if (!value) return;
if (!DATE_REGEX.test(value)) {
errors[field] = `${label} non valida`;
return;
}
const parsed = new Date(`${value}T00:00:00`);
if (Number.isNaN(parsed.getTime())) {
errors[field] = `${label} non valida`;
}
}
export function validateTimeFormat(
errors: FieldErrors,
field: string,
value: string,
label: string
): void {
if (!value) return;
if (!TIME_REGEX.test(value)) {
errors[field] = `${label} non valida`;
}
}
export function validatePositiveInt(
errors: FieldErrors,
field: string,
value: number,
label: string,
required = true
): void {
if (Number.isNaN(value) || value <= 0) {
errors[field] = required ? `${label} obbligatorio` : `${label} non valido`;
}
}
export function validateTimeRange(
errors: FieldErrors,
_startField: string,
endField: string,
start: string,
end: string
): void {
if (!start || !end) return;
if (start >= end) {
errors[endField] =
"L'ora di fine deve essere successiva all'ora di inizio";
}
}
export function validateDecimalPositive(
errors: FieldErrors,
field: string,
value: unknown,
label: string,
min = 0.01
): void {
if (value === undefined || value === null || value === "") return;
const num = typeof value === "number" ? value : Number(value);
if (Number.isNaN(num) || num < min) {
errors[field] = `${label} deve essere almeno ${min}`;
}
}
export function buildResult<T>(data: T, errors: FieldErrors): ValidationResult<T> {
if (Object.keys(errors).length > 0) {
return { success: false as const, errors };
}
return { success: true as const, data };
}

220
src/validation/utente.ts Normal file
View file

@ -0,0 +1,220 @@
import { UTENTE_CONSTRAINTS } from "./constraints";
import {
buildResult,
normalizeEmail,
normalizeString,
validateEmailFormat,
validateEnum,
validateMaxLength,
validateMinLength,
validateRequired,
type FieldErrors,
type ValidationResult,
} from "./primitives";
export type Ruolo = (typeof UTENTE_CONSTRAINTS.ruolo.allowedValues)[number];
export interface LoginInput {
email: string;
password: string;
}
export interface UtenteCreateInput {
nome: string;
cognome: string;
email: string;
password: string;
ruolo: Ruolo;
}
export type UtenteUpdateInput = Partial<UtenteCreateInput>;
export function normalizeLoginInput(raw: Record<string, unknown>): LoginInput {
return {
email: normalizeEmail(raw.email),
password: raw.password?.toString() ?? "",
};
}
export function validateLoginInput(
raw: Record<string, unknown>
): ValidationResult<LoginInput> {
const data = normalizeLoginInput(raw);
const errors: FieldErrors = {};
validateRequired(errors, "email", data.email, "Email obbligatoria");
validateMaxLength(
errors,
"email",
data.email,
UTENTE_CONSTRAINTS.email.maxLength,
"Email"
);
validateEmailFormat(errors, "email", data.email);
validateRequired(errors, "password", data.password, "Password obbligatoria");
validateMaxLength(
errors,
"password",
data.password,
UTENTE_CONSTRAINTS.password.maxLength,
"Password"
);
return buildResult(data, errors);
}
function validateUtenteProfileFields(
data: UtenteCreateInput,
errors: FieldErrors
): void {
validateRequired(errors, "nome", data.nome, "Nome obbligatorio");
validateMaxLength(
errors,
"nome",
data.nome,
UTENTE_CONSTRAINTS.nome.maxLength,
"Nome"
);
validateRequired(errors, "cognome", data.cognome, "Cognome obbligatorio");
validateMaxLength(
errors,
"cognome",
data.cognome,
UTENTE_CONSTRAINTS.cognome.maxLength,
"Cognome"
);
validateRequired(errors, "email", data.email, "Email obbligatoria");
validateMaxLength(
errors,
"email",
data.email,
UTENTE_CONSTRAINTS.email.maxLength,
"Email"
);
validateEmailFormat(errors, "email", data.email);
validateRequired(errors, "password", data.password, "Password obbligatoria");
validateMinLength(
errors,
"password",
data.password,
UTENTE_CONSTRAINTS.password.minLength,
"Password"
);
validateMaxLength(
errors,
"password",
data.password,
UTENTE_CONSTRAINTS.password.maxLength,
"Password"
);
validateRequired(errors, "ruolo", data.ruolo, "Ruolo obbligatorio");
validateEnum(
errors,
"ruolo",
data.ruolo,
UTENTE_CONSTRAINTS.ruolo.allowedValues,
"Ruolo"
);
}
export function validateUtenteCreate(
raw: Record<string, unknown>
): ValidationResult<UtenteCreateInput> {
const data: UtenteCreateInput = {
nome: normalizeString(raw.nome),
cognome: normalizeString(raw.cognome),
email: normalizeEmail(raw.email),
password: raw.password?.toString() ?? "",
ruolo: normalizeString(raw.ruolo) as Ruolo,
};
const errors: FieldErrors = {};
validateUtenteProfileFields(data, errors);
return buildResult(data, errors);
}
export function validateUtenteUpdate(
raw: Record<string, unknown>
): ValidationResult<UtenteUpdateInput> {
const errors: FieldErrors = {};
const data: UtenteUpdateInput = {};
if ("nome" in raw) {
data.nome = normalizeString(raw.nome);
validateRequired(errors, "nome", data.nome, "Nome obbligatorio");
validateMaxLength(
errors,
"nome",
data.nome,
UTENTE_CONSTRAINTS.nome.maxLength,
"Nome"
);
}
if ("cognome" in raw) {
data.cognome = normalizeString(raw.cognome);
validateRequired(errors, "cognome", data.cognome, "Cognome obbligatorio");
validateMaxLength(
errors,
"cognome",
data.cognome,
UTENTE_CONSTRAINTS.cognome.maxLength,
"Cognome"
);
}
if ("email" in raw) {
data.email = normalizeEmail(raw.email);
validateRequired(errors, "email", data.email, "Email obbligatoria");
validateMaxLength(
errors,
"email",
data.email,
UTENTE_CONSTRAINTS.email.maxLength,
"Email"
);
validateEmailFormat(errors, "email", data.email);
}
if ("password" in raw) {
const password = raw.password?.toString() ?? "";
if (password) {
data.password = password;
validateMinLength(
errors,
"password",
password,
UTENTE_CONSTRAINTS.password.minLength,
"Password"
);
validateMaxLength(
errors,
"password",
password,
UTENTE_CONSTRAINTS.password.maxLength,
"Password"
);
}
}
if ("ruolo" in raw) {
data.ruolo = normalizeString(raw.ruolo) as Ruolo;
validateRequired(errors, "ruolo", data.ruolo, "Ruolo obbligatorio");
validateEnum(
errors,
"ruolo",
data.ruolo,
UTENTE_CONSTRAINTS.ruolo.allowedValues,
"Ruolo"
);
}
if (Object.keys(data).length === 0) {
errors._form = "Nessun campo da aggiornare";
}
return buildResult(data, errors);
}