ajout authentification admin/user
This commit is contained in:
+21
-6
@@ -1,4 +1,4 @@
|
||||
import { Routes, Route } from 'react-router-dom';
|
||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||
import Layout from './components/Layout';
|
||||
import Home from './pages/Home';
|
||||
import Books from './pages/Books';
|
||||
@@ -8,19 +8,34 @@ import NotFound from './pages/NotFound';
|
||||
import AddBook from './pages/AddBook';
|
||||
import BookDetail from './pages/BookDetail';
|
||||
import Customers from './pages/Customers';
|
||||
import Login from './pages/Login';
|
||||
import { useAuth } from './context/AuthContext';
|
||||
|
||||
function RequireAuth({ children }) {
|
||||
const { user } = useAuth();
|
||||
return user ? children : <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
function RequireAdmin({ children }) {
|
||||
const { user } = useAuth();
|
||||
if (!user) return <Navigate to="/login" replace />;
|
||||
if (user.role !== 'admin') return <Navigate to="/" replace />;
|
||||
return children;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/" element={<Layout />}>
|
||||
<Route index element={<Home />} />
|
||||
<Route path="books" element={<Books />} />
|
||||
<Route path="orders" element={<Orders />} />
|
||||
<Route path="profile" element={<Profile />} />
|
||||
<Route path="books/:bookId" element={<RequireAuth><BookDetail /></RequireAuth>} />
|
||||
<Route path="books/new" element={<RequireAdmin><AddBook /></RequireAdmin>} />
|
||||
<Route path="orders" element={<RequireAuth><Orders /></RequireAuth>} />
|
||||
<Route path="profile" element={<RequireAuth><Profile /></RequireAuth>} />
|
||||
<Route path="customers" element={<RequireAdmin><Customers /></RequireAdmin>} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
<Route path="books/new" element={<AddBook />} />
|
||||
<Route path="books/:bookId" element={<BookDetail />} />
|
||||
<Route path="customers" element={<Customers />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import '../styles/navbar.css';
|
||||
|
||||
export default function Navbar() {
|
||||
const { user, logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
function handleLogout() {
|
||||
logout();
|
||||
navigate('/login');
|
||||
}
|
||||
|
||||
return (
|
||||
<nav className="navbar">
|
||||
<Link to="/" className="navbar__logo">Biblio</Link>
|
||||
@@ -9,13 +18,20 @@ export default function Navbar() {
|
||||
<ul className="navbar__links">
|
||||
<li><Link to="/">Accueil</Link></li>
|
||||
<li><Link to="/books">Catalogue</Link></li>
|
||||
<li><Link to="/orders">Commandes</Link></li>
|
||||
<li><Link to="/profile">Mon compte</Link></li>
|
||||
{user && <li><Link to="/orders">Commandes</Link></li>}
|
||||
{user && <li><Link to="/profile">Mon compte</Link></li>}
|
||||
{user?.role === 'admin' && <li><Link to="/customers">Clients</Link></li>}
|
||||
</ul>
|
||||
|
||||
<div className="navbar__actions">
|
||||
<button className="btn-ghost">Connexion</button>
|
||||
<button className="btn-cta">S'inscrire</button>
|
||||
{user ? (
|
||||
<>
|
||||
<span>{user.username} ({user.role})</span>
|
||||
<button onClick={handleLogout}>Déconnexion</button>
|
||||
</>
|
||||
) : (
|
||||
<Link to="/login"><button>Connexion</button></Link>
|
||||
)}
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { createContext, useContext, useState } from 'react';
|
||||
|
||||
const USERS = [
|
||||
{ username: 'admin', password: 'admin', role: 'admin' },
|
||||
{ username: 'alice', password: 'bob', role: 'user' },
|
||||
];
|
||||
|
||||
const AuthContext = createContext(null);
|
||||
|
||||
export function AuthProvider({ children }) {
|
||||
const [user, setUser] = useState(() => {
|
||||
const saved = localStorage.getItem('auth');
|
||||
return saved ? JSON.parse(saved) : null;
|
||||
});
|
||||
|
||||
function login(username, password) {
|
||||
const found = USERS.find(u => u.username === username && u.password === password);
|
||||
if (!found) return false;
|
||||
const { password: _, ...safe } = found;
|
||||
setUser(safe);
|
||||
localStorage.setItem('auth', JSON.stringify(safe));
|
||||
return true;
|
||||
}
|
||||
|
||||
function logout() {
|
||||
setUser(null);
|
||||
localStorage.removeItem('auth');
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
return useContext(AuthContext);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { AuthProvider } from './context/AuthContext';
|
||||
import App from './App';
|
||||
import './styles/global.css';
|
||||
|
||||
@@ -8,7 +9,9 @@ const root = ReactDOM.createRoot(document.getElementById('root'));
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</React.StrictMode>
|
||||
);
|
||||
@@ -1,14 +1,35 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import { getBookById } from '../api/books';
|
||||
import { getBookById, reserveBook } from '../api/books';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export default function BookDetail() {
|
||||
const { user } = useAuth();
|
||||
const { bookId } = useParams();
|
||||
const [book, setBook] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [phoneNumber, setPhoneNumber] = useState('');
|
||||
const [reservationStatus, setReservationStatus] = useState(null);
|
||||
const [reserving, setReserving] = useState(false);
|
||||
|
||||
useEffect(() => {getBookById(bookId).then((response) => setBook(response.data)).catch((err) => {console.error(err);setError('Livre introuvable.');}).finally(() => setLoading(false));}, [bookId]);
|
||||
useEffect(() => { getBookById(bookId).then((response) => setBook(response.data)).catch((err) => { console.error(err); setError('Livre introuvable.'); }).finally(() => setLoading(false)); }, [bookId]);
|
||||
|
||||
function handleReservation(e) {
|
||||
e.preventDefault();
|
||||
setReserving(true);
|
||||
setReservationStatus(null);
|
||||
reserveBook(bookId, { phoneNumber })
|
||||
.then(() => {
|
||||
setReservationStatus({ success: true, message: 'Réservation effectuée avec succès !' });
|
||||
setPhoneNumber('');
|
||||
})
|
||||
.catch((err) => {
|
||||
const msg = err.response?.data || 'Erreur lors de la réservation.';
|
||||
setReservationStatus({ success: false, message: msg });
|
||||
})
|
||||
.finally(() => setReserving(false));
|
||||
}
|
||||
|
||||
if (loading) return <main><p>Chargement…</p></main>;
|
||||
if (error) return <main><p>{error}</p><Link to="/books">← Retour au catalogue</Link></main>;
|
||||
@@ -26,6 +47,30 @@ export default function BookDetail() {
|
||||
<p>Langue : {book.language}</p>
|
||||
<p>Catégories : {book.categories?.join(', ')}</p>
|
||||
{book.description && <p>{book.description}</p>}
|
||||
|
||||
{user?.role === 'user' && <section>
|
||||
<h2>Réserver ce livre</h2>
|
||||
<form onSubmit={handleReservation}>
|
||||
<label>
|
||||
Numéro de téléphone :
|
||||
<input
|
||||
type="tel"
|
||||
value={phoneNumber}
|
||||
onChange={(e) => setPhoneNumber(e.target.value)}
|
||||
placeholder="0612345678"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={reserving}>
|
||||
{reserving ? 'Réservation…' : 'Réserver'}
|
||||
</button>
|
||||
</form>
|
||||
{reservationStatus && (
|
||||
<p style={{ color: reservationStatus.success ? 'green' : 'red' }}>
|
||||
{reservationStatus.message}
|
||||
</p>
|
||||
)}
|
||||
</section>}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { getBooks } from '../api/books';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export default function Books() {
|
||||
const { user } = useAuth();
|
||||
const [books, setBooks] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
@@ -28,7 +30,7 @@ export default function Books() {
|
||||
return (
|
||||
<main>
|
||||
<h1>Catalogue</h1>
|
||||
<Link to="/books/new">+ Ajouter un livre</Link>
|
||||
{user?.role === 'admin' && <Link to="/books/new">+ Ajouter un livre</Link>}
|
||||
<ul>
|
||||
{books.map((book) => (
|
||||
<li key={book.isbn}>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export default function Login() {
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [form, setForm] = useState({ username: '', password: '' });
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
function handleSubmit(e) {
|
||||
e.preventDefault();
|
||||
const ok = login(form.username, form.password);
|
||||
if (ok) {
|
||||
navigate('/');
|
||||
} else {
|
||||
setError('Identifiants incorrects.');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main>
|
||||
<h1>Connexion</h1>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div>
|
||||
<label>
|
||||
Nom d'utilisateur :
|
||||
<input
|
||||
type="text"
|
||||
value={form.username}
|
||||
onChange={e => setForm(f => ({ ...f, username: e.target.value }))}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label>
|
||||
Mot de passe :
|
||||
<input
|
||||
type="password"
|
||||
value={form.password}
|
||||
onChange={e => setForm(f => ({ ...f, password: e.target.value }))}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<button type="submit">Se connecter</button>
|
||||
{error && <p style={{ color: 'red' }}>{error}</p>}
|
||||
</form>
|
||||
<p>Comptes disponibles :</p>
|
||||
<ul>
|
||||
<li><strong>admin</strong> / admin (administrateur)</li>
|
||||
<li><strong>user</strong> / user (utilisateur)</li>
|
||||
</ul>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user