Documents need to show, upload and generate their files from the interface, and users need to see who changed a record. This adds the attachment list (upload, preview, download, lock, trash and restore, older versions, ZIP, generate/regenerate), in-app previews for PDF, images, XML, text, CSV and XLSX, an A4 print preview with "save as attachment", and an audit history list read through a permission-checked AuditTrailService. Files are served by /files endpoints that require a signed-in user and the company permissions; only PDF and images open inline, with their own CSP that allows framing by this site only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
135 lines
6.8 KiB
C#
135 lines
6.8 KiB
C#
using System.Globalization;
|
|
using System.Net.Mime;
|
|
using Khaemhat.Application.Files;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Web.Security;
|
|
|
|
namespace Khaemhat.Web.Hosting;
|
|
|
|
/// <summary>
|
|
/// The addresses that send files to the browser (SPEC §9.4, mockup 024-025): an attachment, all the attachments of a
|
|
/// record as ZIP, a file generated on the fly (print preview). The services check company and permissions; only PDF
|
|
/// and common images open in the browser, everything else is downloaded.
|
|
/// </summary>
|
|
public static class FileEndpoints
|
|
{
|
|
/// <summary>The content security policy of a file opened in the browser: framed by this site only, no scripts.</summary>
|
|
public const string InlinePolicy = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; object-src 'self'; frame-ancestors 'self'";
|
|
|
|
/// <summary>The base address.</summary>
|
|
public const string BasePath = "/files";
|
|
|
|
/// <summary>The address of an attachment, opened in the browser when it can be.</summary>
|
|
/// <param name="id">The attachment.</param>
|
|
/// <returns>The address relative to the application.</returns>
|
|
public static string View(long id) => BasePath[1..] + "/" + id.ToString(CultureInfo.InvariantCulture);
|
|
|
|
/// <summary>The address that downloads an attachment.</summary>
|
|
/// <param name="id">The attachment.</param>
|
|
/// <returns>The address relative to the application.</returns>
|
|
public static string Download(long id) => View(id) + "?download=1";
|
|
|
|
/// <summary>The address of the ZIP with all the attachments of a record.</summary>
|
|
/// <param name="entity">The entity.</param>
|
|
/// <param name="entityId">The record.</param>
|
|
/// <returns>The address relative to the application.</returns>
|
|
public static string Zip(string entity, long entityId) =>
|
|
BasePath[1..] + "/zip?entity=" + Uri.EscapeDataString(entity) + "&id=" + entityId.ToString(CultureInfo.InvariantCulture);
|
|
|
|
/// <summary>The address of a file generated on the fly, without attaching it.</summary>
|
|
/// <param name="entity">The entity.</param>
|
|
/// <param name="entityId">The record.</param>
|
|
/// <param name="generator">The generator code.</param>
|
|
/// <param name="download">Whether to download it instead of opening it.</param>
|
|
/// <returns>The address relative to the application.</returns>
|
|
public static string Generated(string entity, long entityId, string generator, bool download = false) =>
|
|
BasePath[1..] + "/generate?entity=" + Uri.EscapeDataString(entity) + "&id=" + entityId.ToString(CultureInfo.InvariantCulture)
|
|
+ "&generator=" + Uri.EscapeDataString(generator) + (download ? "&download=1" : string.Empty);
|
|
|
|
/// <summary>Whether a media type may be shown by the browser instead of downloaded.</summary>
|
|
/// <param name="mime">The media type.</param>
|
|
/// <returns><see langword="true"/> for PDF and common images.</returns>
|
|
public static bool OpensInBrowser(string mime) => MediaTypes.PreviewOf(mime) is AttachmentPreview.Pdf or AttachmentPreview.Image;
|
|
|
|
/// <summary>Maps the addresses.</summary>
|
|
/// <param name="endpoints">The application.</param>
|
|
public static void MapFiles(this IEndpointRouteBuilder endpoints)
|
|
{
|
|
endpoints.MapGet(BasePath + "/{id:long}", (HttpContext context, long id, AttachmentService attachments) =>
|
|
RunAsync(context, async actor =>
|
|
{
|
|
var file = await attachments.OpenAsync(actor, Company(actor), id, context.RequestAborted).ConfigureAwait(false);
|
|
context.Response.RegisterForDisposeAsync(file);
|
|
return Send(context, file.Content, file.Attachment.Mime, file.Attachment.FileName);
|
|
}));
|
|
|
|
endpoints.MapGet(BasePath + "/zip", (HttpContext context, string entity, long id, AttachmentService attachments) =>
|
|
RunAsync(context, async actor =>
|
|
{
|
|
// Read the list first: missing rights fail before the download starts.
|
|
var company = Company(actor);
|
|
var list = await attachments.ListAsync(actor, company, entity, id, cancellationToken: context.RequestAborted).ConfigureAwait(false);
|
|
var name = MediaTypes.CleanFileName(entity.Replace('.', '-') + "-" + id.ToString(CultureInfo.InvariantCulture) + "-allegati.zip");
|
|
return list.Count == 0
|
|
? Results.NotFound()
|
|
: Results.Stream(output => attachments.WriteZipAsync(actor, company, entity, id, output, context.RequestAborted), MediaTypes.Zip, name);
|
|
}));
|
|
|
|
endpoints.MapGet(BasePath + "/generate", (HttpContext context, string entity, long id, string generator, FileGenerationService files) =>
|
|
RunAsync(context, async actor =>
|
|
{
|
|
var content = new MemoryStream();
|
|
context.Response.RegisterForDisposeAsync(content);
|
|
var (name, mime) = await files.WriteAsync(actor, Company(actor), entity, id, generator, content, context.RequestAborted).ConfigureAwait(false);
|
|
content.Position = 0;
|
|
return Send(context, content, mime, name);
|
|
}));
|
|
}
|
|
|
|
private static string Company(Actor actor) =>
|
|
actor.CompanyCode ?? throw new AccessDeniedException(SecurityErrors.PermissionDenied, "Files belong to a company: choose one first.");
|
|
|
|
private static async Task<IResult> RunAsync(HttpContext context, Func<Actor, Task<IResult>> action)
|
|
{
|
|
if (SessionCookie.ActorOf(context.User) is not { } actor)
|
|
{
|
|
return Results.Unauthorized();
|
|
}
|
|
|
|
try
|
|
{
|
|
return await action(actor).ConfigureAwait(false);
|
|
}
|
|
catch (AccessDeniedException)
|
|
{
|
|
return Results.StatusCode(StatusCodes.Status403Forbidden);
|
|
}
|
|
catch (ValidationFailedException ex) when (ex.Errors.Contains(AttachmentService.NotFoundError))
|
|
{
|
|
return Results.NotFound();
|
|
}
|
|
catch (ValidationFailedException)
|
|
{
|
|
return Results.BadRequest();
|
|
}
|
|
}
|
|
|
|
private static IResult Send(HttpContext context, Stream content, string mime, string fileName)
|
|
{
|
|
var download = context.Request.Query.ContainsKey("download") || !OpensInBrowser(mime);
|
|
if (download)
|
|
{
|
|
return Results.File(content, mime, fileName, enableRangeProcessing: true);
|
|
}
|
|
|
|
var disposition = new ContentDisposition { Inline = true, FileName = fileName };
|
|
context.Response.Headers.ContentDisposition = disposition.ToString();
|
|
context.Response.Headers.CacheControl = "private, no-store";
|
|
|
|
// Shown inside the preview of this site only: no scripts, no other framing site.
|
|
context.Response.Headers.ContentSecurityPolicy = InlinePolicy;
|
|
context.Response.Headers.XFrameOptions = "SAMEORIGIN";
|
|
return Results.File(content, mime, enableRangeProcessing: true);
|
|
}
|
|
}
|