feat: add admin application setup with authentication and deployment configurations

This commit is contained in:
2026-10-17 14:51:59 +02:00
parent 3126a8ac36
commit 55d5fd7a39
6 changed files with 141 additions and 13 deletions

View File

@@ -42,15 +42,68 @@ export async function loginAdmin(
}
try {
// Search user by email (case-insensitive) or by exact name
const user = await prisma.user.findFirst({
where: {
OR: [
{ email: { equals: cleanIdentifier, mode: 'insensitive' } },
{ name: { equals: cleanIdentifier, mode: 'insensitive' } },
],
},
});
let user = null;
try {
// Search user by email (case-insensitive) or by exact name
user = await prisma.user.findFirst({
where: {
OR: [
{ email: { equals: cleanIdentifier, mode: 'insensitive' } },
{ name: { equals: cleanIdentifier, mode: 'insensitive' } },
],
},
});
} catch (queryErr: any) {
// If column adminRole does not exist in production database yet, auto-heal schema!
if (
queryErr?.message?.includes('adminRole') ||
queryErr?.message?.includes('column') ||
queryErr?.code === 'P2021' ||
queryErr?.code === 'P2022'
) {
console.log("⚠️ Colonnes manquantes détectées en production. Auto-migration de la table User...");
try {
await prisma.$executeRawUnsafe(`ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "adminRole" TEXT DEFAULT 'ADMIN';`);
await prisma.$executeRawUnsafe(`ALTER TABLE "User" ADD COLUMN IF NOT EXISTS "adminPermissions" TEXT[] DEFAULT ARRAY[]::TEXT[];`);
// Retry findFirst
user = await prisma.user.findFirst({
where: {
OR: [
{ email: { equals: cleanIdentifier, mode: 'insensitive' } },
{ name: { equals: cleanIdentifier, mode: 'insensitive' } },
],
},
});
} catch (alterErr) {
console.error("Auto-alter failed:", alterErr);
}
} else {
throw queryErr;
}
}
// Auto-bootstrap for production: If admin@afrohub.com is requested and does not exist in DB yet,
// create it automatically so that newly deployed production databases have a Super Admin immediately.
if (!user && (cleanIdentifier.toLowerCase() === 'admin@afrohub.com' || cleanIdentifier.toLowerCase() === 'admin')) {
try {
const initialPassword = process.env.ADMIN_INITIAL_PASSWORD || 'afrohub2025';
const hashedPassword = await bcrypt.hash(initialPassword, 10);
user = await prisma.user.create({
data: {
name: 'Admin Afrohub',
email: 'admin@afrohub.com',
password: hashedPassword,
role: 'ADMIN',
adminRole: 'SUPER_ADMIN',
adminPermissions: [],
emailVerified: true,
},
});
console.log('✅ Compte Super Admin auto-initialisé avec succès lors de la première connexion.');
} catch (e) {
console.error('Erreur auto-création super admin:', e);
}
}
if (!user) {
return {