improve security (change RLS, and allow table sensitive access only at server side, with supabase service key)

This commit is contained in:
Yannick Le Duc
2025-08-26 14:51:15 +02:00
parent 4119875f48
commit 0093f4edba
17 changed files with 1240 additions and 285 deletions

117
src/lib/auth.ts Normal file
View File

@@ -0,0 +1,117 @@
import { supabase } from './supabase';
import { supabaseAdmin } from './supabase-admin';
export interface AdminUser {
id: string;
email: string;
role: 'admin' | 'super_admin';
created_at: string;
updated_at: string;
}
export const authService = {
// Vérifier si l'utilisateur actuel est connecté
async getCurrentUser() {
const { data: { user }, error } = await supabase.auth.getUser();
if (error) throw error;
return user;
},
// Vérifier si l'utilisateur actuel est admin
async isAdmin(): Promise<boolean> {
try {
const user = await this.getCurrentUser();
if (!user) return false;
const { data, error } = await supabase
.from('admin_users')
.select('id')
.eq('id', user.id)
.single();
if (error) return false;
return !!data;
} catch {
return false;
}
},
// Vérifier si l'utilisateur actuel est super admin
async isSuperAdmin(): Promise<boolean> {
try {
const user = await this.getCurrentUser();
if (!user) return false;
const { data, error } = await supabase
.from('admin_users')
.select('id')
.eq('id', user.id)
.eq('role', 'super_admin')
.single();
if (error) return false;
return !!data;
} catch {
return false;
}
},
// Obtenir les informations de l'admin actuel
async getCurrentAdmin(): Promise<AdminUser | null> {
try {
const user = await this.getCurrentUser();
if (!user) return null;
const { data, error } = await supabase
.from('admin_users')
.select('*')
.eq('id', user.id)
.single();
if (error) return null;
return data;
} catch {
return null;
}
},
// Connexion
async signIn(email: string, password: string) {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) throw error;
return data;
},
// Déconnexion
async signOut() {
const { error } = await supabase.auth.signOut();
if (error) throw error;
},
// Lister tous les admins (pour les super admins)
async getAllAdmins(): Promise<AdminUser[]> {
const { data, error } = await supabase
.from('admin_users')
.select('*')
.order('created_at', { ascending: false });
if (error) throw error;
return data || [];
},
// Changer le rôle d'un admin (pour les super admins)
async updateAdminRole(adminId: string, role: 'admin' | 'super_admin') {
const { data, error } = await supabaseAdmin
.from('admin_users')
.update({ role })
.eq('id', adminId)
.select()
.single();
if (error) throw error;
return data;
}
};