feat: add guestsAllowed to RequestUser

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2022-10-03 21:06:49 +02:00
parent 6b62688824
commit b0247b0efb

View file

@ -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;
},