refactor: add organizations system

This commit is contained in:
Mauricio Siu
2025-02-09 20:53:06 -06:00
parent fafc238e70
commit 8bd72a8a34
47 changed files with 359 additions and 171 deletions

View File

@@ -1,8 +1,10 @@
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin } from "better-auth/plugins";
import { admin, createAuthMiddleware, organization } from "better-auth/plugins";
import { db } from "../db";
import * as schema from "../db/schema";
import type { IncomingMessage } from "node:http";
import { eq } from "drizzle-orm";
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg",
@@ -11,5 +13,38 @@ export const auth = betterAuth({
emailAndPassword: {
enabled: true,
},
plugins: [admin()],
hooks: {
after: createAuthMiddleware(async (ctx) => {
if (ctx.path.startsWith("/sign-up")) {
const newSession = ctx.context.newSession;
await db
.update(schema.user)
.set({
role: "admin",
})
.where(eq(schema.user.id, newSession?.user?.id || ""));
}
}),
},
user: {
additionalFields: {},
},
plugins: [organization()],
});
export const validateRequest = async (request: IncomingMessage) => {
const session = await auth.api.getSession({
headers: new Headers({
cookie: request.headers.cookie || "",
}),
});
if (!session?.session || !session.user) {
return {
session: null,
user: null,
};
}
return session;
};