mirror of
https://github.com/Portabase/portabase.git
synced 2026-07-14 11:16:13 +02:00
fix: endpoints
This commit is contained in:
+54
-51
@@ -1,18 +1,20 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { withApiKey, ApiKeyContext } from "@/lib/api-v1/middleware";
|
import { withApiKey } from "@/lib/api-v1/middleware";
|
||||||
import { getAccessibleAgentIds } from "@/lib/api-v1/acl";
|
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import * as drizzleDb from "@/db";
|
import * as drizzleDb from "@/db";
|
||||||
import { inArray, eq, count, and, or, isNull } from "drizzle-orm";
|
import { inArray, eq, count, and, or, isNull } from "drizzle-orm";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { slugify } from "@/utils/slugify";
|
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
|
import {createAgentService} from "@/features/agents/agents.action";
|
||||||
|
import { ActionError } from "@/lib/safe-actions/actions";
|
||||||
|
import {getAccessibleAgentIds} from "@/lib/api-v1/services/agents";
|
||||||
|
import {ApiKeyContext} from "@/lib/api-v1/types";
|
||||||
|
|
||||||
const log = logger.child({ module: "api/v1/agents" });
|
const log = logger.child({ module: "api/v1/agents" });
|
||||||
|
|
||||||
export const GET = withApiKey(async (_req: Request, ctx: ApiKeyContext) => {
|
export const GET = withApiKey(async (_req: Request, ctx: ApiKeyContext) => {
|
||||||
try {
|
try {
|
||||||
const agentIds = await getAccessibleAgentIds(ctx.userId);
|
const agentIds = await getAccessibleAgentIds(ctx.user);
|
||||||
|
|
||||||
if (agentIds.length === 0) {
|
if (agentIds.length === 0) {
|
||||||
return NextResponse.json({ data: [] });
|
return NextResponse.json({ data: [] });
|
||||||
@@ -37,76 +39,77 @@ export const GET = withApiKey(async (_req: Request, ctx: ApiKeyContext) => {
|
|||||||
|
|
||||||
const CreateAgentSchema = z.object({
|
const CreateAgentSchema = z.object({
|
||||||
name: z.string().min(1, "name is required"),
|
name: z.string().min(1, "name is required"),
|
||||||
description: z.string().min(1, "description is required"),
|
organizationId: z.string().uuid("organizationId must be a valid UUID").optional(),
|
||||||
organizationId: z.string().uuid("organizationId must be a valid UUID"),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const POST = withApiKey(async (req: Request, ctx: ApiKeyContext) => {
|
export const POST = withApiKey(
|
||||||
|
async (req: Request, ctx: ApiKeyContext) => {
|
||||||
try {
|
try {
|
||||||
let body: unknown;
|
const body = await req.json().catch(() => null);
|
||||||
try {
|
|
||||||
body = await req.json();
|
if (!body) {
|
||||||
} catch {
|
return NextResponse.json(
|
||||||
return NextResponse.json({ error: "Invalid JSON body" }, { status: 422 });
|
{ error: "Invalid JSON body" },
|
||||||
|
{ status: 422 }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const parsed = CreateAgentSchema.safeParse(body);
|
const parsed = CreateAgentSchema.safeParse(body);
|
||||||
|
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: parsed.error.issues[0].message },
|
{
|
||||||
|
error: parsed.error.issues[0]?.message ??
|
||||||
|
"Invalid payload",
|
||||||
|
},
|
||||||
{ status: 422 }
|
{ status: 422 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { name, description, organizationId } = parsed.data;
|
const { name, organizationId } = parsed.data;
|
||||||
|
|
||||||
if (!ctx.orgIds.includes(organizationId)) {
|
const org = ctx.organizations.find(
|
||||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
(org) => org.id === organizationId
|
||||||
|
);
|
||||||
|
|
||||||
|
if (
|
||||||
|
organizationId &&
|
||||||
|
(!org || !org.permissions.canManageAgents)
|
||||||
|
) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Forbidden" },
|
||||||
|
{ status: 403 }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const createdAgent = await db.transaction(async (tx) => {
|
const createdAgent = await createAgentService({
|
||||||
const slug = slugify(name);
|
|
||||||
|
|
||||||
const [existing] = await tx
|
|
||||||
.select({ count: count() })
|
|
||||||
.from(drizzleDb.schemas.agent)
|
|
||||||
.where(eq(drizzleDb.schemas.agent.slug, slug));
|
|
||||||
|
|
||||||
if (existing.count > 0) {
|
|
||||||
return null; // signal slug conflict
|
|
||||||
}
|
|
||||||
|
|
||||||
const [agent] = await tx
|
|
||||||
.insert(drizzleDb.schemas.agent)
|
|
||||||
.values({ name, description, slug, organizationId })
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
if (!agent) throw new Error("Failed to create agent");
|
|
||||||
|
|
||||||
await tx.insert(drizzleDb.schemas.organizationAgent).values({
|
|
||||||
organizationId,
|
organizationId,
|
||||||
agentId: agent.id,
|
data: {
|
||||||
|
name,
|
||||||
|
description: "",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return agent;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (createdAgent === null) {
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "An agent with this name already exists" },
|
{ data: createdAgent },
|
||||||
{ status: 422 }
|
{ status: 201 }
|
||||||
|
);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
if (error instanceof ActionError) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: error.message },
|
||||||
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({ data: createdAgent }, { status: 201 });
|
log.error({error},
|
||||||
} catch (error: any) {
|
"Error in POST /api/v1/agents"
|
||||||
if (error?.code === "23505") {
|
);
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "An agent with this name already exists" },
|
{ error: "Internal server error" },
|
||||||
{ status: 422 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
log.error({ error }, "Error in POST /api/v1/agents");
|
|
||||||
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
|
||||||
}
|
}
|
||||||
});
|
);
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { withApiKey, ApiKeyContext } from "@/lib/api-v1/middleware";
|
import { withApiKey } from "@/lib/api-v1/middleware";
|
||||||
import { getAccessibleDatabaseIds } from "@/lib/api-v1/acl";
|
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import * as drizzleDb from "@/db";
|
import * as drizzleDb from "@/db";
|
||||||
import { eq, and, isNull } from "drizzle-orm";
|
import { eq, and, isNull } from "drizzle-orm";
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
|
import {getAccessibleDatabaseIds} from "@/lib/api-v1/services/databases";
|
||||||
|
import {ApiKeyContext} from "@/lib/api-v1/types";
|
||||||
|
|
||||||
const log = logger.child({ module: "api/v1/databases/[id]/backup/[backupId]" });
|
const log = logger.child({ module: "api/v1/databases/[id]/backup/[backupId]" });
|
||||||
|
|
||||||
@@ -14,7 +15,7 @@ export const GET = withApiKey(
|
|||||||
const { id, backupId } = params ?? {};
|
const { id, backupId } = params ?? {};
|
||||||
if (!id || !backupId) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
if (!id || !backupId) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
|
||||||
const accessibleIds = await getAccessibleDatabaseIds(ctx.userId);
|
const accessibleIds = await getAccessibleDatabaseIds(ctx.user);
|
||||||
if (!accessibleIds.includes(id)) {
|
if (!accessibleIds.includes(id)) {
|
||||||
const exists = await db.query.database.findFirst({
|
const exists = await db.query.database.findFirst({
|
||||||
where: eq(drizzleDb.schemas.database.id, id),
|
where: eq(drizzleDb.schemas.database.id, id),
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { withApiKey, ApiKeyContext } from "@/lib/api-v1/middleware";
|
import { withApiKey } from "@/lib/api-v1/middleware";
|
||||||
import { getAccessibleDatabaseIds } from "@/lib/api-v1/acl";
|
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import * as drizzleDb from "@/db";
|
import * as drizzleDb from "@/db";
|
||||||
import { eq, desc, isNull, and } from "drizzle-orm";
|
import { eq, desc, isNull, and } from "drizzle-orm";
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
|
import {getAccessibleDatabaseIds} from "@/lib/api-v1/services/databases";
|
||||||
|
import {ApiKeyContext, ApiKeyContextUser} from "@/lib/api-v1/types";
|
||||||
|
|
||||||
const log = logger.child({ module: "api/v1/databases/[id]/backup" });
|
const log = logger.child({ module: "api/v1/databases/[id]/backup" });
|
||||||
|
|
||||||
async function resolveDatabaseAccess(id: string, userId: string) {
|
async function resolveDatabaseAccess(id: string, user: ApiKeyContextUser) {
|
||||||
const accessibleIds = await getAccessibleDatabaseIds(userId);
|
const accessibleIds = await getAccessibleDatabaseIds(user);
|
||||||
if (accessibleIds.includes(id)) return "ok";
|
if (accessibleIds.includes(id)) return "ok";
|
||||||
const exists = await db.query.database.findFirst({
|
const exists = await db.query.database.findFirst({
|
||||||
where: eq(drizzleDb.schemas.database.id, id),
|
where: eq(drizzleDb.schemas.database.id, id),
|
||||||
@@ -22,9 +23,10 @@ export const GET = withApiKey(
|
|||||||
async (_req: Request, ctx: ApiKeyContext, params?: Record<string, string>) => {
|
async (_req: Request, ctx: ApiKeyContext, params?: Record<string, string>) => {
|
||||||
try {
|
try {
|
||||||
const id = params?.id;
|
const id = params?.id;
|
||||||
|
|
||||||
if (!id) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
if (!id) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
|
||||||
const access = await resolveDatabaseAccess(id, ctx.userId);
|
const access = await resolveDatabaseAccess(id, ctx.user);
|
||||||
if (access === "forbidden") return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
if (access === "forbidden") return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||||
if (access === "not_found") return NextResponse.json({ error: "Not found" }, { status: 404 });
|
if (access === "not_found") return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
|
||||||
@@ -50,7 +52,7 @@ export const POST = withApiKey(
|
|||||||
const id = params?.id;
|
const id = params?.id;
|
||||||
if (!id) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
if (!id) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
|
||||||
const access = await resolveDatabaseAccess(id, ctx.userId);
|
const access = await resolveDatabaseAccess(id, ctx.user);
|
||||||
if (access === "forbidden") return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
if (access === "forbidden") return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||||
if (access === "not_found") return NextResponse.json({ error: "Not found" }, { status: 404 });
|
if (access === "not_found") return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { withApiKey, ApiKeyContext } from "@/lib/api-v1/middleware";
|
import { withApiKey } from "@/lib/api-v1/middleware";
|
||||||
import { getAccessibleDatabaseIds } from "@/lib/api-v1/acl";
|
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import * as drizzleDb from "@/db";
|
import * as drizzleDb from "@/db";
|
||||||
import { eq, and, isNull } from "drizzle-orm";
|
import { eq, and, isNull } from "drizzle-orm";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
|
import {ApiKeyContext} from "@/lib/api-v1/types";
|
||||||
|
import {getAccessibleDatabaseIds} from "@/lib/api-v1/services/databases";
|
||||||
|
|
||||||
const log = logger.child({ module: "api/v1/databases/[id]/restore" });
|
const log = logger.child({ module: "api/v1/databases/[id]/restore" });
|
||||||
|
|
||||||
@@ -20,7 +21,7 @@ export const POST = withApiKey(
|
|||||||
const id = params?.id;
|
const id = params?.id;
|
||||||
if (!id) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
if (!id) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
|
||||||
const accessibleIds = await getAccessibleDatabaseIds(ctx.userId);
|
const accessibleIds = await getAccessibleDatabaseIds(ctx.user);
|
||||||
if (!accessibleIds.includes(id)) {
|
if (!accessibleIds.includes(id)) {
|
||||||
const exists = await db.query.database.findFirst({
|
const exists = await db.query.database.findFirst({
|
||||||
where: eq(drizzleDb.schemas.database.id, id),
|
where: eq(drizzleDb.schemas.database.id, id),
|
||||||
@@ -63,7 +64,6 @@ export const POST = withApiKey(
|
|||||||
return NextResponse.json({ error: "Backup not found for this database" }, { status: 404 });
|
return NextResponse.json({ error: "Backup not found for this database" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate backupStorage belongs to backup and is successful
|
|
||||||
const backupStorage = await db.query.backupStorage.findFirst({
|
const backupStorage = await db.query.backupStorage.findFirst({
|
||||||
where: and(
|
where: and(
|
||||||
eq(drizzleDb.schemas.backupStorage.id, backupStorageId),
|
eq(drizzleDb.schemas.backupStorage.id, backupStorageId),
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { withApiKey, ApiKeyContext } from "@/lib/api-v1/middleware";
|
import { withApiKey } from "@/lib/api-v1/middleware";
|
||||||
import { getAccessibleDatabaseIds } from "@/lib/api-v1/acl";
|
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import * as drizzleDb from "@/db";
|
import * as drizzleDb from "@/db";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
|
import {getAccessibleDatabaseIds} from "@/lib/api-v1/services/databases";
|
||||||
|
import {ApiKeyContext} from "@/lib/api-v1/types";
|
||||||
|
|
||||||
const log = logger.child({ module: "api/v1/databases/[id]" });
|
const log = logger.child({ module: "api/v1/databases/[id]" });
|
||||||
|
|
||||||
@@ -14,7 +15,7 @@ export const GET = withApiKey(
|
|||||||
const id = params?.id;
|
const id = params?.id;
|
||||||
if (!id) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
if (!id) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
|
||||||
const accessibleIds = await getAccessibleDatabaseIds(ctx.userId);
|
const accessibleIds = await getAccessibleDatabaseIds(ctx.user);
|
||||||
if (!accessibleIds.includes(id)) {
|
if (!accessibleIds.includes(id)) {
|
||||||
const exists = await db.query.database.findFirst({
|
const exists = await db.query.database.findFirst({
|
||||||
where: eq(drizzleDb.schemas.database.id, id),
|
where: eq(drizzleDb.schemas.database.id, id),
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { withApiKey, ApiKeyContext } from "@/lib/api-v1/middleware";
|
import { withApiKey } from "@/lib/api-v1/middleware";
|
||||||
import { getAccessibleDatabaseIds } from "@/lib/api-v1/acl";
|
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import * as drizzleDb from "@/db";
|
import * as drizzleDb from "@/db";
|
||||||
import { eq, desc, and, isNull } from "drizzle-orm";
|
import { eq, desc, and, isNull } from "drizzle-orm";
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
|
import {ApiKeyContext} from "@/lib/api-v1/types";
|
||||||
|
import {getAccessibleDatabaseIds} from "@/lib/api-v1/services/databases";
|
||||||
|
|
||||||
const log = logger.child({ module: "api/v1/databases/[id]/status" });
|
const log = logger.child({ module: "api/v1/databases/[id]/status" });
|
||||||
|
|
||||||
@@ -14,7 +15,7 @@ export const GET = withApiKey(
|
|||||||
const id = params?.id;
|
const id = params?.id;
|
||||||
if (!id) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
if (!id) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
|
||||||
const accessibleIds = await getAccessibleDatabaseIds(ctx.userId);
|
const accessibleIds = await getAccessibleDatabaseIds(ctx.user);
|
||||||
if (!accessibleIds.includes(id)) {
|
if (!accessibleIds.includes(id)) {
|
||||||
const exists = await db.query.database.findFirst({
|
const exists = await db.query.database.findFirst({
|
||||||
where: eq(drizzleDb.schemas.database.id, id),
|
where: eq(drizzleDb.schemas.database.id, id),
|
||||||
@@ -26,7 +27,13 @@ export const GET = withApiKey(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const [latestBackup, latestRestoration] = await Promise.all([
|
const [database, latestBackup, latestRestoration] = await Promise.all([
|
||||||
|
db.query.database.findFirst({
|
||||||
|
where: and(
|
||||||
|
eq(drizzleDb.schemas.database.id, id),
|
||||||
|
isNull(drizzleDb.schemas.database.deletedAt)
|
||||||
|
)
|
||||||
|
}),
|
||||||
db.query.backup.findFirst({
|
db.query.backup.findFirst({
|
||||||
where: and(
|
where: and(
|
||||||
eq(drizzleDb.schemas.backup.databaseId, id),
|
eq(drizzleDb.schemas.backup.databaseId, id),
|
||||||
@@ -43,8 +50,14 @@ export const GET = withApiKey(
|
|||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
if (!database){
|
||||||
|
return NextResponse.json({ error: "Database not found" });
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
data: {
|
data: {
|
||||||
|
isWaitingForBackup: database.isWaitingForBackup,
|
||||||
|
lastContact: database.lastContact,
|
||||||
latestBackup: latestBackup ?? null,
|
latestBackup: latestBackup ?? null,
|
||||||
latestRestoration: latestRestoration ?? null,
|
latestRestoration: latestRestoration ?? null,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { withApiKey, ApiKeyContext } from "@/lib/api-v1/middleware";
|
import { withApiKey } from "@/lib/api-v1/middleware";
|
||||||
import { getAccessibleAgentIds } from "@/lib/api-v1/acl";
|
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import * as drizzleDb from "@/db";
|
import * as drizzleDb from "@/db";
|
||||||
import { inArray, and, isNull } from "drizzle-orm";
|
import { inArray, and, isNull } from "drizzle-orm";
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
|
import {getAccessibleAgentIds} from "@/lib/api-v1/services/agents";
|
||||||
|
import {ApiKeyContext} from "@/lib/api-v1/types";
|
||||||
|
|
||||||
const log = logger.child({ module: "api/v1/databases" });
|
const log = logger.child({ module: "api/v1/databases" });
|
||||||
|
|
||||||
export const GET = withApiKey(async (_req: Request, ctx: ApiKeyContext) => {
|
export const GET = withApiKey(async (_req: Request, ctx: ApiKeyContext) => {
|
||||||
try {
|
try {
|
||||||
const agentIds = await getAccessibleAgentIds(ctx.userId);
|
const agentIds = await getAccessibleAgentIds(ctx.user);
|
||||||
|
|
||||||
if (agentIds.length === 0) {
|
if (agentIds.length === 0) {
|
||||||
return NextResponse.json({ data: [] });
|
return NextResponse.json({ data: [] });
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"use server";
|
"use server";
|
||||||
import {ActionError, userAction} from "@/lib/safe-actions/actions";
|
import {action, ActionError, userAction} from "@/lib/safe-actions/actions";
|
||||||
import {AgentSchema} from "@/features/agents/agents.schema";
|
import {AgentSchema} from "@/features/agents/agents.schema";
|
||||||
import {z} from "zod";
|
import {z} from "zod";
|
||||||
import {eq, and, ne, count} from "drizzle-orm";
|
import {eq, and, ne, count} from "drizzle-orm";
|
||||||
@@ -16,23 +16,59 @@ const verifySlugUniqueness = async (slug: string, agentId?: string) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
type CreateAgentInput = {
|
||||||
|
organizationId?: string;
|
||||||
|
data: z.infer<typeof AgentSchema>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function createAgentService(input: CreateAgentInput) {
|
||||||
|
const slug = slugify(input.data.name);
|
||||||
|
|
||||||
|
await verifySlugUniqueness(slug);
|
||||||
|
|
||||||
|
const [createdAgent] = await db
|
||||||
|
.insert(drizzleDb.schemas.agent)
|
||||||
|
.values({
|
||||||
|
...input.data,
|
||||||
|
slug,
|
||||||
|
organizationId: input.organizationId,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
if (createdAgent && input.organizationId) {
|
||||||
|
await db.insert(drizzleDb.schemas.organizationAgent).values({
|
||||||
|
organizationId: input.organizationId,
|
||||||
|
agentId: createdAgent.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return createdAgent;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const createAgentAction = userAction.schema(
|
export const createAgentAction = userAction.schema(
|
||||||
z.object({
|
z.object({
|
||||||
organizationId: z.string().optional(),
|
organizationId: z.string().optional(),
|
||||||
data: AgentSchema,
|
data: AgentSchema,
|
||||||
})
|
})
|
||||||
).action(async ({parsedInput}) => {
|
).action(async ({parsedInput}) => {
|
||||||
const slug = slugify(parsedInput.data.name);
|
// const slug = slugify(parsedInput.data.name);
|
||||||
await verifySlugUniqueness(slug);
|
// await verifySlugUniqueness(slug);
|
||||||
|
//
|
||||||
|
// const [createdAgent] = await db.insert(drizzleDb.schemas.agent).values({...parsedInput.data, slug: slug, organizationId: parsedInput.organizationId}).returning();
|
||||||
|
//
|
||||||
|
// if (createdAgent && parsedInput.organizationId){
|
||||||
|
// await db.insert(drizzleDb.schemas.organizationAgent).values({
|
||||||
|
// organizationId: parsedInput.organizationId,
|
||||||
|
// agentId: createdAgent.id,
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
const createdAgent = await createAgentService(parsedInput);
|
||||||
|
|
||||||
const [createdAgent] = await db.insert(drizzleDb.schemas.agent).values({...parsedInput.data, slug: slug, organizationId: parsedInput.organizationId}).returning();
|
|
||||||
|
|
||||||
if (createdAgent && parsedInput.organizationId){
|
|
||||||
await db.insert(drizzleDb.schemas.organizationAgent).values({
|
|
||||||
organizationId: parsedInput.organizationId,
|
|
||||||
agentId: createdAgent.id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
data: createdAgent,
|
data: createdAgent,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { MemberWithUser } from "@/db/schemas/organization";
|
|
||||||
import { computeOrganizationPermissions } from "@/lib/acl/organization-acl";
|
import { computeOrganizationPermissions } from "@/lib/acl/organization-acl";
|
||||||
|
import {MemberWithUser} from "@/db/schema/03_organization";
|
||||||
|
|
||||||
export const useOrganizationPermissions = (
|
export const useOrganizationPermissions = (
|
||||||
activeMember: MemberWithUser | null,
|
activeMember: MemberWithUser | null,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { User } from "@/db/schemas/user";
|
|
||||||
import { computeSystemPermissions } from "@/lib/acl/system-acl";
|
import { computeSystemPermissions } from "@/lib/acl/system-acl";
|
||||||
|
import {User} from "@/db/schema/02_user";
|
||||||
|
|
||||||
export const useSystemPermissions = (user: User | null) => {
|
export const useSystemPermissions = (user: User | null) => {
|
||||||
return computeSystemPermissions(user);
|
return computeSystemPermissions(user);
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import {MemberWithUser} from "@/db/schema/03_organization";
|
import {MemberWithUser} from "@/db/schema/03_organization";
|
||||||
|
import {OrganizationRole} from "@/lib/acl/role";
|
||||||
|
|
||||||
|
|
||||||
export type OrganizationPermissions = {
|
export type OrganizationPermissions = {
|
||||||
role: string | null;
|
role: OrganizationRole | null;
|
||||||
isOwner: boolean;
|
isOwner: boolean;
|
||||||
isAdmin: boolean;
|
isAdmin: boolean;
|
||||||
isMember: boolean;
|
isMember: boolean;
|
||||||
@@ -19,7 +20,7 @@ export type OrganizationPermissions = {
|
|||||||
export const computeOrganizationPermissions = (
|
export const computeOrganizationPermissions = (
|
||||||
activeMember: MemberWithUser | null
|
activeMember: MemberWithUser | null
|
||||||
): OrganizationPermissions => {
|
): OrganizationPermissions => {
|
||||||
const role = activeMember?.role ?? null;
|
const role = (activeMember?.role as OrganizationRole) ?? null;
|
||||||
|
|
||||||
const isOwner = role === "owner";
|
const isOwner = role === "owner";
|
||||||
const isAdmin = role === "admin";
|
const isAdmin = role === "admin";
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { User } from "@/db/schemas/user";
|
|
||||||
import type { SystemRole } from "@/lib/acl/role";
|
import type { SystemRole } from "@/lib/acl/role";
|
||||||
|
import {User} from "@/db/schema/02_user";
|
||||||
|
|
||||||
export type SystemPermissions = {
|
export type SystemPermissions = {
|
||||||
role: SystemRole | null;
|
role: SystemRole | null;
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
import { db } from "@/db";
|
|
||||||
import * as drizzleDb from "@/db";
|
|
||||||
import { eq, inArray, and, or, isNull } from "drizzle-orm";
|
|
||||||
|
|
||||||
export async function getAccessibleAgentIds(userId: string): Promise<string[]> {
|
|
||||||
const memberships = await db.query.member.findMany({
|
|
||||||
where: eq(drizzleDb.schemas.member.userId, userId),
|
|
||||||
columns: { organizationId: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
if (memberships.length === 0) return [];
|
|
||||||
|
|
||||||
const orgIds = memberships.map((m) => m.organizationId);
|
|
||||||
const isActiveAgent = or(
|
|
||||||
eq(drizzleDb.schemas.agent.isArchived, false),
|
|
||||||
isNull(drizzleDb.schemas.agent.isArchived)
|
|
||||||
);
|
|
||||||
|
|
||||||
// Path 1: via organizationAgent junction table
|
|
||||||
const orgAgents = await db.query.organizationAgent.findMany({
|
|
||||||
where: inArray(drizzleDb.schemas.organizationAgent.organizationId, orgIds),
|
|
||||||
columns: { agentId: true },
|
|
||||||
});
|
|
||||||
const junctionAgentIds = orgAgents.map((oa) => oa.agentId);
|
|
||||||
|
|
||||||
// Path 2: via agent.organizationId direct FK
|
|
||||||
const directAgents = await db.query.agent.findMany({
|
|
||||||
where: and(
|
|
||||||
inArray(drizzleDb.schemas.agent.organizationId, orgIds),
|
|
||||||
isActiveAgent
|
|
||||||
),
|
|
||||||
columns: { id: true },
|
|
||||||
});
|
|
||||||
const directAgentIds = directAgents.map((a) => a.id);
|
|
||||||
|
|
||||||
const allAgentIds = [...new Set([...junctionAgentIds, ...directAgentIds])];
|
|
||||||
if (allAgentIds.length === 0) return [];
|
|
||||||
|
|
||||||
// Filter junction-path agents by active status
|
|
||||||
const agents = await db.query.agent.findMany({
|
|
||||||
where: and(
|
|
||||||
inArray(drizzleDb.schemas.agent.id, allAgentIds),
|
|
||||||
isActiveAgent
|
|
||||||
),
|
|
||||||
columns: { id: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
return agents.map((a) => a.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAccessibleDatabaseIds(userId: string): Promise<string[]> {
|
|
||||||
const agentIds = await getAccessibleAgentIds(userId);
|
|
||||||
if (agentIds.length === 0) return [];
|
|
||||||
|
|
||||||
const databases = await db.query.database.findMany({
|
|
||||||
where: and(
|
|
||||||
inArray(drizzleDb.schemas.database.agentId, agentIds),
|
|
||||||
isNull(drizzleDb.schemas.database.deletedAt)
|
|
||||||
),
|
|
||||||
columns: { id: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
return databases.map((d) => d.id);
|
|
||||||
}
|
|
||||||
@@ -3,13 +3,13 @@ import { auth } from "@/lib/auth/auth";
|
|||||||
import * as drizzleDb from "@/db";
|
import * as drizzleDb from "@/db";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
|
import {computeOrganizationPermissions} from "@/lib/acl/organization-acl";
|
||||||
|
import {db} from "@/db";
|
||||||
|
import {computeSystemPermissions} from "@/lib/acl/system-acl";
|
||||||
|
import {ApiKeyContext} from "@/lib/api-v1/types";
|
||||||
|
|
||||||
const log = logger.child({ module: "api-v1/middleware" });
|
const log = logger.child({ module: "api-v1/middleware" });
|
||||||
|
|
||||||
export type ApiKeyContext = {
|
|
||||||
userId: string;
|
|
||||||
orgIds: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
type ApiKeyHandler = (
|
type ApiKeyHandler = (
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -56,13 +56,39 @@ export function withApiKey(handler: ApiKeyHandler) {
|
|||||||
|
|
||||||
const memberships = await drizzleDb.db.query.member.findMany({
|
const memberships = await drizzleDb.db.query.member.findMany({
|
||||||
where: eq(drizzleDb.schemas.member.userId, userId),
|
where: eq(drizzleDb.schemas.member.userId, userId),
|
||||||
columns: { organizationId: true },
|
with: {
|
||||||
|
user: true
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const orgIds = memberships.map((m) => m.organizationId);
|
const organizations = await Promise.all(
|
||||||
|
memberships.map(async (m) => {
|
||||||
|
return {
|
||||||
|
id: m.organizationId,
|
||||||
|
permissions: computeOrganizationPermissions(m),
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const userFetched = await db.query.user.findFirst({
|
||||||
|
where: eq(drizzleDb.schemas.user.id, userId),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
if (!userFetched) {
|
||||||
|
throw new Error("Unable to find user")
|
||||||
|
}
|
||||||
|
|
||||||
|
const userPermissions = computeSystemPermissions(userFetched)
|
||||||
|
|
||||||
|
const user = {
|
||||||
|
id: userFetched.id,
|
||||||
|
permissions: userPermissions,
|
||||||
|
}
|
||||||
|
|
||||||
const resolvedParams = context?.params ? await context.params : {};
|
const resolvedParams = context?.params ? await context.params : {};
|
||||||
|
|
||||||
return handler(req, { userId, orgIds }, resolvedParams);
|
return handler(req, { user, organizations }, resolvedParams);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.error({ error: err }, "Error in withApiKey middleware");
|
log.error({ error: err }, "Error in withApiKey middleware");
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { db } from "@/db";
|
||||||
|
import * as drizzleDb from "@/db";
|
||||||
|
import { eq, inArray, and, or, isNull } from "drizzle-orm";
|
||||||
|
import {ApiKeyContextUser} from "@/lib/api-v1/types";
|
||||||
|
|
||||||
|
export async function getAccessibleAgentIds(
|
||||||
|
user: ApiKeyContextUser
|
||||||
|
): Promise<string[]> {
|
||||||
|
|
||||||
|
const memberships = await db.query.member.findMany({
|
||||||
|
where: and(
|
||||||
|
eq(drizzleDb.schemas.member.userId, user.id),
|
||||||
|
or(
|
||||||
|
eq(drizzleDb.schemas.member.role, "admin"),
|
||||||
|
eq(drizzleDb.schemas.member.role, "owner")
|
||||||
|
)
|
||||||
|
),
|
||||||
|
columns: { organizationId: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const orgIds = memberships.map((m) => m.organizationId);
|
||||||
|
|
||||||
|
if (orgIds.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const isActiveAgent = or(
|
||||||
|
eq(drizzleDb.schemas.agent.isArchived, false),
|
||||||
|
isNull(drizzleDb.schemas.agent.isArchived)
|
||||||
|
);
|
||||||
|
|
||||||
|
const orgAgents = await db.query.organizationAgent.findMany({
|
||||||
|
where: inArray(
|
||||||
|
drizzleDb.schemas.organizationAgent.organizationId,
|
||||||
|
orgIds
|
||||||
|
),
|
||||||
|
columns: { agentId: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const junctionAgentIds = orgAgents.map((oa) => oa.agentId);
|
||||||
|
|
||||||
|
let directAgentIds: string[] = [];
|
||||||
|
|
||||||
|
if (user.permissions.isAdmin || user.permissions.isSuperAdmin) {
|
||||||
|
const directAgents = await db.query.agent.findMany({
|
||||||
|
where: isActiveAgent,
|
||||||
|
columns: { id: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
directAgentIds = directAgents.map((a) => a.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const allAgentIds = [
|
||||||
|
...new Set([
|
||||||
|
...junctionAgentIds,
|
||||||
|
...directAgentIds,
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
|
||||||
|
if (allAgentIds.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const agents = await db.query.agent.findMany({
|
||||||
|
where: and(
|
||||||
|
inArray(drizzleDb.schemas.agent.id, allAgentIds),
|
||||||
|
isActiveAgent
|
||||||
|
),
|
||||||
|
columns: { id: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return agents.map((a) => a.id);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { db } from "@/db";
|
||||||
|
import * as drizzleDb from "@/db";
|
||||||
|
import { eq, inArray, and, or, isNull } from "drizzle-orm";
|
||||||
|
import {getAccessibleAgentIds} from "@/lib/api-v1/services/agents";
|
||||||
|
import {ApiKeyContextUser} from "@/lib/api-v1/types";
|
||||||
|
|
||||||
|
|
||||||
|
export async function getAccessibleDatabaseIds(user: ApiKeyContextUser): Promise<string[]> {
|
||||||
|
const agentIds = await getAccessibleAgentIds(user);
|
||||||
|
if (agentIds.length === 0) return [];
|
||||||
|
|
||||||
|
const databases = await db.query.database.findMany({
|
||||||
|
where: and(
|
||||||
|
inArray(drizzleDb.schemas.database.agentId, agentIds),
|
||||||
|
isNull(drizzleDb.schemas.database.deletedAt)
|
||||||
|
),
|
||||||
|
columns: { id: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return databases.map((d) => d.id);
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import {SystemPermissions} from "@/lib/acl/system-acl";
|
||||||
|
import {OrganizationPermissions} from "@/lib/acl/organization-acl";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export type ApiKeyContextUser = {
|
||||||
|
id: string;
|
||||||
|
permissions: SystemPermissions;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ApiKeyContextOrganizations = {
|
||||||
|
id: string;
|
||||||
|
permissions: OrganizationPermissions
|
||||||
|
}[];
|
||||||
|
|
||||||
|
export type ApiKeyContext = {
|
||||||
|
user: ApiKeyContextUser;
|
||||||
|
organizations: ApiKeyContextOrganizations
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user