aboutsummaryrefslogtreecommitdiffstats
path: root/packages/api/middlewares/auth.ts
blob: 7f39a6f924c28f6e710c5277b42b724d4d31e718 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { createMiddleware } from "hono/factory";
import { HTTPException } from "hono/http-exception";

import { AuthedContext, createCallerFactory } from "@karakeep/trpc";
import { appRouter } from "@karakeep/trpc/routers/_app";

const createCaller = createCallerFactory(appRouter);

export const authMiddleware = createMiddleware<{
  Variables: {
    ctx: AuthedContext;
    api: ReturnType<typeof createCaller>;
  };
}>(async (c, next) => {
  if (!c.var.ctx || !c.var.ctx.user || c.var.ctx.user === null) {
    throw new HTTPException(401, {
      message: "Unauthorized",
    });
  }
  c.set("api", createCaller(c.get("ctx")));
  await next();
});