improve security (change RLS, and allow table sensitive access only at server side, with supabase service key)
This commit is contained in:
@@ -1,160 +1,200 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
import { User } from '@supabase/supabase-js';
|
||||
import { authService } from '@/lib/auth';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { AlertCircle, Mail, Lock, Loader2 } from 'lucide-react';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Loader2, Lock, Mail, Eye, EyeOff } from 'lucide-react';
|
||||
|
||||
interface AuthGuardProps {
|
||||
children: React.ReactNode;
|
||||
requireSuperAdmin?: boolean;
|
||||
}
|
||||
|
||||
export default function AuthGuard({ children }: AuthGuardProps) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [authMode] = useState<'signin'>('signin');
|
||||
export default function AuthGuard({ children, requireSuperAdmin = false }: AuthGuardProps) {
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||
const [isAuthorized, setIsAuthorized] = useState(false);
|
||||
const [showLogin, setShowLogin] = useState(false);
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [authLoading, setAuthLoading] = useState(false);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const router = useRouter();
|
||||
const [isLoggingIn, setIsLoggingIn] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Vérifier l'état de l'authentification au chargement
|
||||
const checkUser = async () => {
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
setUser(user);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
checkUser();
|
||||
|
||||
// Écouter les changements d'authentification
|
||||
const { data: { subscription } } = supabase.auth.onAuthStateChange(
|
||||
async (event, session) => {
|
||||
setUser(session?.user ?? null);
|
||||
setLoading(false);
|
||||
}
|
||||
);
|
||||
|
||||
return () => subscription.unsubscribe();
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
const handleAuth = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setAuthLoading(true);
|
||||
setError('');
|
||||
setMessage('');
|
||||
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const { error } = await supabase.auth.signInWithPassword({
|
||||
email,
|
||||
password,
|
||||
});
|
||||
if (error) throw error;
|
||||
} catch (error: any) {
|
||||
setError(error.message);
|
||||
setIsLoading(true);
|
||||
|
||||
// Vérifier si l'utilisateur est connecté
|
||||
const user = await authService.getCurrentUser();
|
||||
if (!user) {
|
||||
setIsAuthenticated(false);
|
||||
setIsAuthorized(false);
|
||||
setShowLogin(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsAuthenticated(true);
|
||||
|
||||
// Vérifier les permissions
|
||||
if (requireSuperAdmin) {
|
||||
const isSuperAdmin = await authService.isSuperAdmin();
|
||||
setIsAuthorized(isSuperAdmin);
|
||||
} else {
|
||||
const isAdmin = await authService.isAdmin();
|
||||
setIsAuthorized(isAdmin);
|
||||
}
|
||||
|
||||
if (!isAuthorized) {
|
||||
setError('Vous n\'avez pas les permissions nécessaires pour accéder à cette page.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la vérification d\'authentification:', error);
|
||||
setIsAuthenticated(false);
|
||||
setIsAuthorized(false);
|
||||
setShowLogin(true);
|
||||
} finally {
|
||||
setAuthLoading(false);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSignOut = async () => {
|
||||
await supabase.auth.signOut();
|
||||
router.push('/');
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setIsLoggingIn(true);
|
||||
|
||||
try {
|
||||
await authService.signIn(email, password);
|
||||
await checkAuth();
|
||||
} catch (error: any) {
|
||||
console.error('Erreur de connexion:', error);
|
||||
setError(error.message || 'Erreur lors de la connexion');
|
||||
} finally {
|
||||
setIsLoggingIn(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await authService.signOut();
|
||||
setIsAuthenticated(false);
|
||||
setIsAuthorized(false);
|
||||
setShowLogin(true);
|
||||
router.push('/');
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la déconnexion:', error);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 dark:bg-slate-900 flex items-center justify-center">
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-4 text-slate-600 dark:text-slate-300" />
|
||||
<p className="text-slate-600 dark:text-slate-300">Chargement...</p>
|
||||
<Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">Vérification de l'authentification...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
if (!isAuthenticated || !isAuthorized) {
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 dark:bg-slate-900 flex items-center justify-center p-4">
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50 p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-2xl">Administration</CardTitle>
|
||||
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-blue-100">
|
||||
<Lock className="h-6 w-6 text-blue-600" />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Accès restreint</CardTitle>
|
||||
<CardDescription>
|
||||
Connectez-vous pour accéder à l'administration
|
||||
{requireSuperAdmin
|
||||
? 'Cette page nécessite des privilèges de super administrateur.'
|
||||
: 'Cette page nécessite une authentification administrateur.'
|
||||
}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent>
|
||||
<form onSubmit={handleAuth} className="space-y-4">
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-red-600 dark:text-red-400" />
|
||||
<p className="text-sm text-red-600 dark:text-red-400">{error}</p>
|
||||
{error && (
|
||||
<Alert className="mb-4" variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{showLogin && (
|
||||
<form onSubmit={handleLogin} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="admin@example.com"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="pl-10"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{message && (
|
||||
<div className="p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
|
||||
<p className="text-sm text-green-600 dark:text-green-400">{message}</p>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Mot de passe</Label>
|
||||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute left-3 top-3 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
placeholder="••••••••"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="pl-10"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email" className="flex items-center gap-2">
|
||||
<Mail className="w-4 h-4" />
|
||||
Email
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="admin@example.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password" className="flex items-center gap-2">
|
||||
<Lock className="w-4 h-4" />
|
||||
Mot de passe
|
||||
</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={authLoading}>
|
||||
{authLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Connexion...
|
||||
</>
|
||||
) : (
|
||||
'Se connecter'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isLoggingIn}
|
||||
>
|
||||
{isLoggingIn ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Connexion...
|
||||
</>
|
||||
) : (
|
||||
'Se connecter'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="mt-4 text-center">
|
||||
<Button variant="ghost" asChild className="text-sm">
|
||||
<Link href="/">Retour à l'accueil</Link>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => router.push('/')}
|
||||
className="w-full"
|
||||
>
|
||||
Retour à l'accueil
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -165,26 +205,21 @@ export default function AuthGuard({ children }: AuthGuardProps) {
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Header avec bouton de déconnexion */}
|
||||
<div className="bg-white dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700">
|
||||
<div className="container mx-auto px-4 py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm text-slate-600 dark:text-slate-300">
|
||||
Connecté en tant que :
|
||||
</span>
|
||||
<span className="text-sm font-medium text-slate-900 dark:text-slate-100">
|
||||
{user.email}
|
||||
</span>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={handleSignOut}>
|
||||
Se déconnecter
|
||||
</Button>
|
||||
</div>
|
||||
{/* Barre de navigation admin */}
|
||||
<div className="bg-white border-b px-4 py-2 flex justify-between items-center">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Lock className="h-4 w-4 text-blue-600" />
|
||||
<span className="font-medium text-sm">Administration</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleLogout}
|
||||
>
|
||||
Déconnexion
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Contenu protégé */}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user