mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-31 20:32:20 +03:00
56 lines
1.5 KiB
TypeScript
56 lines
1.5 KiB
TypeScript
import { isAuthRequired, isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";
|
|
import { createErrorResponse } from "@/lib/api/errorResponse";
|
|
import { extractApiKey, isValidApiKey } from "@/sse/services/auth";
|
|
import { getApiKeyMetadata } from "@/lib/db/apiKeys";
|
|
|
|
export const MANAGE_SCOPE = "manage";
|
|
|
|
export function hasManageScope(scopes: string[] = []): boolean {
|
|
return scopes.includes("manage") || scopes.includes("admin");
|
|
}
|
|
|
|
export async function requireManagementAuth(request: Request): Promise<Response | null> {
|
|
if (!(await isAuthRequired(request))) {
|
|
return null;
|
|
}
|
|
|
|
if (await isDashboardSessionAuthenticated(request)) {
|
|
return null;
|
|
}
|
|
|
|
const apiKey = extractApiKey(request);
|
|
if (apiKey) {
|
|
let meta: Awaited<ReturnType<typeof getApiKeyMetadata>>;
|
|
try {
|
|
if (!(await isValidApiKey(apiKey))) {
|
|
return createErrorResponse({
|
|
status: 401,
|
|
message: "Invalid API key",
|
|
type: "invalid_request",
|
|
});
|
|
}
|
|
meta = await getApiKeyMetadata(apiKey);
|
|
} catch {
|
|
return createErrorResponse({
|
|
status: 503,
|
|
message: "Service temporarily unavailable",
|
|
type: "server_error",
|
|
});
|
|
}
|
|
|
|
if (meta && hasManageScope(meta.scopes)) return null;
|
|
|
|
return createErrorResponse({
|
|
status: 403,
|
|
message: "API key lacks 'manage' scope. Enable it in the API Manager dashboard.",
|
|
type: "invalid_request",
|
|
});
|
|
}
|
|
|
|
return createErrorResponse({
|
|
status: 401,
|
|
message: "Authentication required",
|
|
type: "invalid_request",
|
|
});
|
|
}
|