Skip to content
This repository has been archived by the owner on Jul 12, 2024. It is now read-only.

Commit

Permalink
feat: valid file filter
Browse files Browse the repository at this point in the history
  • Loading branch information
foxminchan committed May 12, 2024
1 parent ff9fb07 commit 7c114ad
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
41 changes: 41 additions & 0 deletions src/RookieShop.ApiService/Filters/FileValidationFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using FluentValidation;

namespace RookieShop.ApiService.Filters;

public sealed class FileValidationFilter : IEndpointFilter
{
private const int MaxFileSize = 1048576;

public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var request = context.HttpContext.Request;
var formCollection = await request.ReadFormAsync();
var files = formCollection.Files;

if (files.Count == 0)
return await next(context);

foreach (var file in files)
{
switch (file.Length)
{
case 0:
context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
throw new ValidationException("File is empty.");
case > MaxFileSize:
context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
throw new ValidationException($"File size is too large. Max file size is {MaxFileSize / 1024} KB.");
}

List<string> allowedExtensions = [".jpg", ".jpeg", ".png"];
var extension = Path.GetExtension(file.FileName);

if (allowedExtensions.Contains(extension)) continue;

context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
throw new ValidationException($"File extension {extension} is not allowed.");
}

return await next(context);
}
}
2 changes: 1 addition & 1 deletion src/RookieShop.ApiService/Filters/IdempotencyFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace RookieShop.ApiService.Filters;

public class IdempotencyFilter(IRedisService redisService) : IEndpointFilter
public sealed class IdempotencyFilter(IRedisService redisService) : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
Expand Down

0 comments on commit 7c114ad

Please sign in to comment.