docv/app/login/page.tsx

261 lines
8.8 KiB
TypeScript

"use client"
import type React from "react"
import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
Shield,
Building2,
TestTube,
ArrowLeft,
Home,
Key,
CheckCircle,
AlertTriangle,
Eye,
EyeOff,
} from "lucide-react"
import { AuthModal } from "@/components/4nk/AuthModal"
import MessageBus from "@/lib/4nk/MessageBus"
import { MockService } from "@/lib/4nk/MockService"
import UserStore from "@/lib/4nk/UserStore"
export default function LoginPage() {
const [companyId, setCompanyId] = useState("")
const [isAuthModalOpen, setIsAuthModalOpen] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const [showPairingSection, setShowPairingSection] = useState(false)
const [pairingWords, setPairingWords] = useState(["", "", "", ""])
const [pairingError, setPairingError] = useState("")
const [error, setError] = useState<string | null>(null)
const [pairingSuccess, setPairingSuccess] = useState(false)
const router = useRouter()
const [showPairingInput, setShowPairingInput] = useState(false)
const iframeUrl = process.env.NEXT_PUBLIC_4NK_IFRAME_URL || "https://dev3.4nkweb.com"
const handleLogin = () => {
setIsAuthModalOpen(true)
setError(null)
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!companyId.trim()) {
return
}
setIsLoading(true)
try {
// Si l'identifiant est "1234", activer le mode mock directement
if (companyId === "1234") {
console.log("🎭 Activation du mode mock avec l'identifiant:", companyId)
const messageBus = MessageBus.getInstance(iframeUrl)
const mockService = MockService.getInstance()
const userStore = UserStore.getInstance()
// Mode normal (pas de mock)
// Authentification mock
const authResult = await mockService.mockAuthentication(companyId)
if (!authResult) {
throw new Error("Échec de l'authentification de démonstration")
}
// Simuler la récupération des tokens
const tokens = await mockService.mockRequestLink()
userStore.connect(tokens.accessToken, tokens.refreshToken)
// Simuler la récupération de l'ID d'appairage
const pairingId = await mockService.mockGetUserPairingId()
userStore.pair(pairingId)
console.log("✅ Mode mock activé avec succès")
// Redirection directe vers le dashboard
router.push("/dashboard")
} else {
// Mode normal - ouvrir la modal d'authentification 4NK
setIsAuthModalOpen(true)
}
} catch (error) {
console.error("Erreur lors de l'activation du mode mock:", error)
// En cas d'erreur, ouvrir quand même la modal d'authentification
setIsAuthModalOpen(true)
} finally {
setIsLoading(false)
}
}
const handleAuthSuccess = () => {
setIsAuthModalOpen(false)
router.push("/dashboard")
}
const handlePairingSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setPairingError("")
// Vérifier que tous les mots sont remplis
if (pairingWords.some((word) => !word.trim())) {
setPairingError("Veuillez saisir les 4 mots de pairing")
return
}
// Simuler la vérification des mots de pairing
const validWords = ["alpha", "bravo", "charlie", "delta"]
const isValid = pairingWords.every((word, index) => word.toLowerCase().trim() === validWords[index])
if (isValid) {
setPairingSuccess(true)
setTimeout(() => {
// Simuler l'ajout de l'appareil et la connexion
const userStore = UserStore.getInstance()
const mockService = MockService.getInstance()
// Simuler des tokens pour le pairing
userStore.connect("paired_access_token", "paired_refresh_token")
userStore.pair("paired_device_id")
router.push("/dashboard")
}, 2000)
} else {
setPairingError("Mots de pairing incorrects. Vérifiez les mots saisis sur votre autre appareil.")
}
}
const handlePairingWordChange = (index: number, value: string) => {
const newWords = [...pairingWords]
newWords[index] = value
setPairingWords(newWords)
setPairingError("")
}
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4">
<div className="w-full max-w-md space-y-6">
{/* Lien de retour vers l'accueil */}
<div className="text-center">
<Link
href="/"
className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900 transition-colors"
>
<ArrowLeft className="h-4 w-4 mr-2" />
Retour à l'accueil
</Link>
</div>
{/* Logo et titre */}
<div className="text-center">
<div className="flex items-center justify-center mb-6">
<Shield className="h-12 w-12 text-blue-600" />
</div>
<h1 className="text-3xl font-bold text-gray-900 mb-2">DocV</h1>
<p className="text-gray-600">Gestion électronique de documents sécurisée</p>
</div>
{/* Carte de connexion 4NK */}
<Card>
<CardHeader>
<CardTitle className="text-center">
<Shield className="h-8 w-8 mx-auto mb-4 text-blue-600" />
Connexion sécurisée 4NK
</CardTitle>
<CardDescription className="text-center">
Authentification cryptographique sans mot de passe
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* Description de la connexion 4NK */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<h3 className="font-semibold text-blue-900 mb-2">🔐 Authentification 4NK</h3>
<ul className="text-sm text-blue-800 space-y-1">
<li>• Aucun mot de passe requis</li>
<li>• Identité cryptographique sécurisée</li>
<li>• Chiffrement bout en bout</li>
<li>• Protection par blockchain</li>
</ul>
</div>
{/* Affichage des erreurs */}
{error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
<p className="text-red-700 font-medium">Erreur de connexion :</p>
<p className="text-red-600 text-sm">{error}</p>
</div>
)}
{/* Bouton de connexion */}
<Button
onClick={handleLogin}
className="w-full"
size="lg"
disabled={isLoading}
>
<Shield className="h-5 w-5 mr-2" />
{isLoading ? "Connexion en cours..." : "Se connecter avec 4NK"}
</Button>
{/* Informations sur l'iframe */}
<div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
<p className="text-xs text-gray-600 text-center">
<strong>URL d'authentification :</strong><br />
{iframeUrl}
</p>
</div>
</CardContent>
</Card>
{/* Badges de sécurité */}
<div className="flex flex-wrap justify-center gap-2">
<Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
<Shield className="h-3 w-3 mr-1" />
Sécurisé 4NK
</Badge>
<Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
Chiffrement bout en bout
</Badge>
<Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">
Blockchain
</Badge>
</div>
{/* Lien vers l'espace public */}
<div className="text-center">
<Link
href="/"
className="inline-flex items-center text-sm text-blue-600 hover:text-blue-800 transition-colors"
>
<Home className="h-4 w-4 mr-2" />
Découvrir DocV sans se connecter
</Link>
</div>
{/* Informations légales */}
<div className="text-center text-xs text-gray-500 space-y-1">
<p>En vous connectant, vous acceptez nos conditions d'utilisation</p>
<p>Vos données sont protégées par le chiffrement 4NK</p>
</div>
</div>
{/* Modal d'authentification 4NK */}
<AuthModal
isOpen={isAuthModalOpen}
onConnect={handleAuthSuccess}
onClose={() => setIsAuthModalOpen(false)}
iframeUrl={iframeUrl}
/>
</div>
)
}