Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(api): implement workspace access middleware for project routes

Andrej Acevski81c3c859e8ff
diff --git a/apps/api/src/project/controllers/delete-project.ts b/apps/api/src/project/controllers/delete-project.ts
index 916a13c9d..3e5df1ee6 100644
--- a/apps/api/src/project/controllers/delete-project.ts
+++ b/apps/api/src/project/controllers/delete-project.ts
@@ -1,19 +1,22 @@
-import { eq } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { projectTable } from "../../database/schema";
-async function deleteProject(id: string) {
+async function deleteProject(id: string, workspaceId: string) {
const [existingProject] = await db
.select()
.from(projectTable)
- .where(eq(projectTable.id, id));
+ .where(
+ and(eq(projectTable.id, id), eq(projectTable.workspaceId, workspaceId)),
+ );
const isProjectExisting = Boolean(existingProject);
if (!isProjectExisting) {
throw new HTTPException(404, {
- message: "Project doesn't exist",
+ message:
+ "Project doesn't exist or doesn't belong to the specified workspace",
});
}
diff --git a/apps/api/src/project/controllers/update-project.ts b/apps/api/src/project/controllers/update-project.ts
index 6e42286c4..722de1266 100644
--- a/apps/api/src/project/controllers/update-project.ts
+++ b/apps/api/src/project/controllers/update-project.ts
@@ -1,4 +1,4 @@
-import { eq } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { projectTable } from "../../database/schema";
@@ -10,17 +10,21 @@ async function updateProject(
slug: string,
description: string,
isPublic: boolean,
+ workspaceId: string,
) {
const [existingProject] = await db
.select()
.from(projectTable)
- .where(eq(projectTable.id, id));
+ .where(
+ and(eq(projectTable.id, id), eq(projectTable.workspaceId, workspaceId)),
+ );
const isProjectExisting = Boolean(existingProject);
if (!isProjectExisting) {
throw new HTTPException(404, {
- message: "Project doesn't exist",
+ message:
+ "Project doesn't exist or doesn't belong to the specified workspace",
});
}
diff --git a/apps/api/src/project/index.ts b/apps/api/src/project/index.ts
index 631fef7ea..302767e4f 100644
--- a/apps/api/src/project/index.ts
+++ b/apps/api/src/project/index.ts
@@ -2,7 +2,7 @@ import { Hono } from "hono";
import { describeRoute, resolver, validator } from "hono-openapi";
import * as v from "valibot";
import { projectSchema } from "../schemas";
-import { validateWorkspaceAccess } from "../utils/validate-workspace-access";
+import { workspaceAccess } from "../utils/workspace-access-middleware";
import createProjectCtrl from "./controllers/create-project";
import deleteProjectCtrl from "./controllers/delete-project";
import getProjectCtrl from "./controllers/get-project";
@@ -12,6 +12,7 @@ import updateProjectCtrl from "./controllers/update-project";
const project = new Hono<{
Variables: {
userId: string;
+ workspaceId: string;
};
}>()
.get(
@@ -30,10 +31,9 @@ const project = new Hono<{
},
}),
validator("query", v.object({ workspaceId: v.string() })),
+ workspaceAccess.fromQuery(),
async (c) => {
- const { workspaceId } = c.req.valid("query");
- const userId = c.get("userId");
- await validateWorkspaceAccess(userId, workspaceId);
+ const workspaceId = c.get("workspaceId");
const projects = await getProjectsCtrl(workspaceId);
return c.json(projects);
},
@@ -62,10 +62,10 @@ const project = new Hono<{
slug: v.string(),
}),
),
+ workspaceAccess.fromBody(),
async (c) => {
- const { name, workspaceId, icon, slug } = c.req.valid("json");
- const userId = c.get("userId");
- await validateWorkspaceAccess(userId, workspaceId);
+ const { name, icon, slug } = c.req.valid("json");
+ const workspaceId = c.get("workspaceId");
const newProject = await createProjectCtrl(workspaceId, name, icon, slug);
return c.json(newProject);
},
@@ -86,10 +86,11 @@ const project = new Hono<{
},
}),
validator("param", v.object({ id: v.string() })),
- validator("query", v.object({ workspaceId: v.string() })),
+ validator("query", v.optional(v.object({ workspaceId: v.string() }))),
+ workspaceAccess.fromProject(),
async (c) => {
const { id } = c.req.valid("param");
- const { workspaceId } = c.req.valid("query");
+ const workspaceId = c.get("workspaceId");
const projectData = await getProjectCtrl(id, workspaceId);
return c.json(projectData);
},
@@ -120,9 +121,11 @@ const project = new Hono<{
isPublic: v.boolean(),
}),
),
+ workspaceAccess.fromProject(),
async (c) => {
const { id } = c.req.valid("param");
const { name, icon, slug, description, isPublic } = c.req.valid("json");
+ const workspaceId = c.get("workspaceId");
const updatedProject = await updateProjectCtrl(
id,
name,
@@ -130,6 +133,7 @@ const project = new Hono<{
slug,
description,
isPublic,
+ workspaceId,
);
return c.json(updatedProject);
},
@@ -150,9 +154,12 @@ const project = new Hono<{
},
}),
validator("param", v.object({ id: v.string() })),
+ validator("query", v.optional(v.object({ workspaceId: v.string() }))),
+ workspaceAccess.fromProject(),
async (c) => {
const { id } = c.req.valid("param");
- const deletedProject = await deleteProjectCtrl(id);
+ const workspaceId = c.get("workspaceId");
+ const deletedProject = await deleteProjectCtrl(id, workspaceId);
return c.json(deletedProject);
},
);
diff --git a/apps/api/src/utils/workspace-access-middleware.ts b/apps/api/src/utils/workspace-access-middleware.ts
new file mode 100644
index 000000000..d40c193c0
--- /dev/null
+++ b/apps/api/src/utils/workspace-access-middleware.ts
@@ -0,0 +1,190 @@
+import { eq } from "drizzle-orm";
+import type { Context, Next } from "hono";
+import { HTTPException } from "hono/http-exception";
+import db, { schema } from "../database";
+import { validateWorkspaceAccess } from "./validate-workspace-access";
+
+type WorkspaceIdSource =
+ | { type: "query"; key: string }
+ | { type: "body"; key: string }
+ | { type: "param"; key: string }
+ | {
+ type: "lookup";
+ resource: "project" | "task" | "label" | "timeEntry" | "activity";
+ idKey: string;
+ };
+
+interface WorkspaceAccessMiddlewareConfig {
+ sources: WorkspaceIdSource[];
+}
+
+export function workspaceAccessMiddleware(
+ config: WorkspaceAccessMiddlewareConfig,
+) {
+ return async (c: Context, next: Next) => {
+ const userId = c.get("userId");
+
+ if (!userId) {
+ throw new HTTPException(401, { message: "Unauthorized" });
+ }
+
+ let workspaceId: string | null = null;
+
+ for (const source of config.sources) {
+ if (source.type === "query") {
+ workspaceId = c.req.query(source.key) || null;
+ } else if (source.type === "body") {
+ const body = await c.req.json().catch(() => ({}));
+ workspaceId = body[source.key] || null;
+ } else if (source.type === "param") {
+ workspaceId = c.req.param(source.key) || null;
+ } else if (source.type === "lookup") {
+ const id = c.req.param(source.idKey) || c.req.query(source.idKey);
+ if (id) {
+ workspaceId = await lookupWorkspaceId(source.resource, id);
+ }
+ }
+
+ if (workspaceId) {
+ break;
+ }
+ }
+
+ if (!workspaceId) {
+ throw new HTTPException(400, {
+ message: "Workspace ID could not be determined",
+ });
+ }
+
+ await validateWorkspaceAccess(userId, workspaceId);
+
+ c.set("workspaceId", workspaceId);
+
+ return next();
+ };
+}
+
+async function lookupWorkspaceId(
+ resource: "project" | "task" | "label" | "timeEntry" | "activity",
+ id: string,
+): Promise<string | null> {
+ try {
+ switch (resource) {
+ case "project": {
+ const [project] = await db
+ .select({ workspaceId: schema.projectTable.workspaceId })
+ .from(schema.projectTable)
+ .where(eq(schema.projectTable.id, id))
+ .limit(1);
+ return project?.workspaceId || null;
+ }
+
+ case "task": {
+ const [task] = await db
+ .select({
+ workspaceId: schema.projectTable.workspaceId,
+ })
+ .from(schema.taskTable)
+ .innerJoin(
+ schema.projectTable,
+ eq(schema.taskTable.projectId, schema.projectTable.id),
+ )
+ .where(eq(schema.taskTable.id, id))
+ .limit(1);
+ return task?.workspaceId || null;
+ }
+
+ case "label": {
+ const [label] = await db
+ .select({ workspaceId: schema.labelTable.workspaceId })
+ .from(schema.labelTable)
+ .where(eq(schema.labelTable.id, id))
+ .limit(1);
+ return label?.workspaceId || null;
+ }
+
+ case "timeEntry": {
+ const [timeEntry] = await db
+ .select({
+ workspaceId: schema.projectTable.workspaceId,
+ })
+ .from(schema.timeEntryTable)
+ .innerJoin(
+ schema.taskTable,
+ eq(schema.timeEntryTable.taskId, schema.taskTable.id),
+ )
+ .innerJoin(
+ schema.projectTable,
+ eq(schema.taskTable.projectId, schema.projectTable.id),
+ )
+ .where(eq(schema.timeEntryTable.id, id))
+ .limit(1);
+ return timeEntry?.workspaceId || null;
+ }
+
+ case "activity": {
+ const [activity] = await db
+ .select({
+ workspaceId: schema.projectTable.workspaceId,
+ })
+ .from(schema.activityTable)
+ .innerJoin(
+ schema.taskTable,
+ eq(schema.activityTable.taskId, schema.taskTable.id),
+ )
+ .innerJoin(
+ schema.projectTable,
+ eq(schema.taskTable.projectId, schema.projectTable.id),
+ )
+ .where(eq(schema.activityTable.id, id))
+ .limit(1);
+ return activity?.workspaceId || null;
+ }
+
+ default:
+ return null;
+ }
+ } catch (error) {
+ console.error(`Error looking up workspaceId for ${resource}:`, error);
+ return null;
+ }
+}
+
+export const workspaceAccess = {
+ fromQuery: (key = "workspaceId") =>
+ workspaceAccessMiddleware({ sources: [{ type: "query", key }] }),
+
+ fromBody: (key = "workspaceId") =>
+ workspaceAccessMiddleware({ sources: [{ type: "body", key }] }),
+
+ fromParam: (key = "workspaceId") =>
+ workspaceAccessMiddleware({ sources: [{ type: "param", key }] }),
+
+ fromProject: (idKey = "id") =>
+ workspaceAccessMiddleware({
+ sources: [
+ { type: "query", key: "workspaceId" },
+ { type: "lookup", resource: "project", idKey },
+ ],
+ }),
+
+ fromTask: (idKey = "id") =>
+ workspaceAccessMiddleware({
+ sources: [{ type: "lookup", resource: "task", idKey }],
+ }),
+
+ fromLabel: (idKey = "id") =>
+ workspaceAccessMiddleware({
+ sources: [{ type: "lookup", resource: "label", idKey }],
+ }),
+
+ fromTimeEntry: (idKey = "id") =>
+ workspaceAccessMiddleware({
+ sources: [{ type: "lookup", resource: "timeEntry", idKey }],
+ }),
+
+ fromActivity: (idKey = "id") =>
+ workspaceAccessMiddleware({
+ sources: [{ type: "lookup", resource: "activity", idKey }],
+ }),
+};