mirror of
https://github.com/outline/outline.git
synced 2026-12-06 11:12:32 +03:00
feat: Record who deleted a document (#13484)
* feat: Record who deleted a document The trash inferred the deleting user from lastModifiedById, so a nested page kept whoever last edited it and deleting a document rewrote its edit history. Add a dedicated deletedById column and set it from the base model. - Migration adds the column, backfills from lastModifiedById, and validates the foreign key without holding an exclusive lock. The backfill runs in batches against a temporary index covering only the rows still to write, so it stays linear on a large table, and every statement is idempotent because the migration cannot run in a transaction. - ParanoidModel records the acting user on destroy and clears it on restore, for any model that has the column. Sequelize soft deletes with the same UPDATE that stamps deletedAt, so the value costs no extra query. - Deleting a document no longer touches lastModifiedById on its descendants. - Present the deleting user, batched in presentDocuments, and use it for the trash notice and the document meta line rather than the last editor. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: Do not overwrite an eager loaded deleting user when batching The batch lookup in presentDocuments skipped documents that already carried the association, but the assignment loop ran for all of them, so a document that arrived with deletedBy loaded was reset to null and fell back to a per-document query. Assign only where the association is missing, and deduplicate the ids so a page deleted by one person asks for one row rather than one per document. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
1ca8335717
commit
def3a42752
15 files changed
+418
-45
No files matched your search
@@ -93,9 +93,11 @@ const DocumentMeta: React.FC<Props> = ({
|
||||
} else if (deletedAt) {
|
||||
content = (
|
||||
<span>
|
||||
{lastUpdatedByCurrentUser
|
||||
{document.deletedBy?.id === user.id
|
||||
? t("You deleted")
|
||||
: t("{{ userName }} deleted", { userName })}{" "}
|
||||
: t("{{ userName }} deleted", {
|
||||
userName: document.deletedBy?.name ?? t("Unknown"),
|
||||
})}{" "}
|
||||
<Time dateTime={deletedAt} addSuffix />
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -204,6 +204,14 @@ export default class Document extends ArchivableModel implements Searchable {
|
||||
@observable
|
||||
updatedBy: User | undefined;
|
||||
|
||||
/**
|
||||
* The user that deleted this document, only set while the document is in the
|
||||
* trash.
|
||||
*/
|
||||
@Relation(() => User)
|
||||
@observable
|
||||
deletedBy: User | undefined;
|
||||
|
||||
@observable
|
||||
publishedAt: string | undefined;
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ export default function Notices({ document }: Props) {
|
||||
description={permanentlyDeletedDescription()}
|
||||
>
|
||||
{t("Deleted by {{userName}}", {
|
||||
userName: document.updatedBy?.name ?? t("Unknown"),
|
||||
userName: document.deletedBy?.name ?? t("Unknown"),
|
||||
})}
|
||||
|
||||
<Time dateTime={document.deletedAt} addSuffix />
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/* oxlint-disable */
|
||||
import stores from "~/stores";
|
||||
|
||||
describe("DocumentsStore", () => {
|
||||
describe("deleted", () => {
|
||||
test("should filter by the user that deleted the document", () => {
|
||||
const deleter = stores.users.add({
|
||||
id: "22222222-2222-2222-2222-222222222222",
|
||||
name: "Deleter",
|
||||
});
|
||||
const other = stores.users.add({
|
||||
id: "33333333-3333-3333-3333-333333333333",
|
||||
name: "Other",
|
||||
});
|
||||
|
||||
const mine = stores.documents.add({
|
||||
id: "11111111-1111-1111-1111-111111111111",
|
||||
title: "Deleted by me",
|
||||
deletedAt: "2026-08-18T00:00:00.000Z",
|
||||
deletedBy: deleter,
|
||||
});
|
||||
stores.documents.add({
|
||||
id: "44444444-4444-4444-4444-444444444444",
|
||||
title: "Deleted by someone else",
|
||||
deletedAt: "2026-08-18T00:00:00.000Z",
|
||||
deletedBy: other,
|
||||
});
|
||||
|
||||
const results = stores.documents.deleted({ userId: deleter.id });
|
||||
expect(results.map((doc) => doc.id)).toEqual([mine.id]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -248,11 +248,10 @@ export default class DocumentsStore extends Store<Document> {
|
||||
(d) => d.deletedAt
|
||||
);
|
||||
|
||||
// The deleting user is recorded as the last to modify the document.
|
||||
if (options.userId) {
|
||||
deleted = filter(
|
||||
deleted,
|
||||
(document) => document.updatedBy?.id === options.userId
|
||||
(document) => document.deletedBy?.id === options.userId
|
||||
);
|
||||
}
|
||||
|
||||
@@ -659,11 +658,11 @@ export default class DocumentsStore extends Store<Document> {
|
||||
// acting user against the document and its descendants. The trash relies
|
||||
// on this to filter by who deleted an item before the next fetch.
|
||||
const user = this.rootStore.auth.user ?? undefined;
|
||||
const setUpdatedBy = (doc: Document) => {
|
||||
doc.updatedBy = user;
|
||||
doc.childDocuments.forEach(setUpdatedBy);
|
||||
const setDeletedBy = (doc: Document) => {
|
||||
doc.deletedBy = user;
|
||||
doc.childDocuments.forEach(setDeletedBy);
|
||||
};
|
||||
setUpdatedBy(document);
|
||||
setDeletedBy(document);
|
||||
}
|
||||
|
||||
// check to see if we have any shares related to this document already
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"use strict";
|
||||
|
||||
const BATCH_SIZE = 1000;
|
||||
|
||||
/** @type {import('sequelize-cli').Migration} */
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
// Every statement is idempotent because the migration cannot run inside a
|
||||
// transaction, so a failure part way through has to be resumable.
|
||||
await queryInterface.sequelize.query(
|
||||
'ALTER TABLE "documents" ADD COLUMN IF NOT EXISTS "deletedById" uuid;'
|
||||
);
|
||||
|
||||
// NOT VALID adds the constraint without scanning the existing rows, which
|
||||
// would hold an exclusive lock for the length of that scan. VALIDATE then
|
||||
// checks them under a lock that still allows reads and writes.
|
||||
const [constraints] = await queryInterface.sequelize.query(
|
||||
`SELECT 1 FROM pg_constraint WHERE conname = 'documents_deletedById_fkey';`
|
||||
);
|
||||
if (!constraints.length) {
|
||||
await queryInterface.sequelize.query(`
|
||||
ALTER TABLE "documents"
|
||||
ADD CONSTRAINT "documents_deletedById_fkey"
|
||||
FOREIGN KEY ("deletedById") REFERENCES "users" ("id")
|
||||
NOT VALID;
|
||||
`);
|
||||
}
|
||||
await queryInterface.sequelize.query(
|
||||
'ALTER TABLE "documents" VALIDATE CONSTRAINT "documents_deletedById_fkey";'
|
||||
);
|
||||
|
||||
// Serves the trash query. Partial so that it only covers deleted documents
|
||||
// rather than the whole table.
|
||||
await queryInterface.sequelize.query(
|
||||
'CREATE INDEX CONCURRENTLY IF NOT EXISTS "documents_deleted_by_id" ON "documents" ("deletedById") WHERE "deletedAt" IS NOT NULL;'
|
||||
);
|
||||
|
||||
// Indexes only the rows the backfill has left to do, so it shrinks as the
|
||||
// loop runs and each batch reads its own rows and nothing else. Without it
|
||||
// every batch re-reads the rows already written, which turns the loop
|
||||
// quadratic on a large table.
|
||||
await queryInterface.sequelize.query(
|
||||
'CREATE INDEX CONCURRENTLY IF NOT EXISTS "documents_deleted_by_backfill" ON "documents" ("id") WHERE "deletedAt" IS NOT NULL AND "deletedById" IS NULL;'
|
||||
);
|
||||
|
||||
// Written in batches, each its own transaction, so that no single statement
|
||||
// locks a large number of rows.
|
||||
let rowCount = 1;
|
||||
let total = 0;
|
||||
|
||||
while (rowCount) {
|
||||
const [, metadata] = await queryInterface.sequelize.query(`
|
||||
WITH rows AS (
|
||||
SELECT "id" FROM "documents"
|
||||
WHERE "deletedAt" IS NOT NULL AND "deletedById" IS NULL
|
||||
ORDER BY "id"
|
||||
LIMIT ${BATCH_SIZE}
|
||||
)
|
||||
UPDATE "documents"
|
||||
SET "deletedById" = "lastModifiedById"
|
||||
WHERE EXISTS (SELECT 1 FROM rows WHERE "documents"."id" = rows."id")
|
||||
`);
|
||||
|
||||
rowCount = metadata.rowCount;
|
||||
total += rowCount;
|
||||
if (rowCount) {
|
||||
console.log(`Backfilling documents.deletedById… ${total}`);
|
||||
}
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
'DROP INDEX CONCURRENTLY IF EXISTS "documents_deleted_by_backfill";'
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
// Dropping the column takes the index and the foreign key with it.
|
||||
await queryInterface.sequelize.query(
|
||||
'ALTER TABLE "documents" DROP COLUMN IF EXISTS "deletedById";'
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { randomString } from "@shared/random";
|
||||
import slugify from "@shared/utils/slugify";
|
||||
import { createContext } from "@server/context";
|
||||
import {
|
||||
buildUser,
|
||||
buildGroup,
|
||||
@@ -329,7 +330,7 @@ describe("#removeDocument", () => {
|
||||
await collection.reload();
|
||||
|
||||
const saveSpy = vi.spyOn(collection, "save");
|
||||
await collection.deleteDocument(document, user);
|
||||
await collection.deleteDocument(createContext({ user }), document);
|
||||
expect(saveSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -339,7 +340,7 @@ describe("#removeDocument", () => {
|
||||
const document = await buildDocument({ collectionId: collection.id });
|
||||
await collection.reload();
|
||||
|
||||
await collection.deleteDocument(document, user);
|
||||
await collection.deleteDocument(createContext({ user }), document);
|
||||
expect(collection.documentStructure!.length).toBe(0);
|
||||
// Verify that the document was removed
|
||||
const collectionDocuments = await Document.findAndCountAll({
|
||||
@@ -369,7 +370,7 @@ describe("#removeDocument", () => {
|
||||
await collection.addDocumentToStructure(newDocument);
|
||||
expect(collection.documentStructure![0].children.length).toBe(1);
|
||||
// Remove the document
|
||||
await collection.deleteDocument(document, user);
|
||||
await collection.deleteDocument(createContext({ user }), document);
|
||||
expect(collection.documentStructure!.length).toBe(0);
|
||||
const collectionDocuments = await Document.findAndCountAll({
|
||||
where: {
|
||||
@@ -400,7 +401,7 @@ describe("#removeDocument", () => {
|
||||
parentDocumentId = child.id;
|
||||
}
|
||||
|
||||
await collection.deleteDocument(document, user);
|
||||
await collection.deleteDocument(createContext({ user }), document);
|
||||
expect(collection.documentStructure!.length).toBe(0);
|
||||
const collectionDocuments = await Document.findAndCountAll({
|
||||
where: {
|
||||
@@ -431,7 +432,7 @@ describe("#removeDocument", () => {
|
||||
expect(collection.documentStructure!.length).toBe(1);
|
||||
expect(collection.documentStructure![0].children.length).toBe(1);
|
||||
// Remove the document
|
||||
await collection.deleteDocument(newDocument, user);
|
||||
await collection.deleteDocument(createContext({ user }), newDocument);
|
||||
const reloaded = await collection.reload();
|
||||
expect(reloaded!.documentStructure!.length).toBe(1);
|
||||
expect(reloaded!.documentStructure![0].children.length).toBe(0);
|
||||
|
||||
+12
-19
@@ -422,9 +422,12 @@ class Collection extends ParanoidModel<
|
||||
|
||||
@BeforeDestroy
|
||||
static async deleteDocuments(model: Collection, ctx: APIContext["context"]) {
|
||||
// A bulk update rather than a destroy per document, so `deletedById` is
|
||||
// written here instead of by the hook on ParanoidModel.
|
||||
await Document.update(
|
||||
{
|
||||
lastModifiedById: ctx.auth.user.id,
|
||||
deletedById: ctx.auth.user.id,
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
{
|
||||
@@ -861,26 +864,23 @@ class Collection extends ParanoidModel<
|
||||
* Removes a document from this collection's structure and soft deletes it
|
||||
* along with all of its descendants.
|
||||
*
|
||||
* @param ctx the API context, which attributes the deletion to the acting user.
|
||||
* @param document the document to delete.
|
||||
* @param user the user performing the deletion, recorded on every document.
|
||||
* @param options the find options, including an optional transaction.
|
||||
*/
|
||||
deleteDocument = async (
|
||||
document: Document,
|
||||
user: User,
|
||||
options?: FindOptions
|
||||
) => {
|
||||
await this.removeDocumentInStructure(document, options);
|
||||
deleteDocument = async (ctx: APIContext, document: Document) => {
|
||||
const { transaction } = ctx.context;
|
||||
|
||||
await this.removeDocumentInStructure(document, { transaction });
|
||||
|
||||
// IDs come back breadth-first so reversing them destroys the deepest
|
||||
// descendants first.
|
||||
const childDocumentIds = (
|
||||
await document.findAllChildDocumentIds(undefined, options)
|
||||
await document.findAllChildDocumentIds(undefined, { transaction })
|
||||
).reverse();
|
||||
|
||||
if (childDocumentIds.length) {
|
||||
const childDocuments = await Document.findAll({
|
||||
...options,
|
||||
transaction,
|
||||
where: {
|
||||
id: childDocumentIds,
|
||||
},
|
||||
@@ -889,18 +889,11 @@ class Collection extends ParanoidModel<
|
||||
|
||||
// Destroyed one at a time to ensure model hooks run for each document.
|
||||
for (const childDocumentId of childDocumentIds) {
|
||||
const childDocument = childDocumentsById[childDocumentId];
|
||||
if (childDocument) {
|
||||
// Attributes the deletion of the whole tree to the acting user, which
|
||||
// the trash relies on to show a person their own deletions.
|
||||
childDocument.lastModifiedById = user.id;
|
||||
childDocument.updatedBy = user;
|
||||
await childDocument.destroy(options);
|
||||
}
|
||||
await childDocumentsById[childDocumentId]?.destroy(ctx.context);
|
||||
}
|
||||
}
|
||||
|
||||
await document.destroy(options);
|
||||
await document.destroy(ctx.context);
|
||||
};
|
||||
|
||||
removeDocumentInStructure = async (
|
||||
|
||||
@@ -684,6 +684,14 @@ class Document extends ArchivableModel<
|
||||
@Column(DataType.UUID)
|
||||
createdById: string;
|
||||
|
||||
@BelongsTo(() => User, "deletedById")
|
||||
deletedBy: User | null;
|
||||
|
||||
/** The user that deleted this document, set automatically on delete. */
|
||||
@ForeignKey(() => User)
|
||||
@Column(DataType.UUID)
|
||||
deletedById: string | null;
|
||||
|
||||
@ForeignKey(() => Template)
|
||||
@Column(DataType.UUID)
|
||||
templateId: string;
|
||||
@@ -1451,13 +1459,13 @@ class Document extends ArchivableModel<
|
||||
});
|
||||
|
||||
if (!this.archivedAt || (this.archivedAt && collection?.archivedAt)) {
|
||||
await collection?.deleteDocument(this, user, { transaction });
|
||||
await collection?.deleteDocument(ctx, this);
|
||||
deleted = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!deleted) {
|
||||
await this.destroy({ transaction });
|
||||
await this.destroy(ctx.context);
|
||||
}
|
||||
|
||||
this.lastModifiedById = user.id;
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { createContext } from "@server/context";
|
||||
import {
|
||||
buildCollection,
|
||||
buildDocument,
|
||||
buildTeam,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
|
||||
describe("ParanoidModel", () => {
|
||||
describe("deletedById", () => {
|
||||
it("should record the acting user on destroy", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({ teamId: user.teamId });
|
||||
|
||||
await document.destroy(createContext({ user }).context);
|
||||
await document.reload({ paranoid: false });
|
||||
|
||||
expect(document.deletedAt).toBeTruthy();
|
||||
expect(document.deletedById).toEqual(user.id);
|
||||
});
|
||||
|
||||
it("should clear the recorded user on restore", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({ teamId: user.teamId });
|
||||
|
||||
await document.destroy(createContext({ user }).context);
|
||||
await document.restore();
|
||||
await document.reload();
|
||||
|
||||
expect(document.deletedAt).toBeNull();
|
||||
expect(document.deletedById).toBeNull();
|
||||
});
|
||||
|
||||
it("should record nothing when the context is unauthenticated", async () => {
|
||||
const document = await buildDocument();
|
||||
|
||||
await document.destroy();
|
||||
await document.reload({ paranoid: false });
|
||||
|
||||
expect(document.deletedAt).toBeTruthy();
|
||||
expect(document.deletedById).toBeNull();
|
||||
});
|
||||
|
||||
it("should ignore models without the column", async () => {
|
||||
const team = await buildTeam();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
// A team must keep at least one collection, so build a second to delete.
|
||||
await buildCollection({ teamId: team.id, userId: user.id });
|
||||
const collection = await buildCollection({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
await collection.destroy(createContext({ user }).context);
|
||||
|
||||
expect(collection.deletedAt).toBeTruthy();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,9 @@
|
||||
import { DeletedAt } from "sequelize-typescript";
|
||||
import { BeforeDestroy, BeforeRestore, DeletedAt } from "sequelize-typescript";
|
||||
import IdModel from "./IdModel";
|
||||
import type { HookContext } from "./Model";
|
||||
|
||||
/** The optional column recording the user that deleted a row. */
|
||||
const DeletedByField = "deletedById";
|
||||
|
||||
class ParanoidModel<
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mirrors Model base; tightening to object resolves Attributes<M> to never inside Sequelize helpers.
|
||||
@@ -17,6 +21,36 @@ class ParanoidModel<
|
||||
get isDeleted() {
|
||||
return !!this.deletedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the acting user against a model that has a `deletedById` column.
|
||||
* Sequelize soft deletes with the same UPDATE that writes `deletedAt`, so the
|
||||
* value set here is persisted without an additional query.
|
||||
*
|
||||
* @param model The model being deleted.
|
||||
* @param context The hook context, which provides the acting user.
|
||||
*/
|
||||
@BeforeDestroy
|
||||
static async setDeletedBy(model: ParanoidModel, context: HookContext) {
|
||||
const userId = context.auth?.user?.id;
|
||||
|
||||
if (userId && DeletedByField in this.rawAttributes) {
|
||||
model.setDataValue(DeletedByField, userId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the recorded deleting user when a model is restored, so that a row
|
||||
* which is no longer deleted carries no attribution.
|
||||
*
|
||||
* @param model The model being restored.
|
||||
*/
|
||||
@BeforeRestore
|
||||
static async unsetDeletedBy(model: ParanoidModel) {
|
||||
if (DeletedByField in this.rawAttributes) {
|
||||
model.setDataValue(DeletedByField, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default ParanoidModel;
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Document } from "@server/models";
|
||||
import { presentDocuments } from "@server/presenters/document";
|
||||
import {
|
||||
buildCollection,
|
||||
buildDocument,
|
||||
buildUser,
|
||||
} from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
|
||||
describe("presentDocuments", () => {
|
||||
describe("deletedBy", () => {
|
||||
it("should resolve the deleting user in a single query", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({ teamId: user.teamId });
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const document = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
}
|
||||
|
||||
const documents = await Document.scope("withDrafts").findAll({
|
||||
where: { collectionId: collection.id },
|
||||
paranoid: false,
|
||||
});
|
||||
expect(documents.length).toEqual(3);
|
||||
|
||||
const queries: string[] = [];
|
||||
const query = sequelize.query.bind(sequelize);
|
||||
const spy = vi
|
||||
.spyOn(sequelize, "query")
|
||||
.mockImplementation((sql, options) => {
|
||||
queries.push(typeof sql === "string" ? sql : sql.query);
|
||||
return query(sql, options);
|
||||
});
|
||||
|
||||
try {
|
||||
await presentDocuments(undefined, documents);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
|
||||
expect(documents.every((doc) => doc.deletedBy?.id === user.id)).toBe(
|
||||
true
|
||||
);
|
||||
|
||||
expect(queries.filter((sql) => /FROM "users"/.test(sql)).length).toEqual(
|
||||
1
|
||||
);
|
||||
});
|
||||
|
||||
it("should not overwrite an already loaded deleting user", async () => {
|
||||
const userA = await buildUser();
|
||||
const userB = await buildUser({ teamId: userA.teamId });
|
||||
const collection = await buildCollection({ teamId: userA.teamId });
|
||||
|
||||
const documentA = await buildDocument({
|
||||
teamId: userA.teamId,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
const documentB = await buildDocument({
|
||||
teamId: userA.teamId,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
await withAPIContext(userA, (ctx) => documentA.destroyWithCtx(ctx));
|
||||
await withAPIContext(userB, (ctx) => documentB.destroyWithCtx(ctx));
|
||||
|
||||
// One document arrives with the association loaded, the other without.
|
||||
const loaded = await Document.scope("withDrafts").findOne({
|
||||
where: { id: documentA.id },
|
||||
include: [{ association: "deletedBy", paranoid: false }],
|
||||
paranoid: false,
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
const unloaded = await Document.scope("withDrafts").findOne({
|
||||
where: { id: documentB.id },
|
||||
paranoid: false,
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
|
||||
await presentDocuments(undefined, [loaded, unloaded]);
|
||||
|
||||
expect(loaded.deletedBy?.id).toEqual(userA.id);
|
||||
expect(unloaded.deletedBy?.id).toEqual(userB.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { Hour } from "@shared/utils/time";
|
||||
import { traceFunction } from "@server/logging/tracing";
|
||||
import type { Document } from "@server/models";
|
||||
import FileOperation from "@server/models/FileOperation";
|
||||
import User from "@server/models/User";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import type { APIContext } from "@server/types";
|
||||
import presentUser from "./user";
|
||||
@@ -80,6 +81,7 @@ async function presentDocument(
|
||||
publishedAt: document.publishedAt,
|
||||
archivedAt: document.archivedAt,
|
||||
deletedAt: document.deletedAt,
|
||||
deletedBy: undefined,
|
||||
collaboratorIds: [],
|
||||
revision: document.revisionCount,
|
||||
fullWidth: document.fullWidth,
|
||||
@@ -114,6 +116,14 @@ async function presentDocument(
|
||||
res.templateId = document.templateId;
|
||||
res.insightsEnabled = document.insightsEnabled;
|
||||
res.popularityScore = document.popularityScore;
|
||||
if (document.deletedById) {
|
||||
const deletedBy =
|
||||
document.deletedBy ??
|
||||
(await document.$get("deletedBy", { paranoid: false }));
|
||||
if (deletedBy) {
|
||||
res.deletedBy = presentUser(deletedBy);
|
||||
}
|
||||
}
|
||||
if (options.includeCommentCount) {
|
||||
res.commentCount = await document.commentCount;
|
||||
}
|
||||
@@ -137,8 +147,8 @@ export default traceFunction({
|
||||
})(presentDocument);
|
||||
|
||||
/**
|
||||
* Batch-present multiple documents, fetching all related FileOperation records
|
||||
* in a single query instead of one per document.
|
||||
* Batch-present multiple documents, fetching all related FileOperation and
|
||||
* deleting User records in a single query instead of one per document.
|
||||
*
|
||||
* @param ctx the API context.
|
||||
* @param documents the documents to present.
|
||||
@@ -169,6 +179,29 @@ export async function presentDocuments(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Deduplicated because a page of trashed documents is often the work of a
|
||||
// single person, and only for documents that arrived without the
|
||||
// association so that an eager loaded one is not overwritten.
|
||||
const deletedByIds = new Set(
|
||||
documents
|
||||
.filter((doc) => doc.deletedById && !doc.deletedBy)
|
||||
.map((doc) => doc.deletedById!)
|
||||
);
|
||||
|
||||
if (deletedByIds.size > 0) {
|
||||
const users = await User.unscoped().findAll({
|
||||
where: { id: { [Op.in]: Array.from(deletedByIds) } },
|
||||
paranoid: false,
|
||||
});
|
||||
const userMap = new Map(users.map((user) => [user.id, user]));
|
||||
|
||||
for (const doc of documents) {
|
||||
if (doc.deletedById && !doc.deletedBy) {
|
||||
doc.deletedBy = userMap.get(doc.deletedById) ?? null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.all(
|
||||
|
||||
@@ -4828,7 +4828,8 @@ describe("#documents.deleted", () => {
|
||||
await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
|
||||
await childDocument.reload({ paranoid: false });
|
||||
expect(childDocument.lastModifiedById).toEqual(user.id);
|
||||
expect(childDocument.deletedById).toEqual(user.id);
|
||||
expect(childDocument.lastModifiedById).toEqual(other.id);
|
||||
|
||||
const res = await server.post("/api/documents.deleted", user, {
|
||||
body: {
|
||||
@@ -4838,6 +4839,41 @@ describe("#documents.deleted", () => {
|
||||
const body = await res.json();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body.data.length).toEqual(2);
|
||||
expect(body.data[0].deletedBy.id).toEqual(user.id);
|
||||
expect(body.data[0].deletedBy.name).toEqual(user.name);
|
||||
});
|
||||
|
||||
it("should present the deleting user on a single document", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({ teamId: user.teamId });
|
||||
const document = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
await withAPIContext(user, (ctx) => document.destroyWithCtx(ctx));
|
||||
|
||||
const res = await server.post("/api/documents.info", user, {
|
||||
body: { id: document.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body.data.deletedBy.id).toEqual(user.id);
|
||||
expect(body.data.deletedBy.name).toEqual(user.name);
|
||||
});
|
||||
|
||||
it("should not present a deleting user on an active document", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const res = await server.post("/api/documents.info", user, {
|
||||
body: { id: document.id },
|
||||
});
|
||||
const body = await res.json();
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body.data.deletedBy).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should reject filters on fields outside the allowlist", async () => {
|
||||
|
||||
@@ -570,15 +570,10 @@ router.post(
|
||||
],
|
||||
};
|
||||
|
||||
// The deleting user is currently recorded as the last to modify the
|
||||
// document, so the public `deletedById` field maps onto that column.
|
||||
const filter = combineFilters(rawFilters);
|
||||
if (filter) {
|
||||
await authorizeFilterFields(user, filter);
|
||||
const mapped = mapFilterFields(filter, {
|
||||
deletedById: "lastModifiedById",
|
||||
});
|
||||
where[Op.and].push(buildWhere<Document>(mapped));
|
||||
where[Op.and].push(buildWhere<Document>(filter));
|
||||
}
|
||||
|
||||
const documents = await Document.scope([
|
||||
|
||||
Reference in new issue
Block a user