1
0
mirror of https://github.com/bitwarden/server.git synced 2025-04-23 22:15:10 -05:00
Andreas Coroiu 354caa3063
[EC-647] OAVR v2 Feature Branch Merge (#2588)
* [EC-19] Move SSO Identifier to Org SSO endpoint (#2184)

* [EC-19] Move SSO identifier to Org SSO config endpoint

* [EC-19] Add Jira tech debt issue reference

* [EC-542] Update email communications (#2348)

* [EC-73] Add users alongside groups for collection details (#2358)

* [EC-73] feat: add new stored procedures

* [EC-73] feat: add migration

* [EC-73] chore: rename collection group details

* [EC-73] fix: migration

* [EC-73] feat: return users from dapper repo

* [EC-73] feat: EF support for collection users

* [EC-73] feat: implement updating users in EF

* [EC-73] feat: new collections with users in EF

* [EC-73] feat: create with users in dapper

* [EC-73] feat: update with users in dapper

* [EC-73] fix: collection service tests

* [EC-73] fix: lint

* [EC-73] feat: add new data model and rename for clarity

* [EC-73] chore: add future migrations

* [EC-16 / EC-86] Implement Groups Table Endpoints (#2280)

* [EC-16] Update Group endpoints/repositories to include necessary collection info

* [EC-16] Add delete many groups endpoint and command

* [EC-16] Add DeleteGroupCommand unit tests

* [EC-16] Update migration script

* [EC-16] Formatting

* [EC-16] Support modifying users via Post Group endpoint

- Add optional Users property to GroupRequestModel
- Add users parameter to the GroupService.SaveAsync() method
- Use the users argument to update the Group via the GroupRepository if present.

* [EC-16] Add/update Sprocs for bulk group deletion

- Add a new bump account revision date by multiple org ids sproc to be used by the delete many group sproc.
- Update the delete many group sproc to no longer require the organization Id as authorization is a business concern.

* [EC-16] No longer require org Id in delete many GroupRepository

The group repository should not care about which organization a group belongs to when being deleted. That is a business logic concern and is not necessary at the repository level.

* [EC-16] Remove org Id from delete many group command

- Remove the organization Id from the delete many method.
- Require Group entities instead of just group Ids so that group retrieval is completed outside the command.
- No longer return deleted groups as they are now being passed into the command.
- Update unit tests

* [EC-16] Remove org id from bulk delete group endpoint

- Remove the Org Id from the endpoint and make use of the updated delete many command

* [EC-16] Rename delete many groups sproc

* [EC-16] Update migration script

* [EC-16] Fix typo in migration script

* [EC-16] Fix order of operations in Group_DeleteByIds sproc

* [EC-16] Formatting

* [EC-86] Fix DeleteManyAsync parameter name

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* [EC-16] Add missing sproc to sqlproj file

* [EC-16] Improve GroupRepository method performance

Use GroupBy before marrying Groups and Collections to avoid iterating over all collections for every group)

* [EC-16] Use ToListAsync() to be consistent in the repository

* [EC-16] Fix collection grouping in the EF repository

* [EC-16] Adjust DeleteGroup command namespace to be less verbose

* [EC-16] Cleanup DeleteGroupCommandTests

* [EC-16] Formatting

* [EC-16] Ensure a non-null group collection list is provided

* [EC-16] Add bulk GroupEvents method to EventService

- Use the new method in the DeleteGroups command

* [EC-16] Remove bulk delete group Api response

The response is unnecessary and not used by the client

* [EC-16] Log OrganizationUser_UpdateGroups event in GroupService

Events are logged for users during both Group creation (all added users) and modification (only changed users).

* [EC-16] Fix failing unit test

* [EC-16] Rename newUsers variable per feedback

* [EC-16] Assert delete many group log events

Explicitly check for the event type and groups that are logged to the event service.

* [EC-16] Update DeleteManyAsync signature

Use ICollection<> instead of IEnumerable<> to avoid ambiguity of possible multiple enumeration

* [EC-16] Increment migration script name

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>

* Add missing GO command to EC-73 migration script (#2433)

* [EC-15] Members Grid Api Support (#2485)

* [EC-15] Update OrganizationUser models to support list of collections and groups

* [EC-15] Add sprocs to query GroupUser and CollectionUser entities

* [EC-15] Update the OrganizationUserRepository to optionally fetch groups/collections

* [EC-15] Formatting

* [EC-15] Remove leftover repository method

* [EC-15] Fix table identifier inconsistency in sproc/migration

* Formatting

* [EC-14]: Server changes for Collection rows in Vault (#2360)

* [EC-14] add collection management methods to repo
- delete many, get many by ids, and get many with groups by org

* [EC-14] connection command tests had wrong folder name

* [EC-14] add collection repo methods to interface

* [EC-14] create DeleteCollectionCommand

* [EC-14] add getManyWithDetails collections endpoint

* [EC-14] add GetManyWithGroupsByUserId

* [EC-14] add call to interface

* [EC-14] add GetOrganizationCollectionsWIthGroups
- gets groups with collections
- add tests as well

* [EC-14] add call to interface

* [EC-14] add new coll call to controller
- gets collections with groups

* [EC-14] use new delete collection command

* [EC-14] add CollectionBulkDeleteRequestModel

* [EC-14] remove org from delete collection cmd
- move all permission checks to controller
- add tests to controller
- remove org check from repository method

* [EC-14] add migration and sprocs

* [EC-14] formatting

* [EC-14] revert delete permission check changes

* [EC-14] rename SelectionReadOnly to CollectionAccessSelection

* [EC-14] move GetOrganizationCollectionsWithGroups to controller
- there's no reason to have this logic in the service layer
- we can still test the permission check in the controller
- also renamed repo methods and changed return types

* [EC-14] include users in collection access details

* [EC-14] fix migration names

* [EC-14] bumpAccountRevisionDate when deleting collections

* [EC-14] new line in collection service

* [EC-14] formatting and add .sql to proc file

* [EC-14] more formatting

* [EC-14] formatting

* [EC-14] fix whitespace

* [EC-14] add datetime to event log of single delete

* [EC-14] remove ToList() from enumerables not returned

* [EC-14] fix permissions on "Create new collection"
- a custom user with "Create new collections" should see all collections

* [EC-14] add bulk events for collections

* [EC-14] group collections from db before iterating

* [EC-14] sql formatting and missing GO

* [EC-14] fix tests

* [EC-14] add null handling to repo methods

* [EC-14] fix account revision call

* [EC-14] formatting

* [EC-548] Member Details Group Tab (#2508)

* [EC-548] Update models to support groups

* [EC-548] Include groups in invite and save organization user methods

* [EC-548] Pass groups to service methods in member/user controllers

* [EC-548] Fix failing tests

* [EC-548] Add option to include groups for GET org user query

* Formatting

* [EC-887] Server fix for managers seeing options to edit/delete Collections they aren't assigned to (#2542)

* [EC-887] Add Assigned property to CollectionResponseModel

A new property to determine if a collection is assigned to the acting user; as some users, have the view all collections permission, but cannot see every collection's items

* [EC-887] Update logic for retrieving GET all collection details

- Only need to check the ViewAllCollections permission
- Calculate new Assigned response property based on the assignedOrgCollections list

* Formatting

* [EC-887] Update unit tests

Co-authored-by: Shane Melton <smelton@bitwarden.com>
Co-authored-by: Jacob Fink <jfink@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
2023-01-19 11:00:54 -05:00

549 lines
24 KiB
C#

using AutoMapper;
using Bit.Core.Models.Data;
using Bit.Core.Repositories;
using Bit.Infrastructure.EntityFramework.Models;
using Bit.Infrastructure.EntityFramework.Repositories.Queries;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace Bit.Infrastructure.EntityFramework.Repositories;
public class CollectionRepository : Repository<Core.Entities.Collection, Collection, Guid>, ICollectionRepository
{
public CollectionRepository(IServiceScopeFactory serviceScopeFactory, IMapper mapper)
: base(serviceScopeFactory, mapper, (DatabaseContext context) => context.Collections)
{ }
public override async Task<Core.Entities.Collection> CreateAsync(Core.Entities.Collection collection)
{
await base.CreateAsync(collection);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
await dbContext.UserBumpAccountRevisionDateByCollectionIdAsync(collection.Id, collection.OrganizationId);
await dbContext.SaveChangesAsync();
}
return collection;
}
public override async Task DeleteAsync(Core.Entities.Collection collection)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
await dbContext.UserBumpAccountRevisionDateByCollectionIdAsync(collection.Id, collection.OrganizationId);
await dbContext.SaveChangesAsync();
}
await base.DeleteAsync(collection);
}
public override async Task UpsertAsync(Core.Entities.Collection collection)
{
await base.UpsertAsync(collection);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
await dbContext.UserBumpAccountRevisionDateByCollectionIdAsync(collection.Id, collection.OrganizationId);
await dbContext.SaveChangesAsync();
}
}
public async Task CreateAsync(Core.Entities.Collection obj, IEnumerable<CollectionAccessSelection> groups, IEnumerable<CollectionAccessSelection> users)
{
await CreateAsync(obj);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
if (groups != null)
{
var availableGroups = await (from g in dbContext.Groups
where g.OrganizationId == obj.OrganizationId
select g.Id).ToListAsync();
var collectionGroups = groups
.Where(g => availableGroups.Contains(g.Id))
.Select(g => new CollectionGroup
{
CollectionId = obj.Id,
GroupId = g.Id,
ReadOnly = g.ReadOnly,
HidePasswords = g.HidePasswords,
});
await dbContext.AddRangeAsync(collectionGroups);
}
if (users != null)
{
var availableUsers = await (from g in dbContext.OrganizationUsers
where g.OrganizationId == obj.OrganizationId
select g.Id).ToListAsync();
var collectionUsers = users
.Where(u => availableUsers.Contains(u.Id))
.Select(u => new CollectionUser
{
CollectionId = obj.Id,
OrganizationUserId = u.Id,
ReadOnly = u.ReadOnly,
HidePasswords = u.HidePasswords,
});
await dbContext.AddRangeAsync(collectionUsers);
}
await dbContext.UserBumpAccountRevisionDateByOrganizationIdAsync(obj.OrganizationId);
await dbContext.SaveChangesAsync();
}
}
public async Task DeleteUserAsync(Guid collectionId, Guid organizationUserId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = from cu in dbContext.CollectionUsers
where cu.CollectionId == collectionId &&
cu.OrganizationUserId == organizationUserId
select cu;
dbContext.RemoveRange(await query.ToListAsync());
await dbContext.UserBumpAccountRevisionDateByOrganizationUserIdAsync(organizationUserId);
await dbContext.SaveChangesAsync();
}
}
public async Task<CollectionDetails> GetByIdAsync(Guid id, Guid userId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
return (await GetManyByUserIdAsync(userId)).FirstOrDefault(c => c.Id == id);
}
}
public async Task<Tuple<Core.Entities.Collection, CollectionAccessDetails>> GetByIdWithAccessAsync(Guid id)
{
var collection = await base.GetByIdAsync(id);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var groupQuery = from cg in dbContext.CollectionGroups
where cg.CollectionId.Equals(id)
select new CollectionAccessSelection
{
Id = cg.GroupId,
ReadOnly = cg.ReadOnly,
HidePasswords = cg.HidePasswords,
};
var groups = await groupQuery.ToArrayAsync();
var userQuery = from cg in dbContext.CollectionUsers
where cg.CollectionId.Equals(id)
select new CollectionAccessSelection
{
Id = cg.OrganizationUserId,
ReadOnly = cg.ReadOnly,
HidePasswords = cg.HidePasswords,
};
var users = await userQuery.ToArrayAsync();
var access = new CollectionAccessDetails { Users = users, Groups = groups };
return new Tuple<Core.Entities.Collection, CollectionAccessDetails>(collection, access);
}
}
public async Task<Tuple<CollectionDetails, CollectionAccessDetails>> GetByIdWithAccessAsync(Guid id, Guid userId)
{
var collection = await GetByIdAsync(id, userId);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var groupQuery = from cg in dbContext.CollectionGroups
where cg.CollectionId.Equals(id)
select new CollectionAccessSelection
{
Id = cg.GroupId,
ReadOnly = cg.ReadOnly,
HidePasswords = cg.HidePasswords,
};
var groups = await groupQuery.ToArrayAsync();
var userQuery = from cg in dbContext.CollectionUsers
where cg.CollectionId.Equals(id)
select new CollectionAccessSelection
{
Id = cg.OrganizationUserId,
ReadOnly = cg.ReadOnly,
HidePasswords = cg.HidePasswords,
};
var users = await userQuery.ToArrayAsync();
var access = new CollectionAccessDetails { Users = users, Groups = groups };
return new Tuple<CollectionDetails, CollectionAccessDetails>(collection, access);
}
}
public async Task<ICollection<Tuple<Core.Entities.Collection, CollectionAccessDetails>>> GetManyByOrganizationIdWithAccessAsync(Guid organizationId)
{
var collections = await GetManyByOrganizationIdAsync(organizationId);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var groups =
from cg in dbContext.CollectionGroups
where cg.Collection.OrganizationId == organizationId
group cg by cg.CollectionId into g
select g;
var users =
from cu in dbContext.CollectionUsers
where cu.Collection.OrganizationId == organizationId
group cu by cu.CollectionId into u
select u;
return collections.Select(collection =>
new Tuple<Core.Entities.Collection, CollectionAccessDetails>(
collection,
new CollectionAccessDetails
{
Groups = groups
.FirstOrDefault(g => g.Key == collection.Id)?
.Select(g => new CollectionAccessSelection
{
Id = g.GroupId,
HidePasswords = g.HidePasswords,
ReadOnly = g.ReadOnly
}).ToList() ?? new List<CollectionAccessSelection>(),
Users = users
.FirstOrDefault(u => u.Key == collection.Id)?
.Select(c => new CollectionAccessSelection
{
Id = c.OrganizationUserId,
HidePasswords = c.HidePasswords,
ReadOnly = c.ReadOnly
}).ToList() ?? new List<CollectionAccessSelection>()
}
)
).ToList();
}
}
public async Task<ICollection<Tuple<Core.Entities.Collection, CollectionAccessDetails>>> GetManyByUserIdWithAccessAsync(Guid userId, Guid organizationId)
{
var collections = (await GetManyByUserIdAsync(userId)).Where(c => c.OrganizationId == organizationId).ToList();
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var groups =
from cg in dbContext.CollectionGroups
where cg.Collection.OrganizationId == organizationId
&& collections.Select(c => c.Id).Contains(cg.Collection.Id)
group cg by cg.CollectionId into g
select g;
var users =
from cu in dbContext.CollectionUsers
where cu.Collection.OrganizationId == organizationId
&& collections.Select(c => c.Id).Contains(cu.Collection.Id)
group cu by cu.CollectionId into u
select u;
return collections.Select(collection =>
new Tuple<Core.Entities.Collection, CollectionAccessDetails>(
collection,
new CollectionAccessDetails
{
Groups = groups
.FirstOrDefault(g => g.Key == collection.Id)?
.Select(g => new CollectionAccessSelection
{
Id = g.GroupId,
HidePasswords = g.HidePasswords,
ReadOnly = g.ReadOnly
}).ToList() ?? new List<CollectionAccessSelection>(),
Users = users
.FirstOrDefault(u => u.Key == collection.Id)?
.Select(c => new CollectionAccessSelection
{
Id = c.OrganizationUserId,
HidePasswords = c.HidePasswords,
ReadOnly = c.ReadOnly
}).ToList() ?? new List<CollectionAccessSelection>()
}
)
).ToList();
}
}
public async Task<ICollection<Core.Entities.Collection>> GetManyByManyIdsAsync(IEnumerable<Guid> collectionIds)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = from c in dbContext.Collections
where collectionIds.Contains(c.Id)
select c;
var data = await query.ToArrayAsync();
return data;
}
}
public async Task<int> GetCountByOrganizationIdAsync(Guid organizationId)
{
var query = new CollectionReadCountByOrganizationIdQuery(organizationId);
return await GetCountFromQuery(query);
}
public async Task<ICollection<Core.Entities.Collection>> GetManyByOrganizationIdAsync(Guid organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = from c in dbContext.Collections
where c.OrganizationId == organizationId
select c;
var collections = await query.ToArrayAsync();
return collections;
}
}
public async Task<ICollection<CollectionDetails>> GetManyByUserIdAsync(Guid userId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
return await (from c in new UserCollectionDetailsQuery(userId).Run(dbContext)
group c by new { c.Id, c.OrganizationId, c.Name, c.CreationDate, c.RevisionDate, c.ExternalId } into collectionGroup
select new CollectionDetails
{
Id = collectionGroup.Key.Id,
OrganizationId = collectionGroup.Key.OrganizationId,
Name = collectionGroup.Key.Name,
CreationDate = collectionGroup.Key.CreationDate,
RevisionDate = collectionGroup.Key.RevisionDate,
ExternalId = collectionGroup.Key.ExternalId,
ReadOnly = Convert.ToBoolean(collectionGroup.Min(c => Convert.ToInt32(c.ReadOnly))),
HidePasswords = Convert.ToBoolean(collectionGroup.Min(c => Convert.ToInt32(c.HidePasswords))),
}).ToListAsync();
}
}
public async Task<ICollection<CollectionAccessSelection>> GetManyUsersByIdAsync(Guid id)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = from cu in dbContext.CollectionUsers
where cu.CollectionId == id
select cu;
var collectionUsers = await query.ToListAsync();
return collectionUsers.Select(cu => new CollectionAccessSelection
{
Id = cu.OrganizationUserId,
ReadOnly = cu.ReadOnly,
HidePasswords = cu.HidePasswords,
}).ToArray();
}
}
public async Task ReplaceAsync(Core.Entities.Collection collection, IEnumerable<CollectionAccessSelection> groups,
IEnumerable<CollectionAccessSelection> users)
{
await UpsertAsync(collection);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
await ReplaceCollectionGroupsAsync(dbContext, collection, groups);
await ReplaceCollectionUsersAsync(dbContext, collection, users);
await dbContext.UserBumpAccountRevisionDateByCollectionIdAsync(collection.Id, collection.OrganizationId);
}
}
public async Task UpdateUsersAsync(Guid id, IEnumerable<CollectionAccessSelection> requestedUsers)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var organizationId = await dbContext.Collections
.Where(c => c.Id == id)
.Select(c => c.OrganizationId)
.FirstOrDefaultAsync();
var existingCollectionUsers = await dbContext.CollectionUsers
.Where(cu => cu.CollectionId == id)
.ToListAsync();
foreach (var requestedUser in requestedUsers)
{
var existingCollectionUser = existingCollectionUsers.FirstOrDefault(cu => cu.OrganizationUserId == requestedUser.Id);
if (existingCollectionUser == null)
{
// This is a brand new entry
dbContext.CollectionUsers.Add(new CollectionUser
{
CollectionId = id,
OrganizationUserId = requestedUser.Id,
HidePasswords = requestedUser.HidePasswords,
ReadOnly = requestedUser.ReadOnly,
});
continue;
}
// It already exists, update it
existingCollectionUser.HidePasswords = requestedUser.HidePasswords;
existingCollectionUser.ReadOnly = requestedUser.ReadOnly;
dbContext.CollectionUsers.Update(existingCollectionUser);
}
// Remove all existing ones that are no longer requested
var requestedUserIds = requestedUsers.Select(u => u.Id);
dbContext.CollectionUsers.RemoveRange(existingCollectionUsers.Where(cu => !requestedUserIds.Contains(cu.OrganizationUserId)));
await dbContext.UserBumpAccountRevisionDateByCollectionIdAsync(id, organizationId);
await dbContext.SaveChangesAsync();
}
}
public async Task DeleteManyAsync(IEnumerable<Guid> collectionIds)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var collectionGroupEntities = await dbContext.CollectionGroups
.Where(cg => collectionIds.Contains(cg.CollectionId))
.ToListAsync();
var collectionEntities = await dbContext.Collections
.Where(c => collectionIds.Contains(c.Id))
.ToListAsync();
dbContext.CollectionGroups.RemoveRange(collectionGroupEntities);
dbContext.Collections.RemoveRange(collectionEntities);
await dbContext.SaveChangesAsync();
foreach (var collection in collectionEntities.GroupBy(g => g.Organization.Id))
{
await dbContext.UserBumpAccountRevisionDateByOrganizationIdAsync(collection.Key);
}
}
}
private async Task ReplaceCollectionGroupsAsync(DatabaseContext dbContext, Core.Entities.Collection collection, IEnumerable<CollectionAccessSelection> groups)
{
var groupsInOrg = dbContext.Groups.Where(g => g.OrganizationId == collection.OrganizationId);
var modifiedGroupEntities = dbContext.Groups.Where(x => groups.Select(x => x.Id).Contains(x.Id));
var target = (from cg in dbContext.CollectionGroups
join g in modifiedGroupEntities
on cg.CollectionId equals collection.Id into s_g
from g in s_g.DefaultIfEmpty()
where g == null || cg.GroupId == g.Id
select new { cg, g }).AsNoTracking();
var source = (from g in modifiedGroupEntities
from cg in dbContext.CollectionGroups
.Where(cg => cg.CollectionId == collection.Id && cg.GroupId == g.Id).DefaultIfEmpty()
select new { cg, g }).AsNoTracking();
var union = await target
.Union(source)
.Where(x =>
x.cg == null ||
((x.g == null || x.g.Id == x.cg.GroupId) &&
(x.cg.CollectionId == collection.Id)))
.AsNoTracking()
.ToListAsync();
var insert = union.Where(x => x.cg == null && groupsInOrg.Any(c => x.g.Id == c.Id))
.Select(x => new CollectionGroup
{
CollectionId = collection.Id,
GroupId = x.g.Id,
ReadOnly = groups.FirstOrDefault(g => g.Id == x.g.Id).ReadOnly,
HidePasswords = groups.FirstOrDefault(g => g.Id == x.g.Id).HidePasswords,
}).ToList();
var update = union
.Where(
x => x.g != null &&
x.cg != null &&
(x.cg.ReadOnly != groups.FirstOrDefault(g => g.Id == x.g.Id).ReadOnly ||
x.cg.HidePasswords != groups.FirstOrDefault(g => g.Id == x.g.Id).HidePasswords)
)
.Select(x => new CollectionGroup
{
CollectionId = collection.Id,
GroupId = x.g.Id,
ReadOnly = groups.FirstOrDefault(g => g.Id == x.g.Id).ReadOnly,
HidePasswords = groups.FirstOrDefault(g => g.Id == x.g.Id).HidePasswords,
});
var delete = union
.Where(
x => x.g == null &&
x.cg.CollectionId == collection.Id
)
.Select(x => new CollectionGroup
{
CollectionId = collection.Id,
GroupId = x.cg.GroupId,
})
.ToList();
await dbContext.AddRangeAsync(insert);
dbContext.UpdateRange(update);
dbContext.RemoveRange(delete);
await dbContext.SaveChangesAsync();
}
private async Task ReplaceCollectionUsersAsync(DatabaseContext dbContext, Core.Entities.Collection collection, IEnumerable<CollectionAccessSelection> users)
{
var usersInOrg = dbContext.OrganizationUsers.Where(u => u.OrganizationId == collection.OrganizationId);
var modifiedUserEntities = dbContext.OrganizationUsers.Where(x => users.Select(x => x.Id).Contains(x.Id));
var target = (from cu in dbContext.CollectionUsers
join u in modifiedUserEntities
on cu.CollectionId equals collection.Id into s_g
from u in s_g.DefaultIfEmpty()
where u == null || cu.OrganizationUserId == u.Id
select new { cu, u }).AsNoTracking();
var source = (from u in modifiedUserEntities
from cu in dbContext.CollectionUsers
.Where(cu => cu.CollectionId == collection.Id && cu.OrganizationUserId == u.Id).DefaultIfEmpty()
select new { cu, u }).AsNoTracking();
var union = await target
.Union(source)
.Where(x =>
x.cu == null ||
((x.u == null || x.u.Id == x.cu.OrganizationUserId) &&
(x.cu.CollectionId == collection.Id)))
.AsNoTracking()
.ToListAsync();
var insert = union.Where(x => x.u == null && usersInOrg.Any(c => x.u.Id == c.Id))
.Select(x => new CollectionUser
{
CollectionId = collection.Id,
OrganizationUserId = x.u.Id,
ReadOnly = users.FirstOrDefault(u => u.Id == x.u.Id).ReadOnly,
HidePasswords = users.FirstOrDefault(u => u.Id == x.u.Id).HidePasswords,
}).ToList();
var update = union
.Where(
x => x.u != null &&
x.cu != null &&
(x.cu.ReadOnly != users.FirstOrDefault(u => u.Id == x.u.Id).ReadOnly ||
x.cu.HidePasswords != users.FirstOrDefault(u => u.Id == x.u.Id).HidePasswords)
)
.Select(x => new CollectionUser
{
CollectionId = collection.Id,
OrganizationUserId = x.u.Id,
ReadOnly = users.FirstOrDefault(u => u.Id == x.u.Id).ReadOnly,
HidePasswords = users.FirstOrDefault(u => u.Id == x.u.Id).HidePasswords,
});
var delete = union
.Where(
x => x.u == null &&
x.cu.CollectionId == collection.Id
)
.Select(x => new CollectionUser
{
CollectionId = collection.Id,
OrganizationUserId = x.cu.OrganizationUserId,
})
.ToList();
await dbContext.AddRangeAsync(insert);
dbContext.UpdateRange(update);
dbContext.RemoveRange(delete);
await dbContext.SaveChangesAsync();
}
}