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.

fix(import): resolve assignees by member email

Tin63bb78016ab6
diff --git a/apps/api/src/task/controllers/import-tasks.ts b/apps/api/src/task/controllers/import-tasks.ts
index 507b1a795..d240b1762 100644
--- a/apps/api/src/task/controllers/import-tasks.ts
+++ b/apps/api/src/task/controllers/import-tasks.ts
@@ -5,7 +5,6 @@ import { columnTable, projectTable, taskTable } from "../../database/schema";
import { publishEvent } from "../../events";
import { filterUsersWithProjectAccess } from "../../project-access/filter-users-with-project-access";
import {
- filterAssignableUsers,
NO_PROJECT_ACCESS,
NOT_ASSIGNABLE,
} from "../../utils/assert-assignable-user";
@@ -14,6 +13,7 @@ import {
coerceStatus,
getValidTaskStatuses,
} from "../validate-task-fields";
+import { resolveImportAssignees } from "../resolve-import-assignees";
import { claimTaskNumber } from "./claim-task-numbers";
import { nextTaskPosition } from "./next-task-position";
@@ -50,12 +50,12 @@ async function importTasks(
),
];
- const memberIds = await filterAssignableUsers(
+ const assignees = await resolveImportAssignees(
assigneeIds,
project.workspaceId,
);
const assignableIds = await filterUsersWithProjectAccess(
- memberIds,
+ assignees.values(),
projectId,
);
@@ -64,12 +64,13 @@ async function importTasks(
const results = [];
for (const taskData of tasksToImport) {
- const assigneeId = taskData.userId?.trim() || null;
+ const reference = taskData.userId?.trim() || null;
+ const assigneeId = reference ? assignees.get(reference) : null;
- if (assigneeId && !assignableIds.has(assigneeId)) {
+ if (reference && (!assigneeId || !assignableIds.has(assigneeId))) {
results.push({
success: false,
- error: memberIds.has(assigneeId) ? NO_PROJECT_ACCESS : NOT_ASSIGNABLE,
+ error: assigneeId ? NO_PROJECT_ACCESS : NOT_ASSIGNABLE,
task: taskData,
});
continue;
@@ -105,7 +106,7 @@ async function importTasks(
.insert(taskTable)
.values({
projectId,
- userId: assigneeId,
+ userId: assigneeId ?? null,
title: taskData.title,
status,
columnId: column?.id ?? null,
diff --git a/apps/api/src/task/resolve-import-assignees.ts b/apps/api/src/task/resolve-import-assignees.ts
new file mode 100644
index 000000000..6507b797b
--- /dev/null
+++ b/apps/api/src/task/resolve-import-assignees.ts
@@ -0,0 +1,55 @@
+import { and, eq, inArray, isNotNull, or, sql } from "drizzle-orm";
+import db, { schema } from "../database";
+import { instanceAdminRoleSql } from "../utils/instance-admin-role";
+
+export async function resolveImportAssignees(
+ references: string[],
+ workspaceId: string,
+): Promise<Map<string, string>> {
+ const resolved = new Map<string, string>();
+ if (references.length === 0) return resolved;
+
+ const users = await db
+ .select({ id: schema.userTable.id, email: schema.userTable.email })
+ .from(schema.userTable)
+ .leftJoin(
+ schema.workspaceUserTable,
+ and(
+ eq(schema.workspaceUserTable.userId, schema.userTable.id),
+ eq(schema.workspaceUserTable.workspaceId, workspaceId),
+ ),
+ )
+ .where(
+ and(
+ or(
+ inArray(schema.userTable.id, references),
+ inArray(
+ sql`lower(${schema.userTable.email})`,
+ references.map((reference) => reference.toLowerCase()),
+ ),
+ ),
+ or(
+ isNotNull(schema.workspaceUserTable.userId),
+ instanceAdminRoleSql(schema.userTable.role),
+ ),
+ ),
+ );
+
+ const ids = new Set(users.map((user) => user.id));
+ const byEmail = new Map<string, string[]>();
+ for (const user of users) {
+ const email = user.email.toLowerCase();
+ byEmail.set(email, [...(byEmail.get(email) ?? []), user.id]);
+ }
+ for (const reference of references) {
+ // Existing exports use IDs; retain their meaning even if an ID resembles an email.
+ if (ids.has(reference)) {
+ resolved.set(reference, reference);
+ continue;
+ }
+ const matches = byEmail.get(reference.toLowerCase());
+ const match = matches?.[0];
+ if (matches?.length === 1 && match) resolved.set(reference, match);
+ }
+ return resolved;
+}
diff --git a/apps/api/src/task/schema.ts b/apps/api/src/task/schema.ts
index 7bea11e0e..9f6609094 100644
--- a/apps/api/src/task/schema.ts
+++ b/apps/api/src/task/schema.ts
@@ -118,7 +118,10 @@ export const importTasksBody = z.object({
priority: z.string().optional(),
startDate: z.string().nullable().optional(),
dueDate: z.string().nullable().optional(),
- userId: z.string().nullable().optional(),
+ userId: z.string().nullable().optional().openapi({
+ description:
+ "Assignable user's ID or email address. Emails match case-insensitively. Null, empty, or omitted leaves the task unassigned.",
+ }),
}),
),
});
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index 8907e27be..bfcf9bf9d 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -12106,7 +12106,8 @@
"type": [
"string",
"null"
- ]
+ ],
+ "description": "Assignable user's ID or email address. Emails match case-insensitively. Null, empty, or omitted leaves the task unassigned."
}
},
"required": [
diff --git a/tests/api-integration/task-import-assignees.test.ts b/tests/api-integration/task-import-assignees.test.ts
new file mode 100644
index 000000000..6710113cd
--- /dev/null
+++ b/tests/api-integration/task-import-assignees.test.ts
@@ -0,0 +1,133 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vite-plus/test";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+import { restrictToProjects } from "./helpers/project-access/restrict-to-projects";
+
+beforeEach(resetTestDatabase);
+
+async function fixture() {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const { project } = await createProjectFixture({ workspaceId: workspace.id });
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+ const importUsers = async (references: (string | null | undefined)[]) => {
+ const response = await app.request(`/api/task/import/${project.id}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ tasks: references.map((userId, index) => ({
+ title: `Task ${index}`,
+ status: "to-do",
+ userId,
+ })),
+ }),
+ });
+ expect(response.status).toBe(200);
+ return response.json();
+ };
+ return { user, workspace, project, importUsers };
+}
+
+describe("JSON import assignees", () => {
+ it("resolves member emails to opaque user IDs and preserves ID and unassigned imports", async () => {
+ const { user, project, importUsers } = await fixture();
+ const result = await importUsers([
+ ` ${user.email.toUpperCase()} `,
+ user.id,
+ null,
+ "",
+ undefined,
+ ]);
+ expect(result.results.successful).toBe(5);
+ const tasks = await db
+ .select()
+ .from(schema.taskTable)
+ .where(eq(schema.taskTable.projectId, project.id));
+ expect(tasks.filter((task) => task.userId === user.id)).toHaveLength(2);
+ expect(tasks.filter((task) => task.userId === null)).toHaveLength(3);
+ expect(tasks.some((task) => task.userId === user.email)).toBe(false);
+ });
+
+ it("rejects another workspace's users without revealing whether the email exists", async () => {
+ const { importUsers } = await fixture();
+ const outsider = await createWorkspaceMember();
+ const result = await importUsers([
+ outsider.user.email,
+ outsider.user.id,
+ ]);
+ expect(result.results.successful).toBe(0);
+ expect(result.results.failed).toBe(3);
+ expect(
+ result.results.tasks.map((entry: { error: string }) => entry.error),
+ ).toEqual(Array(3).fill("Assignee is not a member of this workspace"));
+ });
+
+ it("still enforces project access after resolving an email", async () => {
+ const { workspace, importUsers } = await fixture();
+ const restricted = await createWorkspaceMember();
+ await db.insert(schema.workspaceUserTable).values({
+ userId: restricted.user.id,
+ workspaceId: workspace.id,
+ role: "member",
+ joinedAt: new Date(),
+ });
+ const { project: allowed } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ await restrictToProjects(workspace.id, restricted.user.id, [allowed.id]);
+ const result = await importUsers([
+ restricted.user.email,
+ restricted.user.id,
+ ]);
+ expect(result.results.successful).toBe(0);
+ expect(
+ result.results.tasks.map((entry: { error: string }) => entry.error),
+ ).toEqual(Array(2).fill("Assignee does not have access to this project"));
+ });
+
+ it("preserves instance-admin assignment outside workspace membership", async () => {
+ const { importUsers } = await fixture();
+ const { user: admin } = await createWorkspaceMember();
+ await db
+ .update(schema.userTable)
+ .set({ role: "admin" })
+ .where(eq(schema.userTable.id, admin.id));
+ const result = await importUsers([admin.id, admin.email]);
+ expect(result.results.successful).toBe(2);
+ expect(
+ result.results.tasks.map(
+ (entry: { task: { userId: string } }) => entry.task.userId,
+ ),
+ ).toEqual([admin.id, admin.id]);
+ });
+
+ it("does not pick an arbitrary member when emails differ only by case", async () => {
+ const { user, workspace, importUsers } = await fixture();
+ const duplicate = await createWorkspaceMember();
+ await db
+ .update(schema.userTable)
+ .set({ email: user.email.toUpperCase() })
+ .where(eq(schema.userTable.id, duplicate.user.id));
+ await db.insert(schema.workspaceUserTable).values({
+ userId: duplicate.user.id,
+ workspaceId: workspace.id,
+ role: "member",
+ joinedAt: new Date(),
+ });
+ const result = await importUsers([user.email, user.id]);
+ expect(result.results.successful).toBe(1);
+ expect(result.results.failed).toBe(1);
+ expect(result.results.tasks[0].error).toBe(
+ "Assignee is not a member of this workspace",
+ );
+ expect(result.results.tasks[1].task.userId).toBe(user.id);
+ });
+});