import { useState } from "react"; import styles from "../styles/AuthPage.module.css"; export default function AuthPage({ onAuthSuccess }: { onAuthSuccess: (token: string, user: { id: number; email: string; full_name: string | null }) => void }) { const [isLogin, setIsLogin] = useState(true); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [fullName, setFullName] = useState(""); const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const API_URL = "http://localhost:8000"; const handleLogin = async (e: React.FormEvent) => { e.preventDefault(); setError(""); setLoading(true); try { console.log("Tentative de connexion avec:", email); const response = await fetch(`${API_URL}/login`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email, password }), }); console.log("Status:", response.status); const data = await response.json(); console.log("Response data:", data); if (!response.ok) { throw new Error(data.detail || `Erreur ${response.status}`); } const userResponse = await fetch(`${API_URL}/me?token=${data.access_token}`); const userData = await userResponse.json(); onAuthSuccess(data.access_token, userData); } catch (err) { console.error("Error:", err); setError(err instanceof Error ? err.message : "Erreur lors de la connexion"); } finally { setLoading(false); } }; const handleSignup = async (e: React.FormEvent) => { e.preventDefault(); setError(""); setLoading(true); try { const response = await fetch(`${API_URL}/signup`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email, password, full_name: fullName, }), }); if (!response.ok) { const data = await response.json(); throw new Error(data.detail || "Erreur d'inscription"); } const userData = await response.json(); // Automatiquement connecter après l'inscription const loginResponse = await fetch(`${API_URL}/login`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email, password }), }); const loginData = await loginResponse.json(); onAuthSuccess(loginData.access_token, userData); } catch (err) { setError(err instanceof Error ? err.message : "Erreur lors de l'inscription"); } finally { setLoading(false); } }; const handleSubmit = isLogin ? handleLogin : handleSignup; return (
Gestion des réglementations alimentaires
{isLogin ? "Pas encore de compte ?" : "Déjà inscrit ?"} {" "}