-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDocument.ts
More file actions
291 lines (277 loc) Β· 11.6 KB
/
Document.ts
File metadata and controls
291 lines (277 loc) Β· 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import { Access, Document as DbDocument, PrismaClient, User } from '../../prisma/generated/client.js';
import type { JsonObject } from '@prisma/client/runtime/client';
import prisma from '../prisma.js';
import { HTTP403Error, HTTP404Error } from '../utils/errors/Errors.js';
import DocumentRoot, { AccessCheckableDocumentRoot } from './DocumentRoot.js';
import { highestAccess, NoneAccess, RWAccess } from '../helpers/accessPolicy.js';
import { ApiGroupPermission } from './RootGroupPermission.js';
import { ApiUserPermission } from './RootUserPermission.js';
import Logger from '../utils/logger.js';
import { hasElevatedAccess, Role, whereStudentGroupAccess } from './User.js';
type AccessCheckableDocument = DbDocument & { documentRoot: AccessCheckableDocumentRoot };
export type ApiDocument = DbDocument;
interface DocumentWithPermission {
document: ApiDocument;
highestPermission: Access;
}
const extractPermission = (actorId: string, document: AccessCheckableDocument): Access | null => {
const hasBaseAccess =
document.authorId === actorId || !NoneAccess.has(document.documentRoot.sharedAccess);
if (!hasBaseAccess) {
return null;
}
const permissions = new Set([
document.documentRoot.access,
...document.documentRoot.rootGroupPermissions.map((p) => p.access),
...document.documentRoot.rootUserPermissions.map((p) => p.access)
]);
const usersPermission = highestAccess(permissions);
if (document.authorId === actorId) {
return usersPermission;
}
return highestAccess(new Set([document.documentRoot.sharedAccess]), usersPermission);
};
export const prepareDocument = (actorId: string, document: AccessCheckableDocument | null) => {
if (!document) {
return null;
}
const permission = extractPermission(actorId, document);
if (!permission) {
return null;
}
const model: ApiDocument = { ...document };
delete (model as Partial<AccessCheckableDocument>).documentRoot;
if (NoneAccess.has(permission)) {
model.data = null;
}
return { document: model, highestPermission: permission };
};
type Response<T> = {
model: T;
permissions: {
access: Access;
sharedAccess: Access;
group: ApiGroupPermission[];
user: ApiUserPermission[];
};
};
function Document(db: PrismaClient['document']) {
return Object.assign(db, {
async findModel(actor: User, id: string): Promise<DocumentWithPermission | null> {
return db
.findUnique({
where: { id: id },
include: {
documentRoot: {
include: {
rootGroupPermissions: {
where: { studentGroup: { users: { some: { userId: actor.id } } } }
},
rootUserPermissions: { where: { user: actor } }
}
}
}
})
.then((doc) => prepareDocument(actor.id, doc));
},
async createModel(
actor: User,
type: string,
documentRootId: string,
data: any,
parentId?: string,
uniqueMain?: boolean,
_onBehalfOfUserId?: string /** this flag enables creation of documents on behalf of another user */
): Promise<Response<ApiDocument>> {
const documentRoot = await DocumentRoot.findModel(actor, documentRootId);
if (!documentRoot) {
throw new HTTP404Error('Document root not found');
}
const elevatedAccess = hasElevatedAccess(actor.role);
const onBehalfOf = !!_onBehalfOfUserId && elevatedAccess;
const authorId = onBehalfOf ? _onBehalfOfUserId : actor.id;
if (onBehalfOf && _onBehalfOfUserId !== actor.id) {
const onBehalfOfUser = await prisma.user.findUnique({
where:
actor.role === Role.ADMIN
? { id: _onBehalfOfUserId }
: { id: _onBehalfOfUserId, ...whereStudentGroupAccess(actor.id, true) }
});
if (!onBehalfOfUser) {
throw new HTTP404Error('On Behalf Of user not found or no required access');
}
Logger.info(`π On Behalf Of: ${_onBehalfOfUserId}`);
}
if (parentId) {
const parent = await this.findModel(actor, parentId);
if (!parent) {
throw new HTTP404Error('Parent document not found');
}
/**
* TODO: Should we allow creating children on documents where actor only has RO access?
*/
if (
!(
parent.document.authorId === actor.id ||
elevatedAccess ||
RWAccess.has(parent.highestPermission)
)
) {
throw new HTTP403Error('Insufficient access permission');
}
}
if (uniqueMain) {
const mainDoc = await db.findFirst({
where: { documentRootId: documentRootId, authorId: authorId, type: type }
});
if (mainDoc) {
Logger.warn(
`[not unique]: Main document fro documentRoot "${documentRootId}" already exists for user "${authorId}"`
);
// the frontend may depend on the error message (try to not change: status code + [not unique])
throw new HTTP403Error('[not unique] Main document already exists for this user');
}
}
/**
* Since it is easyier to check wheter a user has permissions to create a model
* when the model actually exists, we create the model first and then check the permissions.
*/
const model = await db
.create({
data: {
type: type,
documentRootId: documentRootId,
data: data,
parentId: parentId,
authorId: authorId
},
include: {
documentRoot: {
include: {
rootGroupPermissions: {
where: { studentGroup: { users: { some: { userId: authorId } } } }
},
rootUserPermissions: { where: { user: { id: authorId } } }
}
}
}
})
.then((doc) => prepareDocument(authorId, doc)!);
/**
* Check if the user has the required permissions to create the model.
* If not, delete the model and throw an error.
*/
const canCreate = RWAccess.has(model.highestPermission);
if (!canCreate && !onBehalfOf) {
Logger.info(`β New Model [${model.document.id}]: ${model.highestPermission}`);
db.delete({ where: { id: model.document.id } });
throw new HTTP403Error('Insufficient access permission');
}
return {
model: model.document,
permissions: {
access: documentRoot.access,
sharedAccess: documentRoot.sharedAccess,
group: documentRoot.groupPermissions,
user: documentRoot.userPermissions
}
};
},
async updateModel(
actor: User,
id: string,
docData: JsonObject,
_onBehalfOf = false /** this flag enables the modification of documents on behalf of another user */
) {
const elevatedAccess = hasElevatedAccess(actor.role);
const onBehalfOf = _onBehalfOf && elevatedAccess;
if (onBehalfOf) {
/**
* ensure the document exists
*/
const record = await db.findUnique({
where:
actor.role === Role.ADMIN
? { id }
: { id: id, author: whereStudentGroupAccess(actor.id, true) }
});
if (!record) {
throw new HTTP404Error('Document not found');
}
} else {
const record = await this.findModel(actor, id);
if (!record) {
throw new HTTP404Error('Document not found');
}
/**
* models can be updated when the user has RW access
*/
const canWrite = RWAccess.has(record.highestPermission);
if (!canWrite && !onBehalfOf) {
throw new HTTP403Error('Not authorized');
}
}
/**
* only the data field is allowed to be updated
*/
const model = (await db.update({
where: { id: id },
data: { data: docData },
include: {
documentRoot: {
include: {
rootGroupPermissions: { select: { access: true, studentGroupId: true } },
rootUserPermissions: { select: { access: true, userId: true } }
}
}
}
})) satisfies DbDocument;
return model;
},
async deleteModel(actor: User, id: string) {
const record = await this.findModel(actor, id);
if (!record) {
throw new HTTP404Error('Document not found');
}
/**
* models can be deleted when the actor is the author and has RW access.
*/
const canDelete = record.document.authorId === actor.id && RWAccess.has(record.highestPermission);
if (!canDelete) {
throw new HTTP403Error('Not authorized');
}
const model = (await db.delete({
where: { id: id },
include: {
documentRoot: {
include: {
rootGroupPermissions: { select: { access: true, studentGroupId: true } },
rootUserPermissions: { select: { access: true, userId: true } }
}
}
}
})) satisfies DbDocument;
return model;
},
async allOfDocumentRoots(
actor: User | { role: Role | string; id: string },
documentRootIds: string[]
): Promise<DbDocument[]> {
if (!hasElevatedAccess(actor.role)) {
throw new HTTP403Error('Not authorized');
}
if (actor.role === Role.ADMIN) {
return db.findMany({ where: { documentRootId: { in: documentRootIds } } });
}
// only include documents where the author is in the same group as the actor.
const documents = await db.findMany({
where: {
documentRootId: { in: documentRootIds },
author: whereStudentGroupAccess(actor.id, true)
}
});
return documents;
}
});
}
export default Document(prisma.document);