Additional checking for post uploads

This commit is contained in:
2025-10-13 10:14:57 +03:00
parent 30cb0521f6
commit cadb8453a2
3 changed files with 19 additions and 1488 deletions

View File

@@ -22,7 +22,8 @@ public class PostController(
ITagService tagService,
ICommentService commentService,
IFileService fileService,
IWebHostEnvironment env
IWebHostEnvironment env,
ILogger<PostController> logger
): ControllerBase
{
@@ -117,6 +118,7 @@ public class PostController(
/// <response code="400">If request is malformed</response>
/// <response code="401">If authentication is missing</response>
/// <response code="403">If authorization is missing</response>
/// <response code="422">If data provided does not fit constraints</response>
[HttpPost]
[Authorize(Roles = UserRoles.Regular)]
[ProducesResponseType(StatusCodes.Status201Created)]
@@ -129,6 +131,11 @@ public class PostController(
var userId = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value;
var user = await userService.GetUserById(userId);
if (user == null) return Unauthorized();
if (dto.FileSize.Value > 10*1024*1024) return Problem("File cannot exceed 10MB", statusCode: StatusCodes.Status422UnprocessableEntity);
if (dto.FileMimeType != "image/png" && dto.FileMimeType != "image/jpeg")
return Problem("File must be image", statusCode: StatusCodes.Status422UnprocessableEntity);
var maybeTags = await TagNamesToTags(dto.Tags);
List<Tag> tags;
@@ -164,6 +171,7 @@ public class PostController(
/// <response code="401">If authentication is missing</response>
/// <response code="403">If authorization is missing</response>
/// <response code="404">If post or file is not found</response>
/// <response code="409">If a chunk was already uploaded</response>
/// <response code="415">If finished upload mime does not match provided</response>
[HttpPatch("{postId:int}/files/{fileId:int}")]
[Authorize(Roles = UserRoles.Regular)]
@@ -214,11 +222,18 @@ public class PostController(
// Append the chunk to the temporary file
var tempFilePath = fileRecord.FilePath;
await using (var stream = new FileStream(tempFilePath, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
try
{
await using var stream = new FileStream(tempFilePath, FileMode.Append, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true);
stream.Seek(start, SeekOrigin.Begin);
await Request.Body.CopyToAsync(stream);
}
catch (Exception e)
{
logger.LogCritical(e.ToString());
return Problem("Chunk has already been uploaded", statusCode: StatusCodes.Status409Conflict);
}
// Check if the upload is complete
// Return 202 Accepted for a successful intermediate chunk