refactor: replace permission check methods with ordered permission enum

This commit replaces the "mayWrite", "mayRead" and "checkPermissionOnNote"
functions with one that returns a sortable permission value.
This is done because many places in the code need to do actions based on the fact if
the user has no, read or write access. If done with the may-functions then the permission
data need to be looked through multiple times.

Also, the whole check code is split into more functions that are tested separately and make it easier
to understand the process.

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2023-05-10 22:50:03 +02:00
parent 4e298cccfb
commit a852c79947
15 changed files with 925 additions and 787 deletions

View file

@ -0,0 +1,65 @@
/*
* SPDX-FileCopyrightText: 2023 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Mock } from 'ts-mockery';
import { User } from '../../users/user.entity';
import { NotePermission } from '../note-permission.enum';
import { NoteUserPermission } from '../note-user-permission.entity';
import { findHighestNotePermissionByUser } from './find-highest-note-permission-by-user';
describe('find highest note permission by user', () => {
const user1 = Mock.of<User>({ id: 0 });
const user2 = Mock.of<User>({ id: 1 });
const user3 = Mock.of<User>({ id: 2 });
const permissionUser2Read = Mock.of<NoteUserPermission>({
user: Promise.resolve(user2),
canEdit: false,
});
const permissionUser3Read = Mock.of<NoteUserPermission>({
user: Promise.resolve(user3),
canEdit: false,
});
const permissionUser3Write = Mock.of<NoteUserPermission>({
user: Promise.resolve(user3),
canEdit: true,
});
it('will fallback to NONE if no permission for the user could be found', async () => {
const result = await findHighestNotePermissionByUser(user1, [
permissionUser2Read,
permissionUser3Write,
]);
expect(result).toBe(NotePermission.DENY);
});
it('can extract a READ permission for the correct user', async () => {
const result = await findHighestNotePermissionByUser(user2, [
permissionUser2Read,
permissionUser3Write,
]);
expect(result).toBe(NotePermission.READ);
});
it('can extract a WRITE permission for the correct user', async () => {
const result = await findHighestNotePermissionByUser(user3, [
permissionUser2Read,
permissionUser3Write,
]);
expect(result).toBe(NotePermission.WRITE);
});
it('can extract a WRITE permission for the correct user if read and write are defined', async () => {
const result = await findHighestNotePermissionByUser(user3, [
permissionUser2Read,
permissionUser3Read,
permissionUser3Write,
]);
expect(result).toBe(NotePermission.WRITE);
});
});