Skip to content

Commit 1c80b01

Browse files
committed
🛂 server: add org auth middleware
1 parent df2fe3c commit 1c80b01

3 files changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@exactly/server": patch
3+
---
4+
5+
🛂 add org auth middleware

‎server/middleware/org.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { createMiddleware } from "hono/factory";
2+
3+
import auth from "../utils/auth";
4+
5+
import type { BlankInput, Env, Input } from "hono/types";
6+
7+
export default function org<E extends Env = Env, P extends string = string, I extends Input = BlankInput>() {
8+
return createMiddleware<
9+
E & { Variables: { session: NonNullable<Awaited<ReturnType<typeof auth.api.getSession>>> } },
10+
P,
11+
I
12+
>(async (c, next) => {
13+
const session = await auth.api.getSession({ headers: c.req.raw.headers });
14+
if (!session) return c.json({ code: "unauthorized" }, 401);
15+
c.set("session", session);
16+
await next();
17+
});
18+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { Hono } from "hono";
2+
import { describe, expect, it, vi } from "vitest";
3+
4+
import org from "../../middleware/org";
5+
import betterAuth from "../../utils/auth";
6+
7+
describe("organization middleware", () => {
8+
it("returns unauthorized when no session is present", async () => {
9+
vi.spyOn(betterAuth.api, "getSession").mockResolvedValueOnce(null);
10+
const app = new Hono().get("/", org(), (c) => c.text("ok"));
11+
const response = await app.request("/");
12+
expect(response.status).toBe(401);
13+
await expect(response.json()).resolves.toStrictEqual({ code: "unauthorized" });
14+
});
15+
16+
it("passes through and exposes the session when authenticated", async () => {
17+
const fakeSession = { session: { id: "ses01", activeOrganizationId: "org01" }, user: { id: "user01" } };
18+
vi.spyOn(betterAuth.api, "getSession").mockResolvedValueOnce(fakeSession as never);
19+
const app = new Hono().get("/", org(), (c) => c.json(c.var.session));
20+
const response = await app.request("/");
21+
expect(response.status).toBe(200);
22+
await expect(response.json()).resolves.toStrictEqual(fakeSession);
23+
});
24+
});

0 commit comments

Comments
 (0)