| | | 1 | | using Chronicis.Api.Data; |
| | | 2 | | using Chronicis.Api.Models; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | |
| | | 5 | | namespace Chronicis.Api.Services; |
| | | 6 | | |
| | | 7 | | public sealed class ImageAccessService : IImageAccessService |
| | | 8 | | { |
| | | 9 | | private readonly ChronicisDbContext _context; |
| | | 10 | | private readonly IBlobStorageService _blobStorage; |
| | | 11 | | private readonly ILogger<ImageAccessService> _logger; |
| | | 12 | | |
| | | 13 | | public ImageAccessService( |
| | | 14 | | ChronicisDbContext context, |
| | | 15 | | IBlobStorageService blobStorage, |
| | | 16 | | ILogger<ImageAccessService> logger) |
| | | 17 | | { |
| | 4 | 18 | | _context = context; |
| | 4 | 19 | | _blobStorage = blobStorage; |
| | 4 | 20 | | _logger = logger; |
| | 4 | 21 | | } |
| | | 22 | | |
| | | 23 | | public async Task<ServiceResult<string>> GetImageDownloadUrlAsync(Guid documentId, Guid userId) |
| | | 24 | | { |
| | | 25 | | var document = await _context.WorldDocuments |
| | | 26 | | .AsNoTracking() |
| | | 27 | | .Include(d => d.World) |
| | | 28 | | .FirstOrDefaultAsync(d => d.Id == documentId); |
| | | 29 | | |
| | | 30 | | if (document == null) |
| | | 31 | | { |
| | | 32 | | return ServiceResult<string>.NotFound(); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | var hasAccess = document.World.OwnerId == userId |
| | | 36 | | || await _context.WorldMembers.AnyAsync(m => m.WorldId == document.WorldId && m.UserId == userId); |
| | | 37 | | |
| | | 38 | | if (!hasAccess) |
| | | 39 | | { |
| | | 40 | | return ServiceResult<string>.Forbidden(); |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | if (!document.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) |
| | | 44 | | { |
| | | 45 | | _logger.LogWarningSanitized("Non-image document {DocumentId} requested via image proxy", documentId); |
| | | 46 | | return ServiceResult<string>.ValidationError("Document is not an image"); |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | var downloadUrl = await _blobStorage.GenerateDownloadSasUrlAsync(document.BlobPath); |
| | | 50 | | return ServiceResult<string>.Success(downloadUrl); |
| | | 51 | | } |
| | | 52 | | } |
| | | 53 | | |