More logging and error handling for API routes

This commit is contained in:
Pat Hartl 2024-09-17 00:18:39 -05:00
parent 594fd0908b
commit 5d3ff9cada
3 changed files with 18 additions and 2 deletions

View file

@ -80,6 +80,8 @@ namespace LANCommander.Server.Controllers.Api
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
await SignInManager.SignOutAsync();
Logger?.LogInformation("Logged out user {UserName}", User.Identity.Name);
return Ok();
}

View file

@ -45,6 +45,7 @@ namespace LANCommander.Server.Controllers.Api
var games = await GameService.Get(g => g.Type == SDK.Enums.GameType.MainGame || g.Type == SDK.Enums.GameType.StandaloneExpansion || g.Type == SDK.Enums.GameType.StandaloneMod).ToListAsync();
var mappedGames = await Cache.GetOrSetAsync<IEnumerable<SDK.Models.Game>>("MappedGames", async _ => {
Logger?.LogDebug("Mapped games cache is empty, repopulating");
return Mapper.Map<IEnumerable<SDK.Models.Game>>(games);
}, TimeSpan.FromHours(1));
@ -96,22 +97,34 @@ namespace LANCommander.Server.Controllers.Api
public async Task<IActionResult> Download(Guid id)
{
if (!Settings.Archives.AllowInsecureDownloads && (User == null || User.Identity == null || !User.Identity.IsAuthenticated))
{
Logger?.LogError("User is not authorized to download game with ID {GameId}", id);
return Unauthorized();
}
var game = await GameService.Get(id);
if (game == null)
{
Logger?.LogError("Game not found with ID {GameId}", id);
return NotFound();
}
if (game.Archives == null || game.Archives.Count == 0)
{
Logger?.LogError("No archives found for game with ID {GameId}", id);
return NotFound();
}
var archive = game.Archives.OrderByDescending(a => a.CreatedOn).First();
var filename = Path.Combine(Settings.Archives.StoragePath, archive.ObjectKey);
if (!System.IO.File.Exists(filename))
{
Logger?.LogError("No archive file exists for game with ID {GameId} at the expected path {FileName}", id, filename);
return NotFound();
}
return File(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read), "application/octet-stream", $"{game.Title.SanitizeFilename()}.zip");
}
@ -128,6 +141,7 @@ namespace LANCommander.Server.Controllers.Api
}
catch (Exception ex)
{
Logger?.LogError(ex, "Could not import game from upload");
return BadRequest(ex.Message);
}
}

View file

@ -70,7 +70,7 @@ namespace LANCommander.Server.Controllers.Api
var user = await UserManager.FindByNameAsync(User.Identity.Name);
if (user == null)
return BadRequest();
return Unauthorized();
var sessions = await PlaySessionService.Get(ps => ps.UserId == user.Id).ToListAsync();
@ -83,7 +83,7 @@ namespace LANCommander.Server.Controllers.Api
var user = await UserManager.FindByNameAsync(User.Identity.Name);
if (user == null)
return BadRequest();
return Unauthorized();
var sessions = await PlaySessionService.Get(ps => ps.UserId == user.Id && ps.GameId == id).ToListAsync();