Update to allow read access for app

This commit is contained in:
jheaps
2025-10-16 14:59:45 -06:00
parent 4bf29488dd
commit 4b68886252
5 changed files with 184 additions and 12 deletions
+32 -12
View File
@@ -1,5 +1,6 @@
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace Media.JoshHeaps.Net.Api;
@@ -17,15 +18,14 @@ public class MediaApi : ControllerBase
[HttpGet("load")]
public async Task<IActionResult> LoadMedia([FromQuery] int offset = 0, [FromQuery] int limit = 20)
{
// Get user ID from session
var userIdString = HttpContext.Session.GetString("UserId");
if (string.IsNullOrEmpty(userIdString))
// Get user ID from JWT claims or session
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized();
}
var userId = long.Parse(userIdString);
var media = await _mediaService.GetUserMediaAsync(userId, offset, limit);
var media = await _mediaService.GetUserMediaAsync(userId.Value, offset, limit);
return Ok(media);
}
@@ -33,24 +33,22 @@ public class MediaApi : ControllerBase
[HttpGet("image/{mediaId}")]
public async Task<IActionResult> GetImage(long mediaId)
{
// Get user ID from session
var userIdString = HttpContext.Session.GetString("UserId");
if (string.IsNullOrEmpty(userIdString))
// Get user ID from JWT claims or session
var userId = GetUserIdFromAuth();
if (userId == null)
{
return Unauthorized(new { error = "Not authenticated" });
}
var userId = long.Parse(userIdString);
// Get media metadata (includes ownership check)
var media = await _mediaService.GetMediaByIdAsync(mediaId, userId);
var media = await _mediaService.GetMediaByIdAsync(mediaId, userId.Value);
if (media == null)
{
return NotFound(new { error = "Image not found or access denied" });
}
// Get decrypted image data
var imageData = await _mediaService.GetDecryptedMediaDataAsync(mediaId, userId);
var imageData = await _mediaService.GetDecryptedMediaDataAsync(mediaId, userId.Value);
if (imageData == null)
{
return NotFound(new { error = "Image file not found" });
@@ -59,4 +57,26 @@ public class MediaApi : ControllerBase
// Return image with proper content type
return File(imageData, media.MimeType);
}
/// <summary>
/// Gets user ID from either JWT claims (for API) or session (for web)
/// </summary>
private long? GetUserIdFromAuth()
{
// First try JWT claims (for mobile/API authentication)
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!string.IsNullOrEmpty(userIdClaim) && long.TryParse(userIdClaim, out var jwtUserId))
{
return jwtUserId;
}
// Fall back to session (for web authentication)
var userIdString = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userIdString) && long.TryParse(userIdString, out var sessionUserId))
{
return sessionUserId;
}
return null;
}
}