role-based authorization

Hi, I'm implementing role-based access control in my admin panel and facing a challenge. I need to restrict access so only users with user.metadata.role === "ADMIN" can log in. What's the recommended approach in Better Auth to: - Validate a user's role/permissions BEFORE creating a session? - Is there any equivalent to Next Auth's authorize callback that lets me check custom conditions during login?
Solution:
thanks @Soheel i tried with hooks (not databasehooks), it worked 🎉 I added this to my auth config ```ts hooks: {...
Jump to solution
3 Replies
Soheel
Soheel•4mo ago
I'd assum the hooks https://www.better-auth.com/docs/reference/options#hooks are what suit you best here
Options | Better Auth
Better Auth configuration options reference.
Soheel
Soheel•4mo ago
Options | Better Auth
Better Auth configuration options reference.
Solution
saurabhdoteth 🇮🇳
thanks @Soheel i tried with hooks (not databasehooks), it worked 🎉 I added this to my auth config
hooks: {
before: createAuthMiddleware(async (ctx) => {
if (ctx.path !== "/sign-in/email") {
return;
}

const email = ctx.body?.email;
if (email) {
const dbUser = await findUserByEmail(email);
if (!dbUser || dbUser.metadata?.role !== "ADMIN") {
throw new APIError("UNAUTHORIZED", {
message: "Only administrators can access this application.",
});
}
}
}),
}
hooks: {
before: createAuthMiddleware(async (ctx) => {
if (ctx.path !== "/sign-in/email") {
return;
}

const email = ctx.body?.email;
if (email) {
const dbUser = await findUserByEmail(email);
if (!dbUser || dbUser.metadata?.role !== "ADMIN") {
throw new APIError("UNAUTHORIZED", {
message: "Only administrators can access this application.",
});
}
}
}),
}

Did you find this page helpful?