Sanitize file name on upload

This commit is contained in:
AJ
2025-10-04 18:19:08 -04:00
parent 462973cf2f
commit a5046df38c

View File

@@ -1,13 +1,14 @@
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using MoneyMap.Data;
using MoneyMap.Models;
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace MoneyMap.Services
{
@@ -98,7 +99,7 @@ namespace MoneyMap.Services
var receipt = new Receipt
{
TransactionId = transactionId,
FileName = file.FileName,
FileName = SanitizeFileName(file.FileName),
StoragePath = relativeStoragePath,
FileSizeBytes = file.Length,
ContentType = file.ContentType,
@@ -112,6 +113,36 @@ namespace MoneyMap.Services
return ReceiptUploadResult.Success(receipt);
}
private static string SanitizeFileName(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName))
return "receipt";
// Remove non-ASCII characters and replace them with safe equivalents
var sanitized = new StringBuilder();
foreach (var c in fileName)
{
if (c == '®' || c == '™' || c == '©')
{
// Skip trademark/copyright symbols
continue;
}
else if (c >= 32 && c <= 126)
{
// Keep ASCII printable characters
sanitized.Append(c);
}
else
{
// Replace other non-ASCII with underscore
sanitized.Append('_');
}
}
var result = sanitized.ToString().Trim();
return string.IsNullOrWhiteSpace(result) ? "receipt" : result;
}
public async Task<bool> DeleteReceiptAsync(long receiptId)
{
var receipt = await _db.Receipts.FindAsync(receiptId);