42 lines
1.5 KiB
JavaScript
42 lines
1.5 KiB
JavaScript
const path = require('path');
|
|
require('dotenv').config({ path: path.join(__dirname, '..', '.env') });
|
|
|
|
const prisma = require('../src/db');
|
|
const { isValidPhone, normalizePhone } = require('../src/lib/phone');
|
|
const { hashPassword } = require('../src/lib/passwords');
|
|
|
|
async function main() {
|
|
const name = String(process.env.SEED_ADMIN_NAME || 'Super Admin').trim();
|
|
const phone = normalizePhone(process.env.SEED_ADMIN_PHONE);
|
|
const password = String(process.env.SEED_ADMIN_PASSWORD || '');
|
|
if (!isValidPhone(phone)) {
|
|
throw new Error('SEED_ADMIN_PHONE must be a Sri Lankan mobile number');
|
|
}
|
|
if (password.length < 8) {
|
|
throw new Error('SEED_ADMIN_PASSWORD must be at least 8 characters');
|
|
}
|
|
|
|
const passwordHash = await hashPassword(password);
|
|
const existingAdmin = await prisma.user.findFirst({ where: { role: 'superAdmin' } });
|
|
const admin = existingAdmin
|
|
? await prisma.user.update({
|
|
where: { id: existingAdmin.id },
|
|
data: { name, phone, role: 'superAdmin', dealerId: null, passwordHash },
|
|
})
|
|
: await prisma.user.upsert({
|
|
where: { phone },
|
|
update: { name, role: 'superAdmin', dealerId: null, passwordHash },
|
|
create: { name, phone, role: 'superAdmin', passwordHash },
|
|
});
|
|
console.log(`Seeded super admin ${admin.name} (${admin.phone})`);
|
|
}
|
|
|
|
main()
|
|
.catch((error) => {
|
|
console.error(error);
|
|
process.exitCode = 1;
|
|
})
|
|
.finally(async () => {
|
|
await prisma.$disconnect();
|
|
});
|