installazione di reac-router-dom e creazione Dachboard, Login, AuthContext, GuestRoute e ProtectdRoute e api/clinet.ts
This commit is contained in:
parent
ad00749aa5
commit
841f999110
11 changed files with 675 additions and 288 deletions
60
package-lock.json
generated
60
package-lock.json
generated
|
|
@ -9,7 +9,8 @@
|
|||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"react": "^19.2.6",
|
||||
"react-dom": "^19.2.6"
|
||||
"react-dom": "^19.2.6",
|
||||
"react-router-dom": "^7.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
|
|
@ -1306,6 +1307,19 @@
|
|||
"dev": true,
|
||||
"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": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
|
|
@ -2370,6 +2384,44 @@
|
|||
"react": "^19.2.7"
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.0.tgz",
|
||||
"integrity": "sha512-pTTGt8J+ji1NOmYnjzT+bAJy/1zD+Jp4ziO6cL7T3ZLvXKtusO7BpFqlRXitqpcPVqllsIXFHRMt+2/k3Xn6HQ==",
|
||||
"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.0",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.0.tgz",
|
||||
"integrity": "sha512-Fi0yY6kgtKae/Th2xibdWK0KSdYZ4B53Gyf6wRtomOKWgpNm7H7+DyfDhncdz9FKbpS+1jmDhg3F4WoGJ+yFOA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"react-router": "7.18.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18",
|
||||
"react-dom": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/rolldown": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.3.tgz",
|
||||
|
|
@ -2420,6 +2472,12 @@
|
|||
"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": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||
|
|
|
|||
|
|
@ -11,7 +11,8 @@
|
|||
},
|
||||
"dependencies": {
|
||||
"react": "^19.2.6",
|
||||
"react-dom": "^19.2.6"
|
||||
"react-dom": "^19.2.6",
|
||||
"react-router-dom": "^7.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
|
|
|
|||
305
src/App.css
305
src/App.css
|
|
@ -1,184 +1,135 @@
|
|||
.counter {
|
||||
font-size: 16px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
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;
|
||||
}
|
||||
.auth-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2rem;
|
||||
background: linear-gradient(135deg, #f0f4f8 0%, #e2e8f0 100%);
|
||||
}
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
.auth-card {
|
||||
background: #fff;
|
||||
padding: 2rem;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.base,
|
||||
.framework,
|
||||
.vite {
|
||||
inset-inline: 0;
|
||||
.auth-card h1 {
|
||||
margin: 0;
|
||||
color: #1e3a5f;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.auth-subtitle {
|
||||
margin: 0;
|
||||
color: #64748b;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.auth-card label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
font-size: 0.9rem;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.auth-card input {
|
||||
padding: 0.65rem 0.75rem;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 8px;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.auth-card input:focus {
|
||||
outline: 2px solid #3b82f6;
|
||||
outline-offset: 1px;
|
||||
border-color: #3b82f6;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 0.7rem 1rem;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: #1e3a5f;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
background: #2d4a6f;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #e2e8f0;
|
||||
color: #1e293b;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: #cbd5e1;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
padding: 0.65rem 0.75rem;
|
||||
background: #fef2f2;
|
||||
color: #b91c1c;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.dashboard-page {
|
||||
min-height: 100vh;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.dashboard-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1.5rem 2rem;
|
||||
background: #1e3a5f;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.dashboard-header h1 {
|
||||
margin: 0 0 0.25rem;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.dashboard-header p {
|
||||
margin: 0;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.dashboard-main {
|
||||
padding: 2rem;
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.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;
|
||||
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;
|
||||
gap: 8px;
|
||||
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;
|
||||
justify-content: center;
|
||||
|
||||
li {
|
||||
flex: 1 1 calc(50% - 8px);
|
||||
}
|
||||
|
||||
a {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#spacer {
|
||||
height: 88px;
|
||||
border-top: 1px solid var(--border);
|
||||
@media (max-width: 1024px) {
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.ticks {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
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);
|
||||
}
|
||||
.dashboard-main p {
|
||||
margin: 0 0 1.5rem;
|
||||
color: #475569;
|
||||
}
|
||||
|
|
|
|||
145
src/App.tsx
145
src/App.tsx
|
|
@ -1,122 +1,29 @@
|
|||
import { useState } from 'react'
|
||||
import reactLogo from './assets/react.svg'
|
||||
import viteLogo from './assets/vite.svg'
|
||||
import heroImg from './assets/hero.png'
|
||||
import './App.css'
|
||||
|
||||
function App() {
|
||||
const [count, setCount] = useState(0)
|
||||
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
|
||||
import GuestRoute from "./components/GuestRoute";
|
||||
import ProtectedRoute from "./components/ProtectedRoute";
|
||||
import { AuthProvider } from "./context/AuthContext";
|
||||
import Dashboard from "./pages/Dashboard";
|
||||
import Login from "./pages/Login";
|
||||
import "./App.css";
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<>
|
||||
<section id="center">
|
||||
<div className="hero">
|
||||
<img src={heroImg} className="base" width="170" height="179" alt="" />
|
||||
<img src={reactLogo} className="framework" alt="React logo" />
|
||||
<img src={viteLogo} className="vite" alt="Vite logo" />
|
||||
</div>
|
||||
<div>
|
||||
<h1>Get started</h1>
|
||||
<p>
|
||||
Edit <code>src/App.tsx</code> and save to test <code>HMR</code>
|
||||
</p>
|
||||
</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>
|
||||
</>
|
||||
)
|
||||
<AuthProvider>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/login" element={<GuestRoute><Login /></GuestRoute>} />
|
||||
<Route
|
||||
path="/dashboard"
|
||||
element={
|
||||
<ProtectedRoute>
|
||||
<Dashboard />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route path="/" element={<Navigate to="/login" replace />} />
|
||||
<Route path="*" element={<Navigate to="/login" replace />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default App
|
||||
|
|
|
|||
215
src/api/client.ts
Normal file
215
src/api/client.ts
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
import type {
|
||||
Cliente,
|
||||
ClienteFormInput,
|
||||
Consegna,
|
||||
ConsegnaFormInput,
|
||||
Ruolo,
|
||||
Utente,
|
||||
UtenteAdmin,
|
||||
UtenteAdminFormInput,
|
||||
VerificaConsegna,
|
||||
} from "../types";
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL ?? "";
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
fields?: Record<string, string>;
|
||||
|
||||
constructor(message: string, status: number, fields?: Record<string, string>) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
this.fields = fields;
|
||||
}
|
||||
}
|
||||
|
||||
interface ApiErrorBody {
|
||||
error?: string;
|
||||
fields?: Record<string, string>;
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
const data = (await response.json().catch(() => ({}))) as ApiErrorBody;
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ApiError(
|
||||
data.error ?? `Errore ${response.status}`,
|
||||
response.status,
|
||||
data.fields
|
||||
);
|
||||
}
|
||||
|
||||
return data as T;
|
||||
}
|
||||
|
||||
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: 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,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getMe(): Promise<Utente> {
|
||||
const data = await request<{
|
||||
id: number;
|
||||
email: string;
|
||||
name: string;
|
||||
ruolo: Ruolo;
|
||||
}>("/api/me");
|
||||
|
||||
const [nome, ...cognomeParts] = (data.name ?? "").split(" ");
|
||||
|
||||
return {
|
||||
id: data.id,
|
||||
nome,
|
||||
cognome: cognomeParts.join(" "),
|
||||
email: data.email,
|
||||
ruolo: data.ruolo,
|
||||
};
|
||||
}
|
||||
|
||||
export async function verificaConsegna(
|
||||
chiave: string
|
||||
): Promise<VerificaConsegna> {
|
||||
const params = new URLSearchParams({ chiave: chiave.trim().toUpperCase() });
|
||||
return request(`/api/verifica-consegna?${params.toString()}`);
|
||||
}
|
||||
|
||||
export async function getClienti(): Promise<Cliente[]> {
|
||||
return request("/api/clienti");
|
||||
}
|
||||
|
||||
export async function createCliente(data: ClienteFormInput): Promise<Cliente> {
|
||||
return request("/api/clienti", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateCliente(
|
||||
id: number,
|
||||
data: Partial<ClienteFormInput>
|
||||
): Promise<Cliente> {
|
||||
return request(`/api/clienti/${id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteCliente(id: number): Promise<void> {
|
||||
await request(`/api/clienti/${id}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
export async function getConsegne(): Promise<Consegna[]> {
|
||||
return request("/api/consegne");
|
||||
}
|
||||
|
||||
export async function createConsegna(
|
||||
data: ConsegnaFormInput
|
||||
): Promise<Consegna> {
|
||||
return request("/api/consegne", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateConsegna(
|
||||
id: number,
|
||||
data: Partial<ConsegnaFormInput>
|
||||
): Promise<Consegna> {
|
||||
return request(`/api/consegne/${id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteConsegna(id: number): Promise<void> {
|
||||
await request(`/api/consegne/${id}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
export async function getUtenti(): Promise<UtenteAdmin[]> {
|
||||
return request("/api/utenti");
|
||||
}
|
||||
|
||||
export async function createUtente(
|
||||
data: UtenteAdminFormInput
|
||||
): Promise<UtenteAdmin> {
|
||||
return request("/api/utenti", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateUtente(
|
||||
id: number,
|
||||
data: Partial<UtenteAdminFormInput>
|
||||
): Promise<UtenteAdmin> {
|
||||
return request(`/api/utenti/${id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteUtente(id: number): Promise<void> {
|
||||
await request(`/api/utenti/${id}`, { method: "DELETE" });
|
||||
}
|
||||
11
src/components/GuestRoute.tsx
Normal file
11
src/components/GuestRoute.tsx
Normal 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}</>;
|
||||
}
|
||||
26
src/components/ProtectedRoute.tsx
Normal file
26
src/components/ProtectedRoute.tsx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { Navigate } from "react-router-dom";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
|
||||
export default function ProtectedRoute({
|
||||
children,
|
||||
adminOnly = false,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
adminOnly?: boolean;
|
||||
}) {
|
||||
const { user, loading } = useAuth();
|
||||
|
||||
if (loading) return <p className="loading">Caricamento...</p>;
|
||||
if (!user) return <Navigate to="/login" replace />;
|
||||
if (adminOnly && user.ruolo !== "Amministratore") {
|
||||
return (
|
||||
<Navigate
|
||||
to="/dashboard"
|
||||
replace
|
||||
state={{ denied: "Operazione riservata agli amministratori." }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
53
src/context/AuthContext.tsx
Normal file
53
src/context/AuthContext.tsx
Normal 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;
|
||||
}
|
||||
25
src/pages/Dashboard.tsx
Normal file
25
src/pages/Dashboard.tsx
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { useAuth } from "../context/AuthContext";
|
||||
|
||||
export default function Dashboard() {
|
||||
const { user, logout } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="dashboard-page">
|
||||
<header className="dashboard-header">
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
<p>
|
||||
Benvenuto, {user?.nome} {user?.cognome}
|
||||
{user?.ruolo === "Amministratore" ? " (Amministratore)" : ""}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => logout()}>
|
||||
Esci
|
||||
</button>
|
||||
</header>
|
||||
<main className="dashboard-main">
|
||||
<p>Area riservata agli operatori corrieri.</p>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
70
src/pages/Login.tsx
Normal file
70
src/pages/Login.tsx
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { useState, type FormEvent } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import { UTENTE_CONSTRAINTS } from "../validation/constraints";
|
||||
import { validateLoginInput } from "../validation/utente";
|
||||
|
||||
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);
|
||||
|
||||
const validation = validateLoginInput({ email, password });
|
||||
if (!validation.success) {
|
||||
setError(Object.values(validation.errors)[0] ?? "Dati di accesso non validi");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
await login(validation.data.email, validation.data.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} noValidate>
|
||||
<h1>Gestione Corrieri</h1>
|
||||
<p className="auth-subtitle">Accedi con le tue credenziali</p>
|
||||
{error && <p className="error">{error}</p>}
|
||||
<label>
|
||||
Email
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoComplete="email"
|
||||
maxLength={UTENTE_CONSTRAINTS.email.maxLength}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Password
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
maxLength={UTENTE_CONSTRAINTS.password.maxLength}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="btn btn-primary" disabled={loading}>
|
||||
{loading ? "Accesso..." : "Accedi"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
70
src/types/index.ts
Normal file
70
src/types/index.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
export type Ruolo = "Operatore" | "Amministratore";
|
||||
|
||||
export interface Utente {
|
||||
id: number;
|
||||
nome: string;
|
||||
cognome: string;
|
||||
email: string;
|
||||
ruolo: Ruolo;
|
||||
}
|
||||
|
||||
export interface Cliente {
|
||||
id: number;
|
||||
nome: string;
|
||||
cognome: string;
|
||||
via: string;
|
||||
comune: string;
|
||||
provincia: string;
|
||||
telefono: string;
|
||||
email: string;
|
||||
note: string | null;
|
||||
}
|
||||
|
||||
export type ClienteFormInput = Omit<Cliente, "id">;
|
||||
|
||||
export type StatoConsegna =
|
||||
| "da ritirare"
|
||||
| "in consegna"
|
||||
| "in giacenza"
|
||||
| "in deposito";
|
||||
|
||||
export interface Consegna {
|
||||
id: number;
|
||||
dataRitiro: string;
|
||||
dataConsegna: string;
|
||||
stato: StatoConsegna;
|
||||
chiaveConsegna: string;
|
||||
clienteId: number;
|
||||
clienteNome: string;
|
||||
clienteCognome: string;
|
||||
}
|
||||
|
||||
export type ConsegnaFormInput = Omit<
|
||||
Consegna,
|
||||
"id" | "clienteNome" | "clienteCognome"
|
||||
>;
|
||||
|
||||
export interface UtenteAdmin {
|
||||
id: number;
|
||||
nome: string;
|
||||
cognome: string;
|
||||
email: string;
|
||||
ruolo: Ruolo;
|
||||
}
|
||||
|
||||
export interface UtenteAdminFormInput {
|
||||
nome: string;
|
||||
cognome: string;
|
||||
email: string;
|
||||
password: string;
|
||||
ruolo: Ruolo;
|
||||
}
|
||||
|
||||
export interface VerificaConsegna {
|
||||
dataRitiro: string;
|
||||
dataConsegna: string;
|
||||
stato: StatoConsegna;
|
||||
clienteNome: string;
|
||||
clienteCognome: string;
|
||||
comune: string;
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue