Only login if specific field set to true

Hey there, Just looking for easiest way to enforce an "approved" boolean being true in the database to allow a user to login. Is it possible via BetterAuth or do I need to just force them to sign out manually?
1 Reply
Sam
SamOP4mo ago
My ideal scenario is reject them with an error message on the sign in page saying your account is still being approved Solved, for future reference:
import { createAuthMiddleware } from "better-auth/api";
import { type BetterAuthPlugin } from "better-auth";
import { APIError } from "better-auth/api";
import { db } from "@/server/db";

export const approvalCheckPlugin = (): BetterAuthPlugin => ({
id: "approval-check-plugin",
hooks: {
before: [
{
matcher: (context) => context.path === "/sign-in/email",
handler: createAuthMiddleware(async (ctx) => {
const { email } = ctx.body;

const user = await db.user.findFirst({
where: {
email: email as string
},
select: {
approved: true
}
})

if (user && !user.approved) {
throw new APIError("FORBIDDEN", {
message: "Your account has not been approved yet. Please wait for approval.",
});
}

return {context: ctx};
}),
},
],
},
});
import { createAuthMiddleware } from "better-auth/api";
import { type BetterAuthPlugin } from "better-auth";
import { APIError } from "better-auth/api";
import { db } from "@/server/db";

export const approvalCheckPlugin = (): BetterAuthPlugin => ({
id: "approval-check-plugin",
hooks: {
before: [
{
matcher: (context) => context.path === "/sign-in/email",
handler: createAuthMiddleware(async (ctx) => {
const { email } = ctx.body;

const user = await db.user.findFirst({
where: {
email: email as string
},
select: {
approved: true
}
})

if (user && !user.approved) {
throw new APIError("FORBIDDEN", {
message: "Your account has not been approved yet. Please wait for approval.",
});
}

return {context: ctx};
}),
},
],
},
});

Did you find this page helpful?