From 7d1f81c3a2f786a0b3b65907bb9c2c3fe7205c7a Mon Sep 17 00:00:00 2001 From: Liam Date: Tue, 23 Apr 2024 21:16:42 +0100 Subject: [PATCH] impl a char limit for pastes --- .../backend/exception/impl/BadRequestException.java | 9 +++++++++ .../cc/fascinated/backend/service/PasteService.java | 12 ++++++++++++ src/main/resources/application.yml | 2 ++ 3 files changed, 23 insertions(+) create mode 100644 src/main/java/cc/fascinated/backend/exception/impl/BadRequestException.java diff --git a/src/main/java/cc/fascinated/backend/exception/impl/BadRequestException.java b/src/main/java/cc/fascinated/backend/exception/impl/BadRequestException.java new file mode 100644 index 0000000..e9e0343 --- /dev/null +++ b/src/main/java/cc/fascinated/backend/exception/impl/BadRequestException.java @@ -0,0 +1,9 @@ +package cc.fascinated.backend.exception.impl; + +import lombok.experimental.StandardException; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@StandardException +@ResponseStatus(HttpStatus.BAD_REQUEST) +public class BadRequestException extends RuntimeException { } diff --git a/src/main/java/cc/fascinated/backend/service/PasteService.java b/src/main/java/cc/fascinated/backend/service/PasteService.java index da03cb1..c8cb4c8 100644 --- a/src/main/java/cc/fascinated/backend/service/PasteService.java +++ b/src/main/java/cc/fascinated/backend/service/PasteService.java @@ -1,5 +1,6 @@ package cc.fascinated.backend.service; +import cc.fascinated.backend.exception.impl.BadRequestException; import cc.fascinated.backend.model.Paste; import cc.fascinated.backend.exception.impl.ResourceNotFoundException; import cc.fascinated.backend.repository.PasteRepository; @@ -24,6 +25,12 @@ public class PasteService { @Value("${paste.id-length}") private int idLength; + /** + * The maximum size of the paste content. + */ + @Value("${paste.upload-size-limit}") + private int uploadSizeLimit; + @Autowired public PasteService(PasteRepository pasteRepository) { this.pasteRepository = pasteRepository; @@ -36,6 +43,11 @@ public class PasteService { * @return The id of the paste. */ public String createPaste(String content) { + int length = content.length(); + if (length > uploadSizeLimit) { + throw new BadRequestException("The paste content is too large, the limit is " + uploadSizeLimit + " characters"); + } + return pasteRepository.save(new Paste( RandomStringUtils.randomAlphabetic(idLength), System.currentTimeMillis(), diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index aad4085..5ff02a7 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -23,6 +23,8 @@ spring: paste: # The length of the ID for the paste id-length: 12 + # The limit of the paste size (in characters) + upload-size-limit: 400000 # Set the embedded MongoDB version de: