1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
import { createMiddleware } from "hono/factory";
import { HTTPException } from "hono/http-exception";
import { AuthedContext, Context, createCallerFactory } from "@karakeep/trpc";
import { appRouter } from "@karakeep/trpc/routers/_app";
const createCaller = createCallerFactory(appRouter);
export const unauthedMiddleware = createMiddleware<{
Variables: {
ctx: Context;
api: ReturnType<typeof createCaller>;
};
}>(async (c, next) => {
if (!c.var.ctx) {
throw new HTTPException(401, {
message: "Unauthorized",
});
}
c.set("api", createCaller(c.get("ctx")));
await next();
});
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();
});
export const adminAuthMiddleware = 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",
});
}
if (c.var.ctx.user.role !== "admin") {
throw new HTTPException(403, {
message: "Forbidden - Admin access required",
});
}
c.set("api", createCaller(c.get("ctx")));
await next();
});
|