/// <summary>
/// Retrieves roles assigned to the user within organizations.
/// </summary>
/// <param name="userId">The ID of the user.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The roles assigned to the user within organizations.</returns>
private async Task<Dictionary<Guid, MemberRole>> GetOrganizationRolesAsync(Guid userId,
CancellationToken cancellationToken)
{
// Get all organizations the user is a member of
var userOrganizations = await db.OrganizationMembers
.Where(om => om.UserId == userId)
.Select(om => om.OrganizationId)
.ToListAsync(cancellationToken);
// Get roles in organizations where the user has a role
var organizationRoles = await db.OrganizationMemberRoles
.Where(omr => omr.OrganizationMember.UserId == userId)
.Select(omr => new { omr.OrganizationId, omr.OrganizationRole.Name })
.ToListAsync(cancellationToken);
// Parse roles and add to dictionary
var parsedRoles = organizationRoles.ToDictionary(
omr => omr.OrganizationId,
omr =>
{
if (Enum.TryParse<MemberRole>(omr.Name, true, out var role))
return role;
throw new InvalidCastException();
});
// For organizations where the user doesn't have a role, add with MemberRole.None
foreach (var orgId in userOrganizations) parsedRoles.TryAdd(orgId, MemberRole.None);
return parsedRoles;
}
/// <summary>
/// Retrieves roles assigned to the user within organizations.
/// </summary>
/// <param name="userId">The ID of the user.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The roles assigned to the user within organizations.</returns>
private async Task<Dictionary<Guid, MemberRole>> GetOrganizationRolesAsync(Guid userId,
CancellationToken cancellationToken)
{
// Get all organizations the user is a member of
var userOrganizations = await db.OrganizationMembers
.Where(om => om.UserId == userId)
.Select(om => om.OrganizationId)
.ToListAsync(cancellationToken);
// Get roles in organizations where the user has a role
var organizationRoles = await db.OrganizationMemberRoles
.Where(omr => omr.OrganizationMember.UserId == userId)
.Select(omr => new { omr.OrganizationId, omr.OrganizationRole.Name })
.ToListAsync(cancellationToken);
// Parse roles and add to dictionary
var parsedRoles = organizationRoles.ToDictionary(
omr => omr.OrganizationId,
omr =>
{
if (Enum.TryParse<MemberRole>(omr.Name, true, out var role))
return role;
throw new InvalidCastException();
});
// For organizations where the user doesn't have a role, add with MemberRole.None
foreach (var orgId in userOrganizations) parsedRoles.TryAdd(orgId, MemberRole.None);
return parsedRoles;
}