From 7afda85f03d410a6c611860d0c3fb2b88a2e3679 Mon Sep 17 00:00:00 2001 From: Elias Schneider Date: Fri, 17 May 2024 15:13:56 +0200 Subject: [PATCH] fix: admin couldn't delete shares created by anonymous users --- backend/src/share/guard/shareOwner.guard.ts | 16 +++++++++++++--- backend/src/share/share.controller.ts | 5 +++-- backend/src/share/share.service.ts | 5 +++-- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/backend/src/share/guard/shareOwner.guard.ts b/backend/src/share/guard/shareOwner.guard.ts index 0ff7263..f8f4812 100644 --- a/backend/src/share/guard/shareOwner.guard.ts +++ b/backend/src/share/guard/shareOwner.guard.ts @@ -5,9 +5,9 @@ import { } from "@nestjs/common"; import { User } from "@prisma/client"; import { Request } from "express"; +import { ConfigService } from "src/config/config.service"; import { PrismaService } from "src/prisma/prisma.service"; import { JwtGuard } from "../../auth/guard/jwt.guard"; -import { ConfigService } from "src/config/config.service"; @Injectable() export class ShareOwnerGuard extends JwtGuard { @@ -34,10 +34,20 @@ export class ShareOwnerGuard extends JwtGuard { if (!share) throw new NotFoundException("Share not found"); + // Run the JWTGuard to set the user + await super.canActivate(context); + const user = request.user as User; + + // If the user is an admin, allow access + if (user?.isAdmin) return true; + + // If it's a anonymous share, allow access if (!share.creatorId) return true; - if (!(await super.canActivate(context))) return false; + // If not signed in, deny access + if (!user) return false; - return share.creatorId == (request.user as User).id; + // If the user is the creator of the share, allow access + return share.creatorId == user.id; } } diff --git a/backend/src/share/share.controller.ts b/backend/src/share/share.controller.ts index a3ae9e0..ce4f3b8 100644 --- a/backend/src/share/share.controller.ts +++ b/backend/src/share/share.controller.ts @@ -94,8 +94,9 @@ export class ShareController { @Delete(":id") @UseGuards(ShareOwnerGuard) - async remove(@Param("id") id: string) { - await this.shareService.remove(id); + async remove(@Param("id") id: string, @GetUser() user: User) { + const isDeleterAdmin = user?.isAdmin === true; + await this.shareService.remove(id, isDeleterAdmin); } @Throttle(10, 60) diff --git a/backend/src/share/share.service.ts b/backend/src/share/share.service.ts index 3fbbeb8..ff4545b 100644 --- a/backend/src/share/share.service.ts +++ b/backend/src/share/share.service.ts @@ -267,13 +267,14 @@ export class ShareService { return share; } - async remove(shareId: string) { + async remove(shareId: string, isDeleterAdmin = false) { const share = await this.prisma.share.findUnique({ where: { id: shareId }, }); if (!share) throw new NotFoundException("Share not found"); - if (!share.creatorId) + + if (!share.creatorId && !isDeleterAdmin) throw new ForbiddenException("Anonymous shares can't be deleted"); await this.fileService.deleteAllFiles(shareId);