Files
euchre_camp/scripts/create-admin-via-api.js
T

93 lines
2.9 KiB
JavaScript

const { PrismaClient } = require('@prisma/client');
const { betterAuth } = require('better-auth');
const { prismaAdapter } = require('better-auth/adapters/prisma');
const { PrismaPg } = require('@prisma/adapter-pg');
// Load environment variables from .env file
require('dotenv').config();
// Check if DATABASE_URL is set
if (!process.env.DATABASE_URL) {
console.error('❌ DATABASE_URL environment variable is not set');
console.error(' Please set DATABASE_URL in your environment or .env file');
console.error(' Example: DATABASE_URL="postgresql://user:password@localhost:5432/dbname"');
process.exit(1);
}
// Create PrismaClient with adapter (matching src/lib/prisma.ts)
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
const prisma = new PrismaClient({ adapter });
// Create Better Auth instance
const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: 'postgresql',
}),
emailAndPassword: {
enabled: true,
},
baseURL: process.env.BETTER_AUTH_URL || 'http://localhost:3000',
secret: process.env.BETTER_AUTH_SECRET || process.env.NEXTAUTH_SECRET || 'your-secret-key-here-change-this-in-production',
});
async function main() {
try {
// Test database connection first
console.log('Connecting to database...');
await prisma.$connect();
console.log('✅ Connected to database');
// Check if user exists
const existing = await prisma.user.findUnique({
where: { email: 'david@dhg.lol' }
});
if (existing) {
console.log('User exists, updating role to site_admin...');
await prisma.user.update({
where: { id: existing.id },
data: { role: 'site_admin' }
});
console.log('✅ User role updated to site_admin (superuser)');
console.log('\nSuperuser created successfully!');
console.log('Email: david@dhg.lol');
console.log('Password: adminadmin');
console.log('Role: site_admin');
return;
}
// Create user using Better Auth's internal method
// Better Auth uses bcrypt internally for password hashing
const signUpResult = await auth.api.signUpEmail({
body: {
email: 'david@dhg.lol',
password: 'adminadmin',
name: 'David Admin',
},
});
console.log('✅ Admin user created via Better Auth API!');
console.log(' Email:', signUpResult.user.email);
console.log(' Name:', signUpResult.user.name);
console.log(' Password: adminadmin');
// Update the user to have site_admin role (superuser)
await prisma.user.update({
where: { id: signUpResult.user.id },
data: { role: 'site_admin' }
});
console.log('✅ User role updated to site_admin (superuser)');
} catch (error) {
console.error('❌ Error:', error.message);
if (error.errors) {
console.error(' Details:', error.errors);
}
} finally {
await prisma.$disconnect();
}
}
main();