BA
Better Auth6mo ago
ab

Seeding an admin user

I want to seed an admin user in my Express app. export const auth = betterAuth({ appName: 'LaundryApp', basePath: '/api/auth', trustedOrigins: ['laundryapp://'], database: prismaAdapter(prisma, { provider: 'sqlite', }), plugins: [admin(), expo()], emailAndPassword: { enabled: true, disableSignUp: false, requireEmailVerification: false, minPasswordLength: 8, advanced: { generateId: false, }, maxPasswordLength: 128, autoSignIn: true, sendResetPassword: async ({ user, url, token }) => { console.log('Reset password URL:', url) // TODO }, resetPasswordTokenExpiresIn: 3600, // 1 hour password: { hash: async (password) => { const hashedPassword = await hash(password, 10) console.log(password) return hashedPassword }, verify: async ({ hash, password }) => { const isValid = await compare(password, hash) return isValid }, }, }, }) WHEN I TRY: auth.api.createUser({... I get UNAUTHORIZED ATTEMPTED WORKAROUND I created my user directly with prisma Note: I also added an account record that is linked to the user. But when i try to sign in the user from my frontend I get this : { "code": "INVALID_EMAIL_OR_PASSWORD", "message": "Invalid email or password" } My questions : Is there a diffrent way to login admins ?? I have checked the docs but not seen any Is it possible to seed user into the database using better-auth ?? Or do I have to do it manually and if so , how do i do it correctly
5 Replies
Ping
Ping6mo ago
Hey I do have a seeding library which may be able to help you out: https://www.better-auth-kit.com/docs/cli/seed
Better Auth Kit
Better Auth Kit
A handy collection of plugins, adapters, libraries and more.
Ping
Ping6mo ago
If you want more finegrain control over the random values in the seeding process, you can do something like this:
export const seed = Seed(async ({ get }) => {
const first_name = await get($.firstname());
const last_name = await get($.lastname());

const isBanned = await get($.randomBoolean({ probability: 0.1 }));


return {
test: table({
name: $.custom(() => `${first_name} ${last_name}`),
first_name: $.custom(() => first_name),
last_name: $.custom(() => last_name),

banned: $.custom(() => isBanned),
banReason: $.custom(() => isBanned ? "test" : null),
banExpires: $.custom(() => isBanned ? get($.randomDate("future")) : null),
}),
};
});
export const seed = Seed(async ({ get }) => {
const first_name = await get($.firstname());
const last_name = await get($.lastname());

const isBanned = await get($.randomBoolean({ probability: 0.1 }));


return {
test: table({
name: $.custom(() => `${first_name} ${last_name}`),
first_name: $.custom(() => first_name),
last_name: $.custom(() => last_name),

banned: $.custom(() => isBanned),
banReason: $.custom(() => isBanned ? "test" : null),
banExpires: $.custom(() => isBanned ? get($.randomDate("future")) : null),
}),
};
});
It's not documented yet.
ab
abOP6mo ago
Just checked it out its a great library. Though for my use-case I just need to seed a single user (Admin user). Let me try looking around if I get a solution I will post it here. If not I might have to roll my own auth
Jim-Y
Jim-Y4mo ago
@ab hi, did you find a solution to this?
bey9363
bey93632mo ago
@ab @Jim-Y Hi I just had this issue and came across this thread so thought I'd share what I did to be able to seed an admin user and have it work when logging in from frontend without getting the invalid email or password error. I'm using prisma and Next js. Setting the password I had followed the documentation at https://www.better-auth.com/docs/authentication/email-password.
import { auth } from "@/src/lib/auth"
import { prisma } from "@/src/lib/prisma"

const adminEmail = process.env.DEV_EMAIL
const adminPassword = process.env.DEV_PASSWORD
const adminName = process.env.DEV_NAME

function generateUserId(): string {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
let result = ""
for (let i = 0; i < 32; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}

export default async function seedUsers() {
if (!adminName || !adminEmail || !adminPassword) {
throw new Error("Admin name, email, and password must be set in environment variables")
}
const name = adminName;
const email = adminEmail;
const ctx = await auth.$context;
const passwordHash = await ctx.password.hash(adminPassword);
const userId = generateUserId();

const user = await prisma.user.upsert({
where: { email },
update: {},
create: {
id: userId,
email,
name,
emailVerified: true,
role: "ADMIN",
accounts: {
create: {
accountId: userId,
providerId: "credential",
password: passwordHash,
createdAt: new Date(),
updatedAt: new Date(),
},
},
},
include: {
accounts: true,
},
})

console.log("Admin user seeded:", userId)
return user
}
import { auth } from "@/src/lib/auth"
import { prisma } from "@/src/lib/prisma"

const adminEmail = process.env.DEV_EMAIL
const adminPassword = process.env.DEV_PASSWORD
const adminName = process.env.DEV_NAME

function generateUserId(): string {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
let result = ""
for (let i = 0; i < 32; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}

export default async function seedUsers() {
if (!adminName || !adminEmail || !adminPassword) {
throw new Error("Admin name, email, and password must be set in environment variables")
}
const name = adminName;
const email = adminEmail;
const ctx = await auth.$context;
const passwordHash = await ctx.password.hash(adminPassword);
const userId = generateUserId();

const user = await prisma.user.upsert({
where: { email },
update: {},
create: {
id: userId,
email,
name,
emailVerified: true,
role: "ADMIN",
accounts: {
create: {
accountId: userId,
providerId: "credential",
password: passwordHash,
createdAt: new Date(),
updatedAt: new Date(),
},
},
},
include: {
accounts: true,
},
})

console.log("Admin user seeded:", userId)
return user
}

Did you find this page helpful?