zerobyte/app/server/modules/auth/auth.middleware.ts
Nico 451aed8983
Multi users (#381)
* feat(db): add support for multiple users and organizations

* feat: backfill entities with new organization id

* refactor: filter all backend queries to surface only organization specific entities

* refactor: each org has its own restic password

* test: ensure organization is created

* chore: pr feedbacks

* refactor: filter by org id in all places

* refactor: download restic password from stored db password

* refactor(navigation): use volume id in urls instead of name

* feat: disable registrations

* refactor(auth): bubble up auth error to hono

* refactor: use async local storage for cleaner context sharing

* refactor: enable user registration vs disabling it

* test: multi-org isolation

* chore: final cleanup
2026-01-20 22:28:22 +01:00

61 lines
1.7 KiB
TypeScript

import { createMiddleware } from "hono/factory";
import { auth } from "~/lib/auth";
import { db } from "~/server/db/db";
import { member } from "~/server/db/schema";
import { eq, and } from "drizzle-orm";
import { withContext } from "~/server/core/request-context";
declare module "hono" {
interface ContextVariableMap {
user: {
id: string;
username: string;
hasDownloadedResticPassword: boolean;
role?: string | null | undefined;
};
organizationId: string;
}
}
/**
* Middleware to require authentication
* Verifies the session cookie and attaches user to context
*/
export const requireAuth = createMiddleware(async (c, next) => {
const sess = await auth.api.getSession({
headers: c.req.raw.headers,
});
const { user, session } = sess ?? {};
const { activeOrganizationId } = session ?? {};
if (!user || !session || !activeOrganizationId) {
return c.json<unknown>({ message: "Invalid or expired session" }, 401);
}
c.set("user", user);
c.set("organizationId", activeOrganizationId);
await withContext({ organizationId: activeOrganizationId, userId: user.id }, async () => {
await next();
});
});
/**
* Middleware to require organization owner or admin role
* Verifies the user has the required role in the current organization
*/
export const requireOrgAdmin = createMiddleware(async (c, next) => {
const user = c.get("user");
const organizationId = c.get("organizationId");
const membership = await db.query.member.findFirst({
where: and(eq(member.userId, user.id), eq(member.organizationId, organizationId)),
});
if (!membership || (membership.role !== "owner" && membership.role !== "admin")) {
return c.json({ message: "Forbidden" }, 403);
}
await next();
});