fonctionnalité majeure : setup ultra simplifié (installation/configuration des infos supabase directement du web)

This commit is contained in:
Yannick Le Duc
2025-08-28 14:05:32 +02:00
parent b7ce1145e3
commit f93c995815
26 changed files with 3066 additions and 341 deletions

682
src/app/debug-auth/page.tsx Normal file
View File

@@ -0,0 +1,682 @@
'use client';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, CheckCircle, AlertCircle, User, Database, Shield, LogIn } from 'lucide-react';
import { authService } from '@/lib/auth';
export default function DebugAuthPage() {
const [email, setEmail] = useState('');
const [loading, setLoading] = useState(false);
const [results, setResults] = useState<any>(null);
const [error, setError] = useState('');
// État pour la connexion
const [loginEmail, setLoginEmail] = useState('');
const [loginPassword, setLoginPassword] = useState('');
const [loginLoading, setLoginLoading] = useState(false);
const [loginError, setLoginError] = useState('');
const [loginSuccess, setLoginSuccess] = useState(false);
// État pour la réparation
const [fixLoading, setFixLoading] = useState(false);
const [fixError, setFixError] = useState('');
const [fixSuccess, setFixSuccess] = useState(false);
// État pour le diagnostic RLS
const [rlsLoading, setRlsLoading] = useState(false);
const [rlsResults, setRlsResults] = useState<any>(null);
const [rlsError, setRlsError] = useState('');
// État pour la correction RLS
const [fixRlsLoading, setFixRlsLoading] = useState(false);
const [fixRlsError, setFixRlsError] = useState('');
const [fixRlsSuccess, setFixRlsSuccess] = useState(false);
const runDiagnostic = async () => {
if (!email) {
setError('Veuillez saisir un email');
return;
}
setLoading(true);
setError('');
setResults(null);
try {
// 1. Diagnostic côté serveur
const response = await fetch('/api/debug-auth', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
});
const serverData = await response.json();
// 2. Diagnostic côté client
const clientData: {
currentUser: any;
isAdmin: boolean;
isSuperAdmin: boolean;
currentAdmin: any;
} = {
currentUser: null,
isAdmin: false,
isSuperAdmin: false,
currentAdmin: null,
};
try {
clientData.currentUser = await authService.getCurrentUser();
} catch (e) {
console.log('Aucun utilisateur connecté côté client');
}
if (clientData.currentUser) {
try {
clientData.isAdmin = await authService.isAdmin();
} catch (e) {
console.log('Erreur lors de la vérification admin');
}
try {
clientData.isSuperAdmin = await authService.isSuperAdmin();
} catch (e) {
console.log('Erreur lors de la vérification super admin');
}
try {
clientData.currentAdmin = await authService.getCurrentPermissions();
} catch (e) {
console.log('Erreur lors de la récupération des permissions');
}
}
setResults({
server: serverData,
client: clientData,
});
} catch (error: any) {
setError(error.message || 'Erreur lors du diagnostic');
} finally {
setLoading(false);
}
};
const handleLogin = async () => {
if (!loginEmail || !loginPassword) {
setLoginError('Veuillez saisir email et mot de passe');
return;
}
setLoginLoading(true);
setLoginError('');
setLoginSuccess(false);
try {
await authService.signIn(loginEmail, loginPassword);
setLoginSuccess(true);
setLoginError('');
// Recharger la page pour mettre à jour l'état
setTimeout(() => {
window.location.reload();
}, 1000);
} catch (error: any) {
setLoginError(error.message || 'Erreur de connexion');
} finally {
setLoginLoading(false);
}
};
const handleFixAdmin = async () => {
if (!email) {
setFixError('Veuillez saisir un email');
return;
}
setFixLoading(true);
setFixError('');
setFixSuccess(false);
try {
const response = await fetch('/api/fix-admin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
});
const result = await response.json();
if (result.success) {
setFixSuccess(true);
setFixError('');
// Recharger la page après un délai
setTimeout(() => {
window.location.reload();
}, 2000);
} else {
setFixError(result.error || 'Erreur lors de la réparation');
}
} catch (error: any) {
setFixError(error.message || 'Erreur lors de la réparation');
} finally {
setFixLoading(false);
}
};
const runRlsDiagnostic = async () => {
if (!email) {
setRlsError('Veuillez saisir un email');
return;
}
setRlsLoading(true);
setRlsError('');
setRlsResults(null);
try {
const response = await fetch('/api/debug-rls', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
});
const result = await response.json();
if (result.success) {
setRlsResults(result);
setRlsError('');
} else {
setRlsError(result.error || 'Erreur lors du diagnostic RLS');
}
} catch (error: any) {
setRlsError(error.message || 'Erreur lors du diagnostic RLS');
} finally {
setRlsLoading(false);
}
};
const handleFixRls = async () => {
setFixRlsLoading(true);
setFixRlsError('');
setFixRlsSuccess(false);
try {
const response = await fetch('/api/fix-rls', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const result = await response.json();
if (result.success) {
setFixRlsSuccess(true);
setFixRlsError('');
// Recharger la page après un délai
setTimeout(() => {
window.location.reload();
}, 3000);
} else {
setFixRlsError(result.error || 'Erreur lors de la correction RLS');
}
} catch (error: any) {
setFixRlsError(error.message || 'Erreur lors de la correction RLS');
} finally {
setFixRlsLoading(false);
}
};
return (
<div className="min-h-screen bg-slate-50 dark:bg-slate-900 py-8">
<div className="container mx-auto px-4 max-w-4xl">
<div className="text-center mb-8">
<h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100 mb-2">
Diagnostic d'Authentification
</h1>
<p className="text-slate-600 dark:text-slate-400">
Vérifiez l'état de l'authentification et des permissions
</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Diagnostic */}
<Card>
<CardHeader>
<CardTitle>Diagnostic</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div>
<Label htmlFor="email">Email de l'utilisateur à diagnostiquer</Label>
<Input
id="email"
type="email"
placeholder="admin@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="mt-2"
/>
</div>
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="grid grid-cols-2 gap-2">
<Button
onClick={runDiagnostic}
disabled={loading}
className="w-full"
>
{loading && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
Diagnostic
</Button>
<Button
onClick={runRlsDiagnostic}
disabled={rlsLoading}
variant="outline"
className="w-full"
>
{rlsLoading && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
Diagnostic RLS
</Button>
</div>
</CardContent>
</Card>
{/* Réparation admin */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Shield className="h-5 w-5" />
Réparation admin
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-sm text-slate-600 dark:text-slate-400">
<p>🔧 <strong>Réparation automatique :</strong> Force la réinsertion de l'utilisateur dans admin_users.</p>
</div>
{fixError && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{fixError}</AlertDescription>
</Alert>
)}
{fixSuccess && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>Réparation réussie ! Redirection...</AlertDescription>
</Alert>
)}
<Button
onClick={handleFixAdmin}
disabled={fixLoading}
variant="outline"
className="w-full"
>
{fixLoading && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
Réparer les permissions
</Button>
</CardContent>
</Card>
{/* Connexion rapide */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<LogIn className="h-5 w-5" />
Connexion rapide
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label htmlFor="loginEmail">Email</Label>
<Input
id="loginEmail"
type="email"
placeholder="admin@example.com"
value={loginEmail}
onChange={(e) => setLoginEmail(e.target.value)}
className="mt-2"
/>
</div>
<div>
<Label htmlFor="loginPassword">Mot de passe</Label>
<Input
id="loginPassword"
type="password"
placeholder="Votre mot de passe"
value={loginPassword}
onChange={(e) => setLoginPassword(e.target.value)}
className="mt-2"
/>
</div>
{loginError && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{loginError}</AlertDescription>
</Alert>
)}
{loginSuccess && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>Connexion réussie ! Redirection...</AlertDescription>
</Alert>
)}
<Button
onClick={handleLogin}
disabled={loginLoading}
className="w-full"
>
{loginLoading && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
Se connecter
</Button>
<div className="text-sm text-slate-600 dark:text-slate-400">
<p>💡 <strong>Conseil :</strong> Utilisez les mêmes identifiants que ceux créés lors du setup.</p>
</div>
</CardContent>
</Card>
</div>
{(results || rlsResults) && (
<div className="mt-8 space-y-6">
<h3 className="text-lg font-semibold">Résultats du diagnostic</h3>
{/* Diagnostic côté serveur */}
{results && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
Diagnostic côté serveur
</CardTitle>
</CardHeader>
<CardContent>
{results.server.success ? (
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<strong>Utilisateur dans auth.users:</strong>
<span className="ml-2 text-green-600">✅ OUI</span>
</div>
<div>
<strong>Utilisateur dans admin_users:</strong>
<span className={`ml-2 ${results.server.inAdminUsers ? 'text-green-600' : 'text-red-600'}`}>
{results.server.inAdminUsers ? ' OUI' : ' NON'}
</span>
</div>
</div>
<div>
<strong>Détails utilisateur:</strong>
<pre className="bg-slate-100 dark:bg-slate-800 p-2 rounded mt-2 text-sm">
{JSON.stringify(results.server.user, null, 2)}
</pre>
</div>
{results.server.adminUser && (
<div>
<strong>Détails admin:</strong>
<pre className="bg-slate-100 dark:bg-slate-800 p-2 rounded mt-2 text-sm">
{JSON.stringify(results.server.adminUser, null, 2)}
</pre>
</div>
)}
<div>
<strong>Configuration:</strong>
<pre className="bg-slate-100 dark:bg-slate-800 p-2 rounded mt-2 text-sm">
{JSON.stringify(results.server.debug, null, 2)}
</pre>
</div>
</div>
) : (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{results.server.error}</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
)}
{/* Diagnostic côté client */}
{results && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<User className="h-5 w-5" />
Diagnostic côté client
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<strong>Utilisateur connecté:</strong>
<span className={`ml-2 ${results.client.currentUser ? 'text-green-600' : 'text-red-600'}`}>
{results.client.currentUser ? ' OUI' : ' NON'}
</span>
</div>
<div>
<strong>Est admin:</strong>
<span className={`ml-2 ${results.client.isAdmin ? 'text-green-600' : 'text-red-600'}`}>
{results.client.isAdmin ? ' OUI' : ' NON'}
</span>
</div>
<div>
<strong>Est super admin:</strong>
<span className={`ml-2 ${results.client.isSuperAdmin ? 'text-green-600' : 'text-red-600'}`}>
{results.client.isSuperAdmin ? ' OUI' : ' NON'}
</span>
</div>
</div>
{results.client.currentUser && (
<div>
<strong>Utilisateur connecté:</strong>
<pre className="bg-slate-100 dark:bg-slate-800 p-2 rounded mt-2 text-sm">
{JSON.stringify(results.client.currentUser, null, 2)}
</pre>
</div>
)}
{results.client.currentAdmin && (
<div>
<strong>Admin connecté:</strong>
<pre className="bg-slate-100 dark:bg-slate-800 p-2 rounded mt-2 text-sm">
{JSON.stringify(results.client.currentAdmin, null, 2)}
</pre>
</div>
)}
</div>
</CardContent>
</Card>
)}
{/* Résultats du diagnostic RLS */}
{rlsResults && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5" />
Diagnostic RLS Avancé
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<strong>Accès user_permissions (service):</strong>
<span className={`ml-2 ${rlsResults.adminTests.userPermissionsAccess ? 'text-green-600' : 'text-red-600'}`}>
{rlsResults.adminTests.userPermissionsAccess ? ' OUI' : ' NON'}
</span>
</div>
<div>
<strong>Utilisateur dans user_permissions:</strong>
<span className={`ml-2 ${rlsResults.adminTests.userExists ? 'text-green-600' : 'text-red-600'}`}>
{rlsResults.adminTests.userExists ? ' OUI' : ' NON'}
</span>
</div>
<div>
<strong>Accès user_permissions (client):</strong>
<span className={`ml-2 ${rlsResults.clientTests.canAccessUserPermissions ? 'text-green-600' : 'text-red-600'}`}>
{rlsResults.clientTests.canAccessUserPermissions ? ' OUI' : ' NON'}
</span>
</div>
<div>
<strong>Sélection utilisateur spécifique:</strong>
<span className={`ml-2 ${rlsResults.clientTests.canSelectSpecificUser ? 'text-green-600' : 'text-red-600'}`}>
{rlsResults.clientTests.canSelectSpecificUser ? ' OUI' : ' NON'}
</span>
</div>
</div>
{rlsResults.clientTests.rlsError && (
<div>
<strong>Erreur RLS:</strong>
<pre className="bg-red-50 dark:bg-red-900/20 p-2 rounded mt-2 text-sm text-red-800 dark:text-red-200">
{rlsResults.clientTests.rlsError}
</pre>
</div>
)}
<div>
<strong>Détails admin (service):</strong>
<pre className="bg-slate-100 dark:bg-slate-800 p-2 rounded mt-2 text-sm">
{JSON.stringify(rlsResults.adminTests, null, 2)}
</pre>
</div>
<div>
<strong>Tests client:</strong>
<pre className="bg-slate-100 dark:bg-slate-800 p-2 rounded mt-2 text-sm">
{JSON.stringify(rlsResults.clientTests, null, 2)}
</pre>
</div>
{/* Bouton de correction RLS */}
{rlsResults.clientTests.rlsError && rlsResults.clientTests.rlsError.includes('infinite recursion') && (
<div className="mt-4 p-4 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg">
<h4 className="font-semibold text-yellow-800 dark:text-yellow-200 mb-2">
🔧 Correction automatique disponible
</h4>
<p className="text-sm text-yellow-700 dark:text-yellow-300 mb-3">
Les politiques RLS causent une récursion infinie. Cliquez ci-dessous pour tenter une correction automatique.
</p>
{fixRlsError && (
<Alert variant="destructive" className="mb-3">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{fixRlsError}</AlertDescription>
</Alert>
)}
{fixRlsSuccess && (
<Alert className="mb-3">
<CheckCircle className="h-4 w-4" />
<AlertDescription>Correction RLS réussie ! Redirection...</AlertDescription>
</Alert>
)}
<Button
onClick={handleFixRls}
disabled={fixRlsLoading}
variant="outline"
className="w-full"
>
{fixRlsLoading && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
Corriger les politiques RLS
</Button>
</div>
)}
</div>
</CardContent>
</Card>
)}
{/* Recommandations */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Shield className="h-5 w-5" />
Recommandations
</CardTitle>
</CardHeader>
<CardContent>
{rlsResults && !rlsResults.clientTests.canAccessUserPermissions ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<strong>Problème RLS identifié :</strong> Les politiques RLS empêchent l'accès à admin_users côté client.
<br />
<strong>Solution :</strong> Les politiques RLS sont trop restrictives. Il faut les ajuster pour permettre l'accès aux admins connectés.
</AlertDescription>
</Alert>
) : results && !results.server.inUserPermissions ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<strong>Problème identifié :</strong> L'utilisateur existe dans auth.users mais pas dans user_permissions.
<br />
<strong>Solution :</strong> Relancez l'assistant de configuration pour ajouter l'utilisateur à la table user_permissions.
</AlertDescription>
</Alert>
) : results && !results.client.currentUser ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<strong>Problème identifié :</strong> Aucun utilisateur connecté côté client.
<br />
<strong>Solution :</strong> Utilisez le formulaire de connexion ci-dessus ou allez sur <code>/admin</code> pour vous connecter.
</AlertDescription>
</Alert>
) : results && !results.client.isAdmin ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
<strong>Problème identifié :</strong> L'utilisateur est connecté mais n'a pas les permissions admin.
<br />
<strong>Solution :</strong> Vérifiez que l'utilisateur est bien dans la table user_permissions avec les bonnes permissions.
</AlertDescription>
</Alert>
) : (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
<strong>Tout semble correct !</strong> L'utilisateur est connecté et a les permissions admin.
</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
</div>
)}
</div>
</div>
);
}