Skip to content

Instantly share code, notes, and snippets.

@darklight9811
Created February 23, 2025 17:45
Show Gist options
  • Select an option

  • Save darklight9811/d94a3e66daf7966f2dc49b3858ad4c5e to your computer and use it in GitHub Desktop.

Select an option

Save darklight9811/d94a3e66daf7966f2dc49b3858ad4c5e to your computer and use it in GitHub Desktop.
import { auth } from "auth/helpers/auth";
import { createMiddleware } from "hono/factory";
type Session = typeof auth.$Infer.Session;
export function authMiddleware<Type extends "optional" | "guest" | "admin" | "required">(
type: Type = "required" as Type,
) {
return createMiddleware<{
Variables: Type extends "optional"
? {
user: Session["user"] | undefined;
session: Session["session"] | undefined;
}
: Type extends "guest"
? {
user: undefined;
session: undefined;
}
: {
user: Session["user"];
session: Session["session"];
};
}>(async (c, next) => {
if (c.req.method === "OPTIONS" || (type === "optional" && !c.req.header("authorization"))) return next();
const session = await auth.api.getSession({
headers: c.req.raw.headers as Headers,
});
if (!session) {
if (["admin", "required"].includes(type)) return c.json({ error: "Unauthorized" }, 401);
c.set("user", undefined);
c.set("session", undefined);
return next();
}
c.set("user", session.user);
c.set("session", session.session);
if (type === "guest") return c.json({ error: "Unauthorized" }, 401);
if (type === "admin" && session.user.type === "guest") return c.json({ error: "Unauthorized" }, 401);
return next();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment