File size: 992 Bytes
c09f67c | 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 | import type { Scope } from "@api/utils/scopes";
import type { MiddlewareHandler } from "hono";
export const withRequiredScope = (
...requiredScopes: Scope[]
): MiddlewareHandler => {
return async (c, next) => {
const scopes = c.get("scopes") as Scope[] | undefined;
if (!scopes) {
return c.json(
{
error: "Unauthorized",
description:
"No scopes found for the current user. Authentication is required.",
},
401,
);
}
// Check if user has at least one of the required scopes
const hasRequiredScope = requiredScopes.some((requiredScope) =>
scopes.includes(requiredScope),
);
if (!hasRequiredScope) {
return c.json(
{
error: "Forbidden",
description: `Insufficient permissions. Required scopes: ${requiredScopes.join(
", ",
)}. Your scopes: ${scopes.join(", ")}`,
},
403,
);
}
await next();
};
};
|