Add seed script to populate the database with admin user

This commit is contained in:
Moshfegh Hamedani 2026-02-10 12:13:22 -08:00
parent ee99c0b012
commit d7ab2c77dd
6 changed files with 90 additions and 0 deletions

View file

@ -7,6 +7,7 @@ export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
seed: "bun prisma/seed.ts",
},
datasource: {
url: process.env["DATABASE_URL"],

View file

@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "user" ADD COLUMN "role" TEXT NOT NULL DEFAULT 'agent';

View file

@ -0,0 +1,7 @@
-- CreateEnum
CREATE TYPE "Role" AS ENUM ('admin', 'agent');
-- AlterTable (cast existing text values to the new enum)
ALTER TABLE "user" ALTER COLUMN "role" DROP DEFAULT,
ALTER COLUMN "role" TYPE "Role" USING "role"::"Role",
ALTER COLUMN "role" SET DEFAULT 'agent';

View file

@ -13,12 +13,18 @@ datasource db {
provider = "postgresql"
}
enum Role {
admin
agent
}
model User {
id String @id
name String
email String @unique
emailVerified Boolean
image String?
role Role @default(agent)
createdAt DateTime
updatedAt DateTime
sessions Session[]

63
server/prisma/seed.ts Normal file
View file

@ -0,0 +1,63 @@
import "dotenv/config";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../src/generated/prisma/client";
import { Role } from "../src/generated/prisma/client";
import { hashPassword } from "better-auth/crypto";
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
const prisma = new PrismaClient({ adapter });
async function main() {
const email = process.env.SEED_ADMIN_EMAIL;
const password = process.env.SEED_ADMIN_PASSWORD;
if (!email || !password) {
throw new Error(
"SEED_ADMIN_EMAIL and SEED_ADMIN_PASSWORD must be set in .env"
);
}
const existing = await prisma.user.findUnique({ where: { email } });
if (existing) {
console.log(`Admin user ${email} already exists — skipping.`);
return;
}
const hashedPassword = await hashPassword(password);
const userId = crypto.randomUUID();
const now = new Date();
await prisma.$transaction([
prisma.user.create({
data: {
id: userId,
name: "Admin",
email,
emailVerified: false,
role: Role.admin,
createdAt: now,
updatedAt: now,
},
}),
prisma.account.create({
data: {
id: crypto.randomUUID(),
accountId: userId,
providerId: "credential",
userId,
password: hashedPassword,
createdAt: now,
updatedAt: now,
},
}),
]);
console.log(`Admin user ${email} created successfully.`);
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(() => prisma.$disconnect());

View file

@ -9,5 +9,16 @@ export const auth = betterAuth({
}),
emailAndPassword: {
enabled: true,
disableSignUp: true,
},
user: {
additionalFields: {
role: {
type: "string",
required: false,
defaultValue: "agent",
input: false,
},
},
},
});