import { useState, useEffect } from "react"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useAuthUnified } from "@/hooks/useAuthUnified"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { useToast } from "@/hooks/use-toast"; import { apiRequest, queryClient } from "@/lib/queryClient"; import { Store, LogIn, User, Info } from "lucide-react"; import { useLocation } from "wouter"; // Fonction pour détecter l'environnement const getEnvironment = () => { const hostname = window.location.hostname; const isDev = hostname.includes('replit.dev') || hostname === 'localhost'; return isDev ? 'development' : 'production'; }; export default function AuthPage() { const [, setLocation] = useLocation(); const { user, isLoading, refreshAuth, forceAuthRefresh, isAuthenticated } = useAuthUnified(); const { toast } = useToast(); const [showDefaultCredentials, setShowDefaultCredentials] = useState(true); const [isSubmitting, setIsSubmitting] = useState(false); const [loginData, setLoginData] = useState({ username: "", password: "", }); const currentEnvironment = getEnvironment(); // Check if admin user still has default password const { data: defaultCredentialsCheck } = useQuery({ queryKey: ['/api/default-credentials-check'], queryFn: async () => { try { const response = await apiRequest("/api/default-credentials-check", "GET"); return response; } catch (error) { // If the endpoint doesn't exist or fails, assume we should show credentials return { showDefault: true }; } }, }); // Fonction de login simple pour production const handleProductionLogin = async (data: typeof loginData) => { setIsSubmitting(true); try { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, credentials: 'include', body: JSON.stringify(data), }); if (response.ok) { toast({ title: "Connexion réussie", description: "Redirection en cours...", }); // En production, recharger la page pour éviter les problèmes de synchronisation setTimeout(() => { window.location.href = "/"; }, 500); } else { const errorData = await response.json().catch(() => ({})); toast({ title: "Erreur de connexion", description: errorData.message || "Identifiant ou mot de passe incorrect", variant: "destructive", }); } } catch (error: any) { toast({ title: "Erreur de connexion", description: error.message || "Une erreur est survenue", variant: "destructive", }); } finally { setIsSubmitting(false); } }; // Mutation complexe pour développement const loginMutation = useMutation({ mutationFn: async (data: typeof loginData) => { const response = await apiRequest("/api/login", "POST", data); return response; }, onSuccess: async (loginResult) => { console.log('✅ Login successful, refreshing auth state...'); toast({ title: "Connexion réussie", description: "Bienvenue dans LogiFlow", }); // Force invalidation of auth queries and refresh auth state queryClient.invalidateQueries({ queryKey: ['/api/user'] }); queryClient.invalidateQueries({ queryKey: ['/api/default-credentials-check'] }); // Force immediate authentication state refresh const refreshedUserData = await forceAuthRefresh(); console.log('🔄 Force auth refresh result:', refreshedUserData); if (refreshedUserData && refreshedUserData.id) { console.log('🔄 User data confirmed, forcing redirect...'); setLocation("/"); } else { setTimeout(() => { forceAuthRefresh().then((retryUserData) => { if (retryUserData && retryUserData.id) { setLocation("/"); } }); }, 500); } }, onError: (error: any) => { toast({ title: "Erreur de connexion", description: error.message || "Identifiant ou mot de passe incorrect", variant: "destructive", }); }, }); // Debug logging for authentication state console.log('🔍 AuthPage Debug:', { isAuthenticated, isLoading, userId: user?.id, username: user?.username }); useEffect(() => { if (defaultCredentialsCheck) { setShowDefaultCredentials(defaultCredentialsCheck.showDefault); } }, [defaultCredentialsCheck]); // Redirect if already authenticated useEffect(() => { if (!isLoading && isAuthenticated && user) { console.log('🔄 User authenticated, redirecting to dashboard...', { user: user.username, authenticated: isAuthenticated }); // Force immediate redirect to home page setLocation("/"); } }, [isLoading, isAuthenticated, user, setLocation]); const handleLogin = (e: React.FormEvent) => { e.preventDefault(); if (currentEnvironment === 'production') { // Utiliser la méthode simple pour production handleProductionLogin(loginData); } else { // Utiliser React Query pour développement loginMutation.mutate(loginData); } }; if (isLoading) { return (
Chargement...
Gestion des commandes et livraisons
Identifiant : admin
Mot de passe : admin
Changez le mot de passe après votre première connexion
LogiFlow centralise la gestion de vos commandes et livraisons across tous vos magasins