diff --git a/src/api/utils/request-user.decorator.ts b/src/api/utils/request-user.decorator.ts index 02284262e..71b96e428 100644 --- a/src/api/utils/request-user.decorator.ts +++ b/src/api/utils/request-user.decorator.ts @@ -1,31 +1,42 @@ /* - * SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file) + * SPDX-FileCopyrightText: 2022 The HedgeDoc developers (see AUTHORS file) * * SPDX-License-Identifier: AGPL-3.0-only */ import { createParamDecorator, ExecutionContext, - InternalServerErrorException, + UnauthorizedException, } from '@nestjs/common'; import { Request } from 'express'; import { User } from '../../users/user.entity'; +type RequestUserParameter = { + guestsAllowed: boolean; +}; + /** - * Extracts the {@link User} object from a request + * Trys to extract the {@link User} object from a request * - * Will throw an {@link InternalServerErrorException} if no user is present + * If a user is present in the request, returns the user object. + * If no user is present and guests are allowed, returns `null`. + * If no user is present and guests are not allowed, throws {@link UnauthorizedException}. */ // eslint-disable-next-line @typescript-eslint/naming-convention export const RequestUser = createParamDecorator( - (data: unknown, ctx: ExecutionContext) => { - const request: Request & { user: User } = ctx.switchToHttp().getRequest(); + ( + data: RequestUserParameter = { guestsAllowed: false }, + ctx: ExecutionContext, + ) => { + const request: Request & { user: User | null } = ctx + .switchToHttp() + .getRequest(); if (!request.user) { - // We should have a user here, otherwise something is wrong - throw new InternalServerErrorException( - 'Request is missing a user object', - ); + if (data.guestsAllowed) { + return null; + } + throw new UnauthorizedException("You're not logged in"); } return request.user; },