Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't throw for missing tournament id in database #99

Merged
merged 1 commit into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions League/Controllers/AbstractController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ protected JsonResult JsonResponseRedirect(string? redirectUrl)
/// <returns>Gets the <see cref="System.Security.Claims.ClaimTypes.NameIdentifier"/> of the current user
/// as <see langword="long"/> integer.</returns>
[NonAction]
protected long GetCurrentUserId()
protected long? GetCurrentUserId()
{
return long.Parse(User.Claims.First(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier).Value);
var userId = User.Claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
return long.TryParse(userId, out var id) ? id : null;
}

/// <summary>
Expand Down
27 changes: 21 additions & 6 deletions League/Controllers/Match.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,12 @@ public IActionResult Index()
[HttpGet("[action]")]
public async Task<IActionResult> Fixtures(CancellationToken cancellationToken)
{
var tournament = await GetPlanTournament(cancellationToken);
if (tournament == null) return NotFound();

var model = new FixturesViewModel(_timeZoneConverter)
{
Tournament = await GetPlanTournament(cancellationToken),
Tournament = tournament,
PlannedMatches = await _appDb.MatchRepository.GetPlannedMatchesAsync(
new PredicateExpression(PlannedMatchFields.TournamentId == _tenantContext.TournamentContext.MatchPlanTournamentId), cancellationToken),
// try to use the browser cookie
Expand Down Expand Up @@ -203,11 +206,12 @@ public async Task<IActionResult> PublicCalendar(long? team, long? round, Cancell
[HttpGet("[action]")]
public async Task<IActionResult> Results(CancellationToken cancellationToken)
{
var tournament = await GetResultTournament(cancellationToken);
if (tournament == null) return NotFound();

var model = new ResultsViewModel(_timeZoneConverter)
{
Tournament =
await _appDb.TournamentRepository.GetTournamentAsync(new PredicateExpression(TournamentFields.Id == _tenantContext.TournamentContext.MatchResultTournamentId),
cancellationToken),
Tournament = tournament,
CompletedMatches = await _appDb.MatchRepository.GetCompletedMatchesAsync(
new PredicateExpression(CompletedMatchFields.TournamentId == _tenantContext.TournamentContext.MatchResultTournamentId), cancellationToken),
// try to use the browser cookie
Expand Down Expand Up @@ -565,6 +569,17 @@ private static MatchEntity FillMatchEntity(PlannedMatchRow currentData)
return null;
}

private async Task<TournamentEntity?> GetResultTournament(CancellationToken cancellationToken)
{
var tournament =
await _appDb.TournamentRepository.GetTournamentAsync(new PredicateExpression(TournamentFields.Id == _tenantContext.TournamentContext.MatchResultTournamentId), cancellationToken);

if (tournament != null) return tournament;

_logger.LogCritical("{name} '{id}' does not exist. User ID '{currentUser}'.", nameof(_tenantContext.TournamentContext.MatchResultTournamentId), _tenantContext.TournamentContext.MatchPlanTournamentId, GetCurrentUserId());
return null;
}

private async Task<EnterResultViewModel> GetEnterResultViewModel(MatchEntity match, CancellationToken cancellationToken)
{
match.Sets.RemovedEntitiesTracker = new EntityCollection<SetEntity>();
Expand Down Expand Up @@ -646,7 +661,7 @@ private void SendFixtureNotification(long matchId)
Parameters =
{
CultureInfo = CultureInfo.DefaultThreadCurrentUICulture ?? CultureInfo.CurrentCulture,
ChangedByUserId = GetCurrentUserId(),
ChangedByUserId = GetCurrentUserId() ?? throw new InvalidOperationException("Current user ID must not be null"),
MatchId = matchId,
}
});
Expand All @@ -663,7 +678,7 @@ private void SendResultNotification(in MatchEntity match)
Parameters =
{
CultureInfo = CultureInfo.DefaultThreadCurrentUICulture ?? CultureInfo.CurrentCulture,
ChangedByUserId = GetCurrentUserId(),
ChangedByUserId = GetCurrentUserId() ?? throw new InvalidOperationException("Current user ID must not be null"),
Match = match,
}
});
Expand Down
5 changes: 3 additions & 2 deletions League/Controllers/Ranking.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,16 @@ await _appDb.TournamentRepository.GetTournamentAsync(new PredicateExpression(Tou

if (model.Tournament == null)
{
throw new Exception($"{nameof(_tenantContext.TournamentContext.MatchResultTournamentId)} '{_tenantContext.TournamentContext.MatchResultTournamentId}' does not exist");
_logger.LogCritical("{name} '{id}' does not exist. User ID '{currentUser}'.", nameof(_tenantContext.TournamentContext.MatchPlanTournamentId), _tenantContext.TournamentContext.MatchResultTournamentId, GetCurrentUserId());
return NotFound();
}

return View(Views.ViewNames.Ranking.Table, model);
}
catch (Exception e)
{
_logger.LogCritical(e, "Error when creating the ranking table");
throw;
return NotFound();
}
}

Expand Down
13 changes: 4 additions & 9 deletions League/Controllers/TeamApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ public async Task<IActionResult> Confirm(bool done, CancellationToken cancellati
TeamId = teamInRoundEntity.TeamId,
IsNewApplication = isNewApplication,
RoundId = teamInRoundEntity.RoundId,
RegisteredByUserId = GetCurrentUserId(),
RegisteredByUserId = GetCurrentUserId() ?? throw new InvalidOperationException("Current user ID must not be null"),
UrlToEditApplication = TenantLink.ActionLink(nameof(EditTeam), nameof(TeamApplication), new { teamId = teamInRoundEntity.TeamId }, scheme: Request.Scheme, host: Request.Host) ?? string.Empty
}
});
Expand Down Expand Up @@ -697,19 +697,14 @@ private async Task<ApplicationSessionModel> GetNewSessionModel(CancellationToken
var previousTournament = await _appDb.TournamentRepository.GetTournamentAsync(
new PredicateExpression(TournamentFields.NextTournamentId == _tenantContext.TournamentContext.ApplicationTournamentId),
cancellationToken);
if (previousTournament == null)
{
_logger.LogCritical("No tournament found for ID '{ApplicationTournamentId}'", _tenantContext.TournamentContext.ApplicationTournamentId);
throw new InvalidOperationException($"No tournament found for ID '{_tenantContext.TournamentContext.ApplicationTournamentId}'");
}

return new ApplicationSessionModel
{
TeamInRound = new League.Models.TeamViewModels.TeamInRoundModel {IsNew = true},
Team = new TeamEditorComponentModel {HtmlFieldPrefix = nameof(ApplicationSessionModel.Team), IsNew = true},
Venue = new VenueEditorComponentModel {HtmlFieldPrefix = nameof(ApplicationSessionModel.Venue), IsNew = true},
TournamentName = teamApplicationTournament.Name,
PreviousTournamentId = previousTournament.Id
PreviousTournamentId = previousTournament?.Id
};
}

Expand Down Expand Up @@ -741,7 +736,7 @@ private async Task AddManagerToTeamEntity(TeamEntity teamEntity, CancellationTok
{
var mot = teamEntity.ManagerOfTeams.AddNew();
mot.Team = teamEntity;
mot.UserId = GetCurrentUserId();
mot.UserId = GetCurrentUserId() ?? throw new InvalidOperationException("Current user ID must not be null");
}
else
{
Expand All @@ -752,7 +747,7 @@ private async Task AddManagerToTeamEntity(TeamEntity teamEntity, CancellationTok
{
mot = teamEntity.ManagerOfTeams.AddNew();
mot.TeamId = teamEntity.Id;
mot.UserId = GetCurrentUserId();
mot.UserId = GetCurrentUserId() ?? throw new InvalidOperationException("Current user ID must not be null");
}
}
}
Expand Down