shoc-backend/SeaHaven.Services/Helpers/WorkOrderUploadFileRules.cs

54 lines
1.6 KiB
C#
Raw Normal View History

namespace SeaHaven.Services.Helpers
{
public static class WorkOrderUploadFileRules
{
private static readonly HashSet<string> AllowedExtensions = new(StringComparer.OrdinalIgnoreCase)
{
".pdf",
".png",
".jpg",
".jpeg",
".webp",
".gif",
".doc",
".docx",
".xls",
".xlsx",
".txt"
};
public static bool TryGetAllowedExtension(string? clientFileName, out string extension, out string? error)
{
extension = string.Empty;
error = null;
if (string.IsNullOrWhiteSpace(clientFileName))
{
error = "file name is required.";
return false;
}
// Reject path segments from the client; only the final name matters for extension.
var name = Path.GetFileName(clientFileName.Replace('\\', '/'));
if (string.IsNullOrWhiteSpace(name) || name is "." or "..")
{
error = "Invalid file name.";
return false;
}
var ext = Path.GetExtension(name);
if (string.IsNullOrWhiteSpace(ext) || !AllowedExtensions.Contains(ext))
{
error = $"File type '{ext}' is not allowed.";
return false;
}
extension = ext.ToLowerInvariant();
return true;
}
public static string BuildServerFileName(string extension)
=> $"{Guid.NewGuid():N}{extension}";
}
}