fix: modify document update permissions to account for document memberships

This commit is contained in:
Apoorv Mishra committed 2023-12-27 22:47:15 +05:30
1 parent faca39becb
commit 19278bc612
4 files changed
+47 -14

No files matched your search

+4 -1
View File
@@ -157,7 +157,10 @@ export default async function documentCreator({
// reload to get all of the data needed to present (user, collection etc)
// we need to specify publishedAt to bypass default scope that only returns
// published documents
return await Document.findOne({
return await Document.scope([
"withDrafts",
{ method: ["withMembership", user.id] },
]).findOne({
where: {
id: document.id,
publishedAt: document.publishedAt,
+19 -11
View File
@@ -194,18 +194,23 @@ type AdditionalFindOptions = {
],
};
},
withMembership: (userId: string) => ({
include: [
{
model: DocumentUser,
as: "memberships",
where: {
userId,
withMembership: (userId: string) => {
if (!userId) {
return {};
}
return {
include: [
{
model: DocumentUser,
as: "memberships",
where: {
userId,
},
required: false,
},
required: false,
},
],
}),
],
};
},
}))
@Table({ tableName: "documents", modelName: "document" })
@Fix
@@ -585,6 +590,9 @@ class Document extends ParanoidModel {
{
method: ["withViews", userId],
},
{
method: ["withMembership", userId],
},
]);
if (isUUID(id)) {
+20 -1
View File
@@ -1,5 +1,6 @@
import invariant from "invariant";
import { TeamPreference } from "@shared/types";
import some from "lodash/some";
import { DocumentPermission, TeamPreference } from "@shared/types";
import { Document, Revision, User, Team } from "@server/models";
import { allow, _cannot as cannot } from "./cancan";
@@ -118,6 +119,13 @@ allow(User, "update", Document, (user, document) => {
return false;
}
const membershipAllowsUpdate = includesMembership(document, [
DocumentPermission.ReadWrite,
]);
if (membershipAllowsUpdate) {
return true;
}
if (document.collectionId) {
invariant(
document.collection,
@@ -360,3 +368,14 @@ allow(User, "unpublish", Document, (user, document) => {
}
return user.teamId === document.teamId;
});
function includesMembership(
document: Document,
permissions: DocumentPermission[]
) {
invariant(
document.memberships,
"memberships should be preloaded, did you forget withMembership scope?"
);
return some(document.memberships, (m) => permissions.includes(m.permission));
}
+4 -1
View File
@@ -304,7 +304,10 @@ router.post(
order: [[sort, direction]],
include: [
{
model: Document,
model: Document.scope([
"withDrafts",
{ method: ["withMembership", userId] },
]),
required: true,
where: {
collectionId: collectionIds,