From cd9d82868608a31491cd389057895ac3eb20ce56 Mon Sep 17 00:00:00 2001 From: Elias Schneider Date: Tue, 31 Jan 2023 13:53:23 +0100 Subject: [PATCH] refactor: move guard checks to service --- backend/src/share/guard/shareSecurity.guard.ts | 10 ++++------ .../src/share/guard/shareTokenSecurity.guard.ts | 15 +++------------ backend/src/share/share.service.ts | 10 +++++++++- 3 files changed, 16 insertions(+), 19 deletions(-) diff --git a/backend/src/share/guard/shareSecurity.guard.ts b/backend/src/share/guard/shareSecurity.guard.ts index c2589ce..9511af0 100644 --- a/backend/src/share/guard/shareSecurity.guard.ts +++ b/backend/src/share/guard/shareSecurity.guard.ts @@ -34,12 +34,10 @@ export class ShareSecurityGuard implements CanActivate { include: { security: true }, }); - if ( - !share || - (moment().isAfter(share.expiration) && - moment(share.expiration).unix() !== 0) - ) - throw new NotFoundException("Share not found"); + const isExpired = + moment().isAfter(share.expiration) && !moment(share.expiration).isSame(0); + + if (!share || isExpired) throw new NotFoundException("Share not found"); if (share.security?.password && !shareToken) throw new ForbiddenException( diff --git a/backend/src/share/guard/shareTokenSecurity.guard.ts b/backend/src/share/guard/shareTokenSecurity.guard.ts index f108842..4363fac 100644 --- a/backend/src/share/guard/shareTokenSecurity.guard.ts +++ b/backend/src/share/guard/shareTokenSecurity.guard.ts @@ -1,7 +1,6 @@ import { CanActivate, ExecutionContext, - ForbiddenException, Injectable, NotFoundException, } from "@nestjs/common"; @@ -27,18 +26,10 @@ export class ShareTokenSecurity implements CanActivate { include: { security: true }, }); - if ( - !share || - (moment().isAfter(share.expiration) && - !moment(share.expiration).isSame(0)) - ) - throw new NotFoundException("Share not found"); + const isExpired = + moment().isAfter(share.expiration) && !moment(share.expiration).isSame(0); - if (share.security?.maxViews && share.security.maxViews <= share.views) - throw new ForbiddenException( - "Maximum views exceeded", - "share_max_views_exceeded" - ); + if (!share || isExpired) throw new NotFoundException("Share not found"); return true; } diff --git a/backend/src/share/share.service.ts b/backend/src/share/share.service.ts index 9afff73..25c0d60 100644 --- a/backend/src/share/share.service.ts +++ b/backend/src/share/share.service.ts @@ -273,8 +273,16 @@ export class ShareService { if ( share?.security?.password && !(await argon.verify(share.security.password, password)) - ) + ) { throw new ForbiddenException("Wrong password"); + } + + if (share.security?.maxViews && share.security.maxViews <= share.views) { + throw new ForbiddenException( + "Maximum views exceeded", + "share_max_views_exceeded" + ); + } const token = await this.generateShareToken(shareId); await this.increaseViewCount(share);