From 3e8f4ec2c588d7644d11d40681c6b7cf081caf1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20M?= Date: Fri, 12 Jan 2024 12:12:33 +0100 Subject: [PATCH] fix: auth user decorator cannot destruct property of undefined (#3394) * fix: auth user decorator cannot destruct property of undefined * fix: change naming --- .../src/core/analytics/analytics.resolver.ts | 2 +- .../src/decorators/auth-user.decorator.ts | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/twenty-server/src/core/analytics/analytics.resolver.ts b/packages/twenty-server/src/core/analytics/analytics.resolver.ts index e4564e2339..c912dd52ca 100644 --- a/packages/twenty-server/src/core/analytics/analytics.resolver.ts +++ b/packages/twenty-server/src/core/analytics/analytics.resolver.ts @@ -21,7 +21,7 @@ export class AnalyticsResolver { createEvent( @Args() createEventInput: CreateAnalyticsInput, @AuthWorkspace() workspace: Workspace | undefined, - @AuthUser() user: User | undefined, + @AuthUser({ allowUndefined: true }) user: User | undefined, ) { return this.analyticsService.create(createEventInput, user, workspace); } diff --git a/packages/twenty-server/src/decorators/auth-user.decorator.ts b/packages/twenty-server/src/decorators/auth-user.decorator.ts index b14e69523c..77248f4fd4 100644 --- a/packages/twenty-server/src/decorators/auth-user.decorator.ts +++ b/packages/twenty-server/src/decorators/auth-user.decorator.ts @@ -1,11 +1,23 @@ -import { ExecutionContext, createParamDecorator } from '@nestjs/common'; +import { + ExecutionContext, + ForbiddenException, + createParamDecorator, +} from '@nestjs/common'; import { getRequest } from 'src/utils/extract-request'; +interface DecoratorOptions { + allowUndefined?: boolean; +} + export const AuthUser = createParamDecorator( - (_: unknown, ctx: ExecutionContext) => { + (options: DecoratorOptions | undefined, ctx: ExecutionContext) => { const request = getRequest(ctx); + if (!options?.allowUndefined && (!request.user || !request.user.user)) { + throw new ForbiddenException("You're not authorized to do this"); + } + return request.user ? request.user.user : undefined; }, );