refactor: extract permission checking from controllers and guard

Signed-off-by: Yannick Bungers <git@innay.de>
Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Yannick Bungers 2023-03-26 15:51:08 +02:00 committed by Yannick Bungers
parent 485f7cd338
commit 001a49329c
4 changed files with 60 additions and 21 deletions

View file

@ -19,6 +19,7 @@ import { Group } from '../groups/group.entity';
import { GroupsService } from '../groups/groups.service';
import { SpecialGroup } from '../groups/groups.special';
import { ConsoleLoggerService } from '../logger/console-logger.service';
import { MediaUpload } from '../media/media-upload.entity';
import { NotePermissionsUpdateDto } from '../notes/note-permissions.dto';
import { Note } from '../notes/note.entity';
import { User } from '../users/user.entity';
@ -26,6 +27,7 @@ import { UsersService } from '../users/users.service';
import { checkArrayForDuplicates } from '../utils/arrayDuplicatCheck';
import { NoteGroupPermission } from './note-group-permission.entity';
import { NoteUserPermission } from './note-user-permission.entity';
import { Permission } from './permissions.enum';
@Injectable()
export class PermissionsService {
@ -38,6 +40,43 @@ export class PermissionsService {
private noteConfig: NoteConfig,
private eventEmitter: EventEmitter2<NoteEventMap>,
) {}
/**
* Checks if the given {@link User} is has the in {@link desiredPermission} specified permission on {@link Note}.
*
* @async
* @param {Permission} desiredPermission - permission level to check for
* @param {User} user - The user whose permission should be checked. Value is null if guest access should be checked
* @param {Note} note - The note for which the permission should be checked
* @return if the user has the specified permission on the note
*/
public async checkPermissionOnNote(
desiredPermission: Permission,
user: User | null,
note: Note,
): Promise<boolean> {
switch (desiredPermission) {
case Permission.READ:
return await this.mayRead(user, note);
case Permission.WRITE:
return await this.mayWrite(user, note);
case Permission.OWNER:
return await this.isOwner(user, note);
}
return false;
}
public async checkMediaDeletePermission(
user: User,
mediaUpload: MediaUpload,
): Promise<boolean> {
const mediaUploadNote = await mediaUpload.note;
const mediaUploadOwner = await mediaUpload.user;
const owner =
!!mediaUploadNote && (await this.isOwner(user, mediaUploadNote));
return mediaUploadOwner?.id === user.id || owner;
}
/**
* Checks if the given {@link User} is allowed to read the given {@link Note}.