1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-21 12:05:42 +01:00

[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>
This commit is contained in:
Andreas Coroiu 2023-01-19 17:00:54 +01:00 committed by GitHub
parent 9e75f65a2d
commit 354caa3063
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
97 changed files with 2649 additions and 382 deletions

View File

@ -419,7 +419,7 @@ public class ProviderService : IProviderService
AccessAll = true,
Type = OrganizationUserType.Owner,
Permissions = null,
Collections = Array.Empty<SelectionReadOnly>(),
Collections = Array.Empty<CollectionAccessSelection>(),
},
null
)

View File

@ -80,7 +80,7 @@ public class PostUserCommand : IPostUserCommand
}
var invitedOrgUser = await _organizationService.InviteUserAsync(organizationId, EventSystemUser.SCIM, email,
OrganizationUserType.User, false, externalId, new List<SelectionReadOnly>());
OrganizationUserType.User, false, externalId, new List<CollectionAccessSelection>(), new List<Guid>());
var orgUser = await _organizationUserRepository.GetDetailsByIdAsync(invitedOrgUser.Id);
return orgUser;

View File

@ -34,13 +34,15 @@ public class PostUserCommandTests
.Returns(organizationUsers);
sutProvider.GetDependency<IOrganizationService>()
.InviteUserAsync(organizationId, EventSystemUser.SCIM, scimUserRequestModel.PrimaryEmail.ToLowerInvariant(), OrganizationUserType.User, false, externalId, Arg.Any<List<SelectionReadOnly>>())
.InviteUserAsync(organizationId, EventSystemUser.SCIM, scimUserRequestModel.PrimaryEmail.ToLowerInvariant(),
OrganizationUserType.User, false, externalId, Arg.Any<List<CollectionAccessSelection>>(),
Arg.Any<List<Guid>>())
.Returns(newUser);
var user = await sutProvider.Sut.PostUserAsync(organizationId, scimUserRequestModel);
await sutProvider.GetDependency<IOrganizationService>().Received(1).InviteUserAsync(organizationId, EventSystemUser.SCIM, scimUserRequestModel.PrimaryEmail.ToLowerInvariant(),
OrganizationUserType.User, false, scimUserRequestModel.ExternalId, Arg.Any<List<SelectionReadOnly>>());
OrganizationUserType.User, false, scimUserRequestModel.ExternalId, Arg.Any<List<CollectionAccessSelection>>(), Arg.Any<List<Guid>>());
await sutProvider.GetDependency<IOrganizationUserRepository>().Received(1).GetDetailsByIdAsync(newUser.Id);
}

View File

@ -3,6 +3,7 @@ using Bit.Api.Models.Response;
using Bit.Core.Context;
using Bit.Core.Entities;
using Bit.Core.Exceptions;
using Bit.Core.OrganizationFeatures.OrganizationCollections.Interfaces;
using Bit.Core.Repositories;
using Bit.Core.Services;
using Microsoft.AspNetCore.Authorization;
@ -16,17 +17,20 @@ public class CollectionsController : Controller
{
private readonly ICollectionRepository _collectionRepository;
private readonly ICollectionService _collectionService;
private readonly IDeleteCollectionCommand _deleteCollectionCommand;
private readonly IUserService _userService;
private readonly ICurrentContext _currentContext;
public CollectionsController(
ICollectionRepository collectionRepository,
ICollectionService collectionService,
IDeleteCollectionCommand deleteCollectionCommand,
IUserService userService,
ICurrentContext currentContext)
{
_collectionRepository = collectionRepository;
_collectionService = collectionService;
_deleteCollectionCommand = deleteCollectionCommand;
_userService = userService;
_currentContext = currentContext;
}
@ -44,7 +48,7 @@ public class CollectionsController : Controller
}
[HttpGet("{id}/details")]
public async Task<CollectionGroupDetailsResponseModel> GetDetails(Guid orgId, Guid id)
public async Task<CollectionAccessDetailsResponseModel> GetDetails(Guid orgId, Guid id)
{
if (!await ViewAtLeastOneCollectionAsync(orgId) && !await _currentContext.ManageUsers(orgId))
{
@ -53,25 +57,58 @@ public class CollectionsController : Controller
if (await _currentContext.ViewAllCollections(orgId))
{
var collectionDetails = await _collectionRepository.GetByIdWithGroupsAsync(id);
if (collectionDetails?.Item1 == null || collectionDetails.Item1.OrganizationId != orgId)
(var collection, var access) = await _collectionRepository.GetByIdWithAccessAsync(id);
if (collection == null || collection.OrganizationId != orgId)
{
throw new NotFoundException();
}
return new CollectionGroupDetailsResponseModel(collectionDetails.Item1, collectionDetails.Item2);
return new CollectionAccessDetailsResponseModel(collection, access.Groups, access.Users);
}
else
{
var collectionDetails = await _collectionRepository.GetByIdWithGroupsAsync(id,
(var collection, var access) = await _collectionRepository.GetByIdWithAccessAsync(id,
_currentContext.UserId.Value);
if (collectionDetails?.Item1 == null || collectionDetails.Item1.OrganizationId != orgId)
if (collection == null || collection.OrganizationId != orgId)
{
throw new NotFoundException();
}
return new CollectionGroupDetailsResponseModel(collectionDetails.Item1, collectionDetails.Item2);
return new CollectionAccessDetailsResponseModel(collection, access.Groups, access.Users);
}
}
[HttpGet("details")]
public async Task<ListResponseModel<CollectionAccessDetailsResponseModel>> GetManyWithDetails(Guid orgId)
{
if (!await ViewAtLeastOneCollectionAsync(orgId) && !await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
// We always need to know which collections the current user is assigned to
var assignedOrgCollections = await _collectionRepository.GetManyByUserIdWithAccessAsync(_currentContext.UserId.Value, orgId);
if (await _currentContext.ViewAllCollections(orgId))
{
// The user can view all collections, but they may not always be assigned to all of them
var allOrgCollections = await _collectionRepository.GetManyByOrganizationIdWithAccessAsync(orgId);
return new ListResponseModel<CollectionAccessDetailsResponseModel>(allOrgCollections.Select(c =>
new CollectionAccessDetailsResponseModel(c.Item1, c.Item2.Groups, c.Item2.Users)
{
// Manually determine which collections they're assigned to
Assigned = assignedOrgCollections.Any(ac => ac.Item1.Id == c.Item1.Id)
})
);
}
return new ListResponseModel<CollectionAccessDetailsResponseModel>(assignedOrgCollections.Select(c =>
new CollectionAccessDetailsResponseModel(c.Item1, c.Item2.Groups, c.Item2.Users)
{
Assigned = true // Mapping from assignedOrgCollections implies they're all assigned
})
);
}
[HttpGet("")]
public async Task<ListResponseModel<CollectionResponseModel>> Get(Guid orgId)
{
@ -110,11 +147,13 @@ public class CollectionsController : Controller
throw new NotFoundException();
}
var groups = model.Groups?.Select(g => g.ToSelectionReadOnly());
var users = model.Users?.Select(g => g.ToSelectionReadOnly());
var assignUserToCollection = !(await _currentContext.EditAnyCollection(orgId)) &&
await _currentContext.EditAssignedCollections(orgId);
await _collectionService.SaveAsync(collection, model.Groups?.Select(g => g.ToSelectionReadOnly()),
assignUserToCollection ? _currentContext.UserId : null);
await _collectionService.SaveAsync(collection, groups, users, assignUserToCollection ? _currentContext.UserId : null);
return new CollectionResponseModel(collection);
}
@ -128,8 +167,9 @@ public class CollectionsController : Controller
}
var collection = await GetCollectionAsync(id, orgId);
await _collectionService.SaveAsync(model.ToCollection(collection),
model.Groups?.Select(g => g.ToSelectionReadOnly()));
var groups = model.Groups?.Select(g => g.ToSelectionReadOnly());
var users = model.Users?.Select(g => g.ToSelectionReadOnly());
await _collectionService.SaveAsync(model.ToCollection(collection), groups, users);
return new CollectionResponseModel(collection);
}
@ -155,7 +195,29 @@ public class CollectionsController : Controller
}
var collection = await GetCollectionAsync(id, orgId);
await _collectionService.DeleteAsync(collection);
await _deleteCollectionCommand.DeleteAsync(collection);
}
[HttpDelete("")]
[HttpPost("delete")]
public async Task DeleteMany([FromBody] CollectionBulkDeleteRequestModel model)
{
var orgId = new Guid(model.OrganizationId);
var collectionIds = model.Ids.Select(i => new Guid(i));
if (!await _currentContext.DeleteAssignedCollections(orgId))
{
throw new NotFoundException();
}
var userCollections = await _collectionRepository.GetManyByUserIdAsync(_currentContext.UserId.Value);
var filteredCollections = userCollections.Where(c => collectionIds.Contains(c.Id) && c.OrganizationId == orgId);
if (!filteredCollections.Any())
{
throw new BadRequestException("No collections found.");
}
await _deleteCollectionCommand.DeleteManyAsync(filteredCollections);
}
[HttpDelete("{id}/user/{orgUserId}")]

View File

@ -16,6 +16,7 @@ public class GroupsController : Controller
{
private readonly IGroupRepository _groupRepository;
private readonly IGroupService _groupService;
private readonly IDeleteGroupCommand _deleteGroupCommand;
private readonly IOrganizationRepository _organizationRepository;
private readonly ICurrentContext _currentContext;
private readonly ICreateGroupCommand _createGroupCommand;
@ -27,7 +28,8 @@ public class GroupsController : Controller
IOrganizationRepository organizationRepository,
ICurrentContext currentContext,
ICreateGroupCommand createGroupCommand,
IUpdateGroupCommand updateGroupCommand)
IUpdateGroupCommand updateGroupCommand,
IDeleteGroupCommand deleteGroupCommand)
{
_groupRepository = groupRepository;
_groupService = groupService;
@ -35,6 +37,7 @@ public class GroupsController : Controller
_currentContext = currentContext;
_createGroupCommand = createGroupCommand;
_updateGroupCommand = updateGroupCommand;
_deleteGroupCommand = deleteGroupCommand;
}
[HttpGet("{id}")]
@ -62,7 +65,7 @@ public class GroupsController : Controller
}
[HttpGet("")]
public async Task<ListResponseModel<GroupResponseModel>> Get(string orgId)
public async Task<ListResponseModel<GroupDetailsResponseModel>> Get(string orgId)
{
var orgIdGuid = new Guid(orgId);
var canAccess = await _currentContext.ManageGroups(orgIdGuid) ||
@ -75,9 +78,9 @@ public class GroupsController : Controller
throw new NotFoundException();
}
var groups = await _groupRepository.GetManyByOrganizationIdAsync(orgIdGuid);
var responses = groups.Select(g => new GroupResponseModel(g));
return new ListResponseModel<GroupResponseModel>(responses);
var groups = await _groupRepository.GetManyWithCollectionsByOrganizationIdAsync(orgIdGuid);
var responses = groups.Select(g => new GroupDetailsResponseModel(g.Item1, g.Item2));
return new ListResponseModel<GroupDetailsResponseModel>(responses);
}
[HttpGet("{id}/users")]
@ -105,7 +108,7 @@ public class GroupsController : Controller
var organization = await _organizationRepository.GetByIdAsync(orgIdGuid);
var group = model.ToGroup(orgIdGuid);
await _createGroupCommand.CreateGroupAsync(group, organization, model.Collections?.Select(c => c.ToSelectionReadOnly()));
await _createGroupCommand.CreateGroupAsync(group, organization, model.Collections?.Select(c => c.ToSelectionReadOnly()), model.Users);
return new GroupResponseModel(group);
}
@ -123,7 +126,7 @@ public class GroupsController : Controller
var orgIdGuid = new Guid(orgId);
var organization = await _organizationRepository.GetByIdAsync(orgIdGuid);
await _updateGroupCommand.UpdateGroupAsync(model.ToGroup(group), organization, model.Collections?.Select(c => c.ToSelectionReadOnly()));
await _updateGroupCommand.UpdateGroupAsync(model.ToGroup(group), organization, model.Collections?.Select(c => c.ToSelectionReadOnly()), model.Users);
return new GroupResponseModel(group);
}
@ -148,7 +151,24 @@ public class GroupsController : Controller
throw new NotFoundException();
}
await _groupService.DeleteAsync(group);
await _deleteGroupCommand.DeleteAsync(group);
}
[HttpDelete("")]
[HttpPost("delete")]
public async Task BulkDelete([FromBody] GroupBulkRequestModel model)
{
var groups = await _groupRepository.GetManyByManyIds(model.Ids);
foreach (var group in groups)
{
if (!await _currentContext.ManageGroups(group.OrganizationId))
{
throw new NotFoundException();
}
}
await _deleteGroupCommand.DeleteManyAsync(groups);
}
[HttpDelete("{id}/user/{orgUserId}")]

View File

@ -49,7 +49,7 @@ public class OrganizationUsersController : Controller
}
[HttpGet("{id}")]
public async Task<OrganizationUserDetailsResponseModel> Get(string orgId, string id)
public async Task<OrganizationUserDetailsResponseModel> Get(string id, bool includeGroups = false)
{
var organizationUser = await _organizationUserRepository.GetByIdWithCollectionsAsync(new Guid(id));
if (organizationUser == null || !await _currentContext.ManageUsers(organizationUser.Item1.OrganizationId))
@ -57,11 +57,18 @@ public class OrganizationUsersController : Controller
throw new NotFoundException();
}
return new OrganizationUserDetailsResponseModel(organizationUser.Item1, organizationUser.Item2);
var response = new OrganizationUserDetailsResponseModel(organizationUser.Item1, organizationUser.Item2);
if (includeGroups)
{
response.Groups = await _groupRepository.GetManyIdsByUserIdAsync(organizationUser.Item1.Id);
}
return response;
}
[HttpGet("")]
public async Task<ListResponseModel<OrganizationUserUserDetailsResponseModel>> Get(string orgId)
public async Task<ListResponseModel<OrganizationUserUserDetailsResponseModel>> Get(string orgId, bool includeGroups = false, bool includeCollections = false)
{
var orgGuidId = new Guid(orgId);
if (!await _currentContext.ViewAllCollections(orgGuidId) &&
@ -72,7 +79,7 @@ public class OrganizationUsersController : Controller
throw new NotFoundException();
}
var organizationUsers = await _organizationUserRepository.GetManyDetailsByOrganizationAsync(orgGuidId);
var organizationUsers = await _organizationUserRepository.GetManyDetailsByOrganizationAsync(orgGuidId, includeGroups, includeCollections);
var responseTasks = organizationUsers.Select(async o => new OrganizationUserUserDetailsResponseModel(o,
await _userService.TwoFactorIsEnabledAsync(o)));
var responses = await Task.WhenAll(responseTasks);
@ -262,7 +269,7 @@ public class OrganizationUsersController : Controller
var userId = _userService.GetProperUserId(User);
await _organizationService.SaveUserAsync(model.ToOrganizationUser(organizationUser), userId.Value,
model.Collections?.Select(c => c.ToSelectionReadOnly()));
model.Collections?.Select(c => c.ToSelectionReadOnly()), model.Groups);
}
[HttpPut("{id}/groups")]

View File

@ -4,9 +4,9 @@ namespace Bit.Api.Models.Public.Request;
public class AssociationWithPermissionsRequestModel : AssociationWithPermissionsBaseModel
{
public SelectionReadOnly ToSelectionReadOnly()
public CollectionAccessSelection ToSelectionReadOnly()
{
return new SelectionReadOnly
return new CollectionAccessSelection
{
Id = Id.Value,
ReadOnly = ReadOnly.Value

View File

@ -9,6 +9,11 @@ public class MemberUpdateRequestModel : MemberBaseModel
/// </summary>
public IEnumerable<AssociationWithPermissionsRequestModel> Collections { get; set; }
/// <summary>
/// Ids of the associated groups that this member will belong to
/// </summary>
public IEnumerable<Guid> Groups { get; set; }
public virtual OrganizationUser ToOrganizationUser(OrganizationUser existingUser)
{
existingUser.Type = Type.Value;

View File

@ -4,7 +4,7 @@ namespace Bit.Api.Models.Public.Response;
public class AssociationWithPermissionsResponseModel : AssociationWithPermissionsBaseModel
{
public AssociationWithPermissionsResponseModel(SelectionReadOnly selection)
public AssociationWithPermissionsResponseModel(CollectionAccessSelection selection)
{
if (selection == null)
{

View File

@ -9,7 +9,7 @@ namespace Bit.Api.Models.Public.Response;
/// </summary>
public class CollectionResponseModel : CollectionBaseModel, IResponseModel
{
public CollectionResponseModel(Collection collection, IEnumerable<SelectionReadOnly> groups)
public CollectionResponseModel(Collection collection, IEnumerable<CollectionAccessSelection> groups)
{
if (collection == null)
{

View File

@ -9,7 +9,7 @@ namespace Bit.Api.Models.Public.Response;
/// </summary>
public class GroupResponseModel : GroupBaseModel, IResponseModel
{
public GroupResponseModel(Group group, IEnumerable<SelectionReadOnly> collections)
public GroupResponseModel(Group group, IEnumerable<CollectionAccessSelection> collections)
{
if (group == null)
{

View File

@ -11,7 +11,7 @@ namespace Bit.Api.Models.Public.Response;
/// </summary>
public class MemberResponseModel : MemberBaseModel, IResponseModel
{
public MemberResponseModel(OrganizationUser user, IEnumerable<SelectionReadOnly> collections)
public MemberResponseModel(OrganizationUser user, IEnumerable<CollectionAccessSelection> collections)
: base(user)
{
if (user == null)
@ -27,7 +27,7 @@ public class MemberResponseModel : MemberBaseModel, IResponseModel
}
public MemberResponseModel(OrganizationUserUserDetails user, bool twoFactorEnabled,
IEnumerable<SelectionReadOnly> collections)
IEnumerable<CollectionAccessSelection> collections)
: base(user)
{
if (user == null)

View File

@ -13,6 +13,7 @@ public class CollectionRequestModel
[StringLength(300)]
public string ExternalId { get; set; }
public IEnumerable<SelectionReadOnlyRequestModel> Groups { get; set; }
public IEnumerable<SelectionReadOnlyRequestModel> Users { get; set; }
public Collection ToCollection(Guid orgId)
{
@ -29,3 +30,10 @@ public class CollectionRequestModel
return existingCollection;
}
}
public class CollectionBulkDeleteRequestModel
{
[Required]
public IEnumerable<string> Ids { get; set; }
public string OrganizationId { get; set; }
}

View File

@ -13,6 +13,7 @@ public class GroupRequestModel
[StringLength(300)]
public string ExternalId { get; set; }
public IEnumerable<SelectionReadOnlyRequestModel> Collections { get; set; }
public IEnumerable<Guid> Users { get; set; }
public Group ToGroup(Guid orgId)
{
@ -30,3 +31,9 @@ public class GroupRequestModel
return existingGroup;
}
}
public class GroupBulkRequestModel
{
[Required]
public IEnumerable<Guid> Ids { get; set; }
}

View File

@ -19,6 +19,7 @@ public class OrganizationUserInviteRequestModel
public bool AccessAll { get; set; }
public Permissions Permissions { get; set; }
public IEnumerable<SelectionReadOnlyRequestModel> Collections { get; set; }
public IEnumerable<Guid> Groups { get; set; }
public OrganizationUserInviteData ToData()
{
@ -28,6 +29,7 @@ public class OrganizationUserInviteRequestModel
Type = Type,
AccessAll = AccessAll,
Collections = Collections?.Select(c => c.ToSelectionReadOnly()),
Groups = Groups,
Permissions = Permissions,
};
}
@ -73,6 +75,7 @@ public class OrganizationUserUpdateRequestModel
public bool AccessAll { get; set; }
public Permissions Permissions { get; set; }
public IEnumerable<SelectionReadOnlyRequestModel> Collections { get; set; }
public IEnumerable<Guid> Groups { get; set; }
public OrganizationUser ToOrganizationUser(OrganizationUser existingUser)
{

View File

@ -10,9 +10,9 @@ public class SelectionReadOnlyRequestModel
public bool ReadOnly { get; set; }
public bool HidePasswords { get; set; }
public SelectionReadOnly ToSelectionReadOnly()
public CollectionAccessSelection ToSelectionReadOnly()
{
return new SelectionReadOnly
return new CollectionAccessSelection
{
Id = new Guid(Id),
ReadOnly = ReadOnly,

View File

@ -39,13 +39,20 @@ public class CollectionDetailsResponseModel : CollectionResponseModel
public bool HidePasswords { get; set; }
}
public class CollectionGroupDetailsResponseModel : CollectionResponseModel
public class CollectionAccessDetailsResponseModel : CollectionResponseModel
{
public CollectionGroupDetailsResponseModel(Collection collection, IEnumerable<SelectionReadOnly> groups)
: base(collection, "collectionGroupDetails")
public CollectionAccessDetailsResponseModel(Collection collection, IEnumerable<CollectionAccessSelection> groups, IEnumerable<CollectionAccessSelection> users)
: base(collection, "collectionAccessDetails")
{
Groups = groups.Select(g => new SelectionReadOnlyResponseModel(g));
Users = users.Select(g => new SelectionReadOnlyResponseModel(g));
}
public IEnumerable<SelectionReadOnlyResponseModel> Groups { get; set; }
public IEnumerable<SelectionReadOnlyResponseModel> Users { get; set; }
/// <summary>
/// True if the acting user is explicitly assigned to the collection
/// </summary>
public bool Assigned { get; set; }
}

View File

@ -30,7 +30,7 @@ public class GroupResponseModel : ResponseModel
public class GroupDetailsResponseModel : GroupResponseModel
{
public GroupDetailsResponseModel(Group group, IEnumerable<SelectionReadOnly> collections)
public GroupDetailsResponseModel(Group group, IEnumerable<CollectionAccessSelection> collections)
: base(group, "groupDetails")
{
Collections = collections.Select(c => new SelectionReadOnlyResponseModel(c));

View File

@ -1,4 +1,5 @@
using Bit.Core.Entities;
using System.Text.Json.Serialization;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Models.Api;
using Bit.Core.Models.Data;
@ -57,13 +58,16 @@ public class OrganizationUserResponseModel : ResponseModel
public class OrganizationUserDetailsResponseModel : OrganizationUserResponseModel
{
public OrganizationUserDetailsResponseModel(OrganizationUser organizationUser,
IEnumerable<SelectionReadOnly> collections)
IEnumerable<CollectionAccessSelection> collections)
: base(organizationUser, "organizationUserDetails")
{
Collections = collections.Select(c => new SelectionReadOnlyResponseModel(c));
}
public IEnumerable<SelectionReadOnlyResponseModel> Collections { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public IEnumerable<Guid> Groups { get; set; }
}
public class OrganizationUserUserDetailsResponseModel : OrganizationUserResponseModel
@ -81,6 +85,8 @@ public class OrganizationUserUserDetailsResponseModel : OrganizationUserResponse
Email = organizationUser.Email;
TwoFactorEnabled = twoFactorEnabled;
SsoBound = !string.IsNullOrWhiteSpace(organizationUser.SsoExternalId);
Collections = organizationUser.Collections.Select(c => new SelectionReadOnlyResponseModel(c));
Groups = organizationUser.Groups;
// Prevent reset password when using key connector.
ResetPasswordEnrolled = ResetPasswordEnrolled && !organizationUser.UsesKeyConnector;
}
@ -89,6 +95,8 @@ public class OrganizationUserUserDetailsResponseModel : OrganizationUserResponse
public string Email { get; set; }
public bool TwoFactorEnabled { get; set; }
public bool SsoBound { get; set; }
public IEnumerable<SelectionReadOnlyResponseModel> Collections { get; set; }
public IEnumerable<Guid> Groups { get; set; }
}
public class OrganizationUserResetPasswordDetailsResponseModel : ResponseModel

View File

@ -4,7 +4,7 @@ namespace Bit.Api.Models.Response;
public class SelectionReadOnlyResponseModel
{
public SelectionReadOnlyResponseModel(SelectionReadOnly selection)
public SelectionReadOnlyResponseModel(CollectionAccessSelection selection)
{
if (selection == null)
{

View File

@ -40,13 +40,12 @@ public class CollectionsController : Controller
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get(Guid id)
{
var collectionWithGroups = await _collectionRepository.GetByIdWithGroupsAsync(id);
var collection = collectionWithGroups?.Item1;
(var collection, var access) = await _collectionRepository.GetByIdWithAccessAsync(id);
if (collection == null || collection.OrganizationId != _currentContext.OrganizationId)
{
return new NotFoundResult();
}
var response = new CollectionResponseModel(collection, collectionWithGroups.Item2);
var response = new CollectionResponseModel(collection, access.Groups);
return new JsonResult(response);
}

View File

@ -83,15 +83,14 @@ public class GroupsController : Controller
/// </summary>
/// <remarks>
/// Returns a list of your organization's groups.
/// Group objects listed in this call do not include information about their associated collections.
/// Group objects listed in this call include information about their associated collections.
/// </remarks>
[HttpGet]
[ProducesResponseType(typeof(ListResponseModel<GroupResponseModel>), (int)HttpStatusCode.OK)]
public async Task<IActionResult> List()
{
var groups = await _groupRepository.GetManyByOrganizationIdAsync(_currentContext.OrganizationId.Value);
// TODO: Get all CollectionGroup associations for the organization and marry them up here for the response.
var groupResponses = groups.Select(g => new GroupResponseModel(g, null));
var groups = await _groupRepository.GetManyWithCollectionsByOrganizationIdAsync(_currentContext.OrganizationId.Value);
var groupResponses = groups.Select(g => new GroupResponseModel(g.Item1, g.Item2));
var response = new ListResponseModel<GroupResponseModel>(groupResponses);
return new JsonResult(response);
}

View File

@ -122,7 +122,7 @@ public class MembersController : Controller
Collections = associations
};
var user = await _organizationService.InviteUserAsync(_currentContext.OrganizationId.Value, null,
model.Email, model.Type.Value, model.AccessAll.Value, model.ExternalId, associations);
model.Email, model.Type.Value, model.AccessAll.Value, model.ExternalId, associations, model.Groups);
var response = new MemberResponseModel(user, associations);
return new JsonResult(response);
}
@ -149,7 +149,7 @@ public class MembersController : Controller
}
var updatedUser = model.ToOrganizationUser(existingUser);
var associations = model.Collections?.Select(c => c.ToSelectionReadOnly());
await _organizationService.SaveUserAsync(updatedUser, null, associations);
await _organizationService.SaveUserAsync(updatedUser, null, associations, model.Groups);
MemberResponseModel response = null;
if (existingUser.UserId.HasValue)
{

View File

@ -9,7 +9,8 @@ public class OrganizationUserInvite
public Enums.OrganizationUserType? Type { get; set; }
public bool AccessAll { get; set; }
public Permissions Permissions { get; set; }
public IEnumerable<SelectionReadOnly> Collections { get; set; }
public IEnumerable<CollectionAccessSelection> Collections { get; set; }
public IEnumerable<Guid> Groups { get; set; }
public OrganizationUserInvite() { }
@ -19,6 +20,7 @@ public class OrganizationUserInvite
Type = requestModel.Type;
AccessAll = requestModel.AccessAll;
Collections = requestModel.Collections;
Groups = requestModel.Groups;
Permissions = requestModel.Permissions;
}
}

View File

@ -0,0 +1,8 @@
namespace Bit.Core.Models.Data;
public class CollectionAccessDetails
{
public IEnumerable<CollectionAccessSelection> Groups { get; set; }
public IEnumerable<CollectionAccessSelection> Users { get; set; }
}

View File

@ -1,6 +1,6 @@
namespace Bit.Core.Models.Data;
public class SelectionReadOnly
public class CollectionAccessSelection
{
public Guid Id { get; set; }
public bool ReadOnly { get; set; }

View File

@ -7,6 +7,7 @@ public class OrganizationUserInviteData
public IEnumerable<string> Emails { get; set; }
public OrganizationUserType? Type { get; set; }
public bool AccessAll { get; set; }
public IEnumerable<SelectionReadOnly> Collections { get; set; }
public IEnumerable<CollectionAccessSelection> Collections { get; set; }
public IEnumerable<Guid> Groups { get; set; }
public Permissions Permissions { get; set; }
}

View File

@ -23,6 +23,9 @@ public class OrganizationUserUserDetails : IExternal, ITwoFactorProvidersUser
public string ResetPasswordKey { get; set; }
public bool UsesKeyConnector { get; set; }
public ICollection<Guid> Groups { get; set; } = new List<Guid>();
public ICollection<CollectionAccessSelection> Collections { get; set; } = new List<CollectionAccessSelection>();
public Dictionary<TwoFactorProviderType, TwoFactorProvider> GetTwoFactorProviders()
{
if (string.IsNullOrWhiteSpace(TwoFactorProviders))

View File

@ -13,35 +13,52 @@ public class CreateGroupCommand : ICreateGroupCommand
{
private readonly IEventService _eventService;
private readonly IGroupRepository _groupRepository;
private readonly IOrganizationUserRepository _organizationUserRepository;
private readonly IReferenceEventService _referenceEventService;
public CreateGroupCommand(
IEventService eventService,
IGroupRepository groupRepository,
IOrganizationUserRepository organizationUserRepository,
IReferenceEventService referenceEventService)
{
_eventService = eventService;
_groupRepository = groupRepository;
_organizationUserRepository = organizationUserRepository;
_referenceEventService = referenceEventService;
}
public async Task CreateGroupAsync(Group group, Organization organization,
IEnumerable<SelectionReadOnly> collections = null)
IEnumerable<CollectionAccessSelection> collections = null,
IEnumerable<Guid> users = null)
{
Validate(organization);
await GroupRepositoryCreateGroupAsync(group, organization, collections);
if (users != null)
{
await GroupRepositoryUpdateUsersAsync(group, users);
}
await _eventService.LogGroupEventAsync(group, Enums.EventType.Group_Created);
}
public async Task CreateGroupAsync(Group group, Organization organization, EventSystemUser systemUser,
IEnumerable<SelectionReadOnly> collections = null)
IEnumerable<CollectionAccessSelection> collections = null,
IEnumerable<Guid> users = null)
{
Validate(organization);
await GroupRepositoryCreateGroupAsync(group, organization, collections);
if (users != null)
{
await GroupRepositoryUpdateUsersAsync(group, users, systemUser);
}
await _eventService.LogGroupEventAsync(group, Enums.EventType.Group_Created, systemUser);
}
private async Task GroupRepositoryCreateGroupAsync(Group group, Organization organization, IEnumerable<SelectionReadOnly> collections = null)
private async Task GroupRepositoryCreateGroupAsync(Group group, Organization organization, IEnumerable<CollectionAccessSelection> collections = null)
{
group.CreationDate = group.RevisionDate = DateTime.UtcNow;
@ -57,6 +74,28 @@ public class CreateGroupCommand : ICreateGroupCommand
await _referenceEventService.RaiseEventAsync(new ReferenceEvent(ReferenceEventType.GroupCreated, organization));
}
private async Task GroupRepositoryUpdateUsersAsync(Group group, IEnumerable<Guid> userIds,
EventSystemUser? systemUser = null)
{
var usersToAddToGroup = userIds as Guid[] ?? userIds.ToArray();
await _groupRepository.UpdateUsersAsync(group.Id, usersToAddToGroup);
var users = await _organizationUserRepository.GetManyAsync(usersToAddToGroup);
var eventDate = DateTime.UtcNow;
if (systemUser.HasValue)
{
await _eventService.LogOrganizationUserEventsAsync(users.Select(u =>
(u, EventType.OrganizationUser_UpdatedGroups, systemUser.Value, (DateTime?)eventDate)));
}
else
{
await _eventService.LogOrganizationUserEventsAsync(users.Select(u =>
(u, EventType.OrganizationUser_UpdatedGroups, (DateTime?)eventDate)));
}
}
private static void Validate(Organization organization)
{
if (organization == null)

View File

@ -9,25 +9,43 @@ namespace Bit.Core.OrganizationFeatures.Groups;
public class DeleteGroupCommand : IDeleteGroupCommand
{
private readonly IEventService _eventService;
private readonly IGroupRepository _groupRepository;
private readonly IEventService _eventService;
public DeleteGroupCommand(IEventService eventService, IGroupRepository groupRepository)
public DeleteGroupCommand(IGroupRepository groupRepository, IEventService eventService)
{
_eventService = eventService;
_groupRepository = groupRepository;
_eventService = eventService;
}
public async Task DeleteGroupAsync(Guid organizationId, Guid id)
{
var group = await GroupRepositoryDeleteGroupAsync(organizationId, id);
await _eventService.LogGroupEventAsync(group, Core.Enums.EventType.Group_Deleted);
await _eventService.LogGroupEventAsync(group, EventType.Group_Deleted);
}
public async Task DeleteGroupAsync(Guid organizationId, Guid id, EventSystemUser eventSystemUser)
{
var group = await GroupRepositoryDeleteGroupAsync(organizationId, id);
await _eventService.LogGroupEventAsync(group, Core.Enums.EventType.Group_Deleted, eventSystemUser);
await _eventService.LogGroupEventAsync(group, EventType.Group_Deleted, eventSystemUser);
}
public async Task DeleteAsync(Group group)
{
await _groupRepository.DeleteAsync(group);
await _eventService.LogGroupEventAsync(group, EventType.Group_Deleted);
}
public async Task DeleteManyAsync(ICollection<Group> groups)
{
await _eventService.LogGroupEventsAsync(
groups.Select(g =>
(g, EventType.Group_Deleted, (EventSystemUser?)null, (DateTime?)DateTime.UtcNow)
));
await _groupRepository.DeleteManyAsync(
groups.Select(g => g.Id)
);
}
private async Task<Group> GroupRepositoryDeleteGroupAsync(Guid organizationId, Guid id)

View File

@ -7,8 +7,10 @@ namespace Bit.Core.OrganizationFeatures.Groups.Interfaces;
public interface ICreateGroupCommand
{
Task CreateGroupAsync(Group group, Organization organization,
IEnumerable<SelectionReadOnly> collections = null);
IEnumerable<CollectionAccessSelection> collections = null,
IEnumerable<Guid> users = null);
Task CreateGroupAsync(Group group, Organization organization, EventSystemUser systemUser,
IEnumerable<SelectionReadOnly> collections = null);
IEnumerable<CollectionAccessSelection> collections = null,
IEnumerable<Guid> users = null);
}

View File

@ -1,4 +1,5 @@
using Bit.Core.Enums;
using Bit.Core.Entities;
using Bit.Core.Enums;
namespace Bit.Core.OrganizationFeatures.Groups.Interfaces;
@ -6,4 +7,6 @@ public interface IDeleteGroupCommand
{
Task DeleteGroupAsync(Guid organizationId, Guid id);
Task DeleteGroupAsync(Guid organizationId, Guid id, EventSystemUser eventSystemUser);
Task DeleteAsync(Group group);
Task DeleteManyAsync(ICollection<Group> groups);
}

View File

@ -7,8 +7,10 @@ namespace Bit.Core.OrganizationFeatures.Groups.Interfaces;
public interface IUpdateGroupCommand
{
Task UpdateGroupAsync(Group group, Organization organization,
IEnumerable<SelectionReadOnly> collections = null);
IEnumerable<CollectionAccessSelection> collections = null,
IEnumerable<Guid> users = null);
Task UpdateGroupAsync(Group group, Organization organization, EventSystemUser systemUser,
IEnumerable<SelectionReadOnly> collections = null);
IEnumerable<CollectionAccessSelection> collections = null,
IEnumerable<Guid> users = null);
}

View File

@ -12,32 +12,49 @@ public class UpdateGroupCommand : IUpdateGroupCommand
{
private readonly IEventService _eventService;
private readonly IGroupRepository _groupRepository;
private readonly IOrganizationUserRepository _organizationUserRepository;
public UpdateGroupCommand(
IEventService eventService,
IGroupRepository groupRepository)
IGroupRepository groupRepository,
IOrganizationUserRepository organizationUserRepository)
{
_eventService = eventService;
_groupRepository = groupRepository;
_organizationUserRepository = organizationUserRepository;
}
public async Task UpdateGroupAsync(Group group, Organization organization,
IEnumerable<SelectionReadOnly> collections = null)
IEnumerable<CollectionAccessSelection> collections = null,
IEnumerable<Guid> userIds = null)
{
Validate(organization);
await GroupRepositoryUpdateGroupAsync(group, collections);
if (userIds != null)
{
await GroupRepositoryUpdateUsersAsync(group, userIds);
}
await _eventService.LogGroupEventAsync(group, Enums.EventType.Group_Updated);
}
public async Task UpdateGroupAsync(Group group, Organization organization, EventSystemUser systemUser,
IEnumerable<SelectionReadOnly> collections = null)
IEnumerable<CollectionAccessSelection> collections = null,
IEnumerable<Guid> userIds = null)
{
Validate(organization);
await GroupRepositoryUpdateGroupAsync(group, collections);
if (userIds != null)
{
await GroupRepositoryUpdateUsersAsync(group, userIds, systemUser);
}
await _eventService.LogGroupEventAsync(group, Enums.EventType.Group_Updated, systemUser);
}
private async Task GroupRepositoryUpdateGroupAsync(Group group, IEnumerable<SelectionReadOnly> collections = null)
private async Task GroupRepositoryUpdateGroupAsync(Group group, IEnumerable<CollectionAccessSelection> collections = null)
{
group.RevisionDate = DateTime.UtcNow;
@ -51,6 +68,34 @@ public class UpdateGroupCommand : IUpdateGroupCommand
}
}
private async Task GroupRepositoryUpdateUsersAsync(Group group, IEnumerable<Guid> userIds, EventSystemUser? systemUser = null)
{
var newUserIds = userIds as Guid[] ?? userIds.ToArray();
var originalUserIds = await _groupRepository.GetManyUserIdsByIdAsync(group.Id);
await _groupRepository.UpdateUsersAsync(group.Id, newUserIds);
// We only want to create events OrganizationUserEvents for those that were actually modified.
// HashSet.SymmetricExceptWith is a convenient method of finding the difference between lists
var changedUserIds = new HashSet<Guid>(originalUserIds);
changedUserIds.SymmetricExceptWith(newUserIds);
// Fetch all changed users for logging the event
var users = await _organizationUserRepository.GetManyAsync(changedUserIds);
var eventDate = DateTime.UtcNow;
if (systemUser.HasValue)
{
await _eventService.LogOrganizationUserEventsAsync(users.Select(u =>
(u, EventType.OrganizationUser_UpdatedGroups, systemUser.Value, (DateTime?)eventDate)));
}
else
{
await _eventService.LogOrganizationUserEventsAsync(users.Select(u =>
(u, EventType.OrganizationUser_UpdatedGroups, (DateTime?)eventDate)));
}
}
private static void Validate(Organization organization)
{
if (organization == null)

View File

@ -0,0 +1,39 @@
using Bit.Core.Entities;
using Bit.Core.OrganizationFeatures.OrganizationCollections.Interfaces;
using Bit.Core.Repositories;
using Bit.Core.Services;
namespace Bit.Core.OrganizationFeatures.OrganizationCollections;
public class DeleteCollectionCommand : IDeleteCollectionCommand
{
private readonly ICollectionRepository _collectionRepository;
private readonly IEventService _eventService;
public DeleteCollectionCommand(
ICollectionRepository collectionRepository,
IEventService eventService)
{
_collectionRepository = collectionRepository;
_eventService = eventService;
}
public async Task DeleteAsync(Collection collection)
{
await _collectionRepository.DeleteAsync(collection);
await _eventService.LogCollectionEventAsync(collection, Enums.EventType.Collection_Deleted, DateTime.UtcNow);
}
public async Task DeleteManyAsync(IEnumerable<Guid> collectionIds)
{
var ids = collectionIds as Guid[] ?? collectionIds.ToArray();
var collectionsToDelete = await _collectionRepository.GetManyByManyIdsAsync(ids);
await this.DeleteManyAsync(collectionsToDelete);
}
public async Task DeleteManyAsync(IEnumerable<Collection> collections)
{
await _collectionRepository.DeleteManyAsync(collections.Select(c => c.Id));
await _eventService.LogCollectionEventsAsync(collections.Select(c => (c, Enums.EventType.Collection_Deleted, (DateTime?)DateTime.UtcNow)));
}
}

View File

@ -0,0 +1,10 @@
using Bit.Core.Entities;
namespace Bit.Core.OrganizationFeatures.OrganizationCollections.Interfaces;
public interface IDeleteCollectionCommand
{
Task DeleteAsync(Collection collection);
Task DeleteManyAsync(IEnumerable<Guid> collectionIds);
Task DeleteManyAsync(IEnumerable<Collection> collections);
}

View File

@ -3,6 +3,8 @@ using Bit.Core.OrganizationFeatures.Groups;
using Bit.Core.OrganizationFeatures.Groups.Interfaces;
using Bit.Core.OrganizationFeatures.OrganizationApiKeys;
using Bit.Core.OrganizationFeatures.OrganizationApiKeys.Interfaces;
using Bit.Core.OrganizationFeatures.OrganizationCollections;
using Bit.Core.OrganizationFeatures.OrganizationCollections.Interfaces;
using Bit.Core.OrganizationFeatures.OrganizationConnections;
using Bit.Core.OrganizationFeatures.OrganizationConnections.Interfaces;
using Bit.Core.OrganizationFeatures.OrganizationSponsorships.FamiliesForEnterprise;
@ -28,13 +30,8 @@ public static class OrganizationServiceCollectionExtensions
services.AddOrganizationConnectionCommands();
services.AddOrganizationSponsorshipCommands(globalSettings);
services.AddOrganizationApiKeyCommandsQueries();
}
private static void AddOrganizationGroupCommands(this IServiceCollection services)
{
services.AddScoped<ICreateGroupCommand, CreateGroupCommand>();
services.AddScoped<IDeleteGroupCommand, DeleteGroupCommand>();
services.AddScoped<IUpdateGroupCommand, UpdateGroupCommand>();
services.AddOrganizationCollectionCommands();
services.AddOrganizationGroupCommands();
}
private static void AddOrganizationConnectionCommands(this IServiceCollection services)
@ -76,6 +73,18 @@ public static class OrganizationServiceCollectionExtensions
services.AddScoped<ICreateOrganizationApiKeyCommand, CreateOrganizationApiKeyCommand>();
}
public static void AddOrganizationCollectionCommands(this IServiceCollection services)
{
services.AddScoped<IDeleteCollectionCommand, DeleteCollectionCommand>();
}
private static void AddOrganizationGroupCommands(this IServiceCollection services)
{
services.AddScoped<ICreateGroupCommand, CreateGroupCommand>();
services.AddScoped<IDeleteGroupCommand, DeleteGroupCommand>();
services.AddScoped<IUpdateGroupCommand, UpdateGroupCommand>();
}
private static void AddTokenizers(this IServiceCollection services)
{
services.AddSingleton<IDataProtectorTokenFactory<OrganizationSponsorshipOfferTokenable>>(serviceProvider =>

View File

@ -6,14 +6,18 @@ namespace Bit.Core.Repositories;
public interface ICollectionRepository : IRepository<Collection, Guid>
{
Task<int> GetCountByOrganizationIdAsync(Guid organizationId);
Task<Tuple<Collection, ICollection<SelectionReadOnly>>> GetByIdWithGroupsAsync(Guid id);
Task<Tuple<CollectionDetails, ICollection<SelectionReadOnly>>> GetByIdWithGroupsAsync(Guid id, Guid userId);
Task<Tuple<Collection, CollectionAccessDetails>> GetByIdWithAccessAsync(Guid id);
Task<Tuple<CollectionDetails, CollectionAccessDetails>> GetByIdWithAccessAsync(Guid id, Guid userId);
Task<ICollection<Collection>> GetManyByOrganizationIdAsync(Guid organizationId);
Task<ICollection<Tuple<Collection, CollectionAccessDetails>>> GetManyByOrganizationIdWithAccessAsync(Guid organizationId);
Task<ICollection<Tuple<Collection, CollectionAccessDetails>>> GetManyByUserIdWithAccessAsync(Guid userId, Guid organizationId);
Task<CollectionDetails> GetByIdAsync(Guid id, Guid userId);
Task<ICollection<Collection>> GetManyByManyIdsAsync(IEnumerable<Guid> collectionIds);
Task<ICollection<CollectionDetails>> GetManyByUserIdAsync(Guid userId);
Task CreateAsync(Collection obj, IEnumerable<SelectionReadOnly> groups);
Task ReplaceAsync(Collection obj, IEnumerable<SelectionReadOnly> groups);
Task CreateAsync(Collection obj, IEnumerable<CollectionAccessSelection> groups, IEnumerable<CollectionAccessSelection> users);
Task ReplaceAsync(Collection obj, IEnumerable<CollectionAccessSelection> groups, IEnumerable<CollectionAccessSelection> users);
Task DeleteUserAsync(Guid collectionId, Guid organizationUserId);
Task UpdateUsersAsync(Guid id, IEnumerable<SelectionReadOnly> users);
Task<ICollection<SelectionReadOnly>> GetManyUsersByIdAsync(Guid id);
Task UpdateUsersAsync(Guid id, IEnumerable<CollectionAccessSelection> users);
Task<ICollection<CollectionAccessSelection>> GetManyUsersByIdAsync(Guid id);
Task DeleteManyAsync(IEnumerable<Guid> collectionIds);
}

View File

@ -5,13 +5,17 @@ namespace Bit.Core.Repositories;
public interface IGroupRepository : IRepository<Group, Guid>
{
Task<Tuple<Group, ICollection<SelectionReadOnly>>> GetByIdWithCollectionsAsync(Guid id);
Task<Tuple<Group, ICollection<CollectionAccessSelection>>> GetByIdWithCollectionsAsync(Guid id);
Task<ICollection<Group>> GetManyByOrganizationIdAsync(Guid organizationId);
Task<ICollection<Tuple<Group, ICollection<CollectionAccessSelection>>>> GetManyWithCollectionsByOrganizationIdAsync(
Guid organizationId);
Task<ICollection<Group>> GetManyByManyIds(IEnumerable<Guid> groupIds);
Task<ICollection<Guid>> GetManyIdsByUserIdAsync(Guid organizationUserId);
Task<ICollection<Guid>> GetManyUserIdsByIdAsync(Guid id);
Task<ICollection<GroupUser>> GetManyGroupUsersByOrganizationIdAsync(Guid organizationId);
Task CreateAsync(Group obj, IEnumerable<SelectionReadOnly> collections);
Task ReplaceAsync(Group obj, IEnumerable<SelectionReadOnly> collections);
Task CreateAsync(Group obj, IEnumerable<CollectionAccessSelection> collections);
Task ReplaceAsync(Group obj, IEnumerable<CollectionAccessSelection> collections);
Task DeleteUserAsync(Guid groupId, Guid organizationUserId);
Task UpdateUsersAsync(Guid groupId, IEnumerable<Guid> organizationUserIds);
Task DeleteManyAsync(IEnumerable<Guid> groupIds);
}

View File

@ -15,20 +15,20 @@ public interface IOrganizationUserRepository : IRepository<OrganizationUser, Gui
Task<int> GetCountByOrganizationAsync(Guid organizationId, string email, bool onlyRegisteredUsers);
Task<ICollection<string>> SelectKnownEmailsAsync(Guid organizationId, IEnumerable<string> emails, bool onlyRegisteredUsers);
Task<OrganizationUser> GetByOrganizationAsync(Guid organizationId, Guid userId);
Task<Tuple<OrganizationUser, ICollection<SelectionReadOnly>>> GetByIdWithCollectionsAsync(Guid id);
Task<Tuple<OrganizationUser, ICollection<CollectionAccessSelection>>> GetByIdWithCollectionsAsync(Guid id);
Task<OrganizationUserUserDetails> GetDetailsByIdAsync(Guid id);
Task<Tuple<OrganizationUserUserDetails, ICollection<SelectionReadOnly>>>
Task<Tuple<OrganizationUserUserDetails, ICollection<CollectionAccessSelection>>>
GetDetailsByIdWithCollectionsAsync(Guid id);
Task<ICollection<OrganizationUserUserDetails>> GetManyDetailsByOrganizationAsync(Guid organizationId);
Task<ICollection<OrganizationUserUserDetails>> GetManyDetailsByOrganizationAsync(Guid organizationId, bool includeGroups = false, bool includeCollections = false);
Task<ICollection<OrganizationUserOrganizationDetails>> GetManyDetailsByUserAsync(Guid userId,
OrganizationUserStatusType? status = null);
Task<OrganizationUserOrganizationDetails> GetDetailsByUserAsync(Guid userId, Guid organizationId,
OrganizationUserStatusType? status = null);
Task UpdateGroupsAsync(Guid orgUserId, IEnumerable<Guid> groupIds);
Task UpsertManyAsync(IEnumerable<OrganizationUser> organizationUsers);
Task<Guid> CreateAsync(OrganizationUser obj, IEnumerable<SelectionReadOnly> collections);
Task<Guid> CreateAsync(OrganizationUser obj, IEnumerable<CollectionAccessSelection> collections);
Task<ICollection<Guid>> CreateManyAsync(IEnumerable<OrganizationUser> organizationIdUsers);
Task ReplaceAsync(OrganizationUser obj, IEnumerable<SelectionReadOnly> collections);
Task ReplaceAsync(OrganizationUser obj, IEnumerable<CollectionAccessSelection> collections);
Task ReplaceManyAsync(IEnumerable<OrganizationUser> organizationUsers);
Task<ICollection<OrganizationUser>> GetManyByManyUsersAsync(IEnumerable<Guid> userIds);
Task<ICollection<OrganizationUser>> GetManyAsync(IEnumerable<Guid> Ids);

View File

@ -5,8 +5,7 @@ namespace Bit.Core.Services;
public interface ICollectionService
{
Task SaveAsync(Collection collection, IEnumerable<SelectionReadOnly> groups = null, Guid? assignUserId = null);
Task DeleteAsync(Collection collection);
Task SaveAsync(Collection collection, IEnumerable<CollectionAccessSelection> groups = null, IEnumerable<CollectionAccessSelection> users = null, Guid? assignUserId = null);
Task DeleteUserAsync(Collection collection, Guid organizationUserId);
Task<IEnumerable<Collection>> GetOrganizationCollections(Guid organizationId);
}

View File

@ -10,8 +10,10 @@ public interface IEventService
Task LogCipherEventAsync(Cipher cipher, EventType type, DateTime? date = null);
Task LogCipherEventsAsync(IEnumerable<Tuple<Cipher, EventType, DateTime?>> events);
Task LogCollectionEventAsync(Collection collection, EventType type, DateTime? date = null);
Task LogCollectionEventsAsync(IEnumerable<(Collection collection, EventType type, DateTime? date)> events);
Task LogGroupEventAsync(Group group, EventType type, DateTime? date = null);
Task LogGroupEventAsync(Group group, EventType type, EventSystemUser systemUser, DateTime? date = null);
Task LogGroupEventsAsync(IEnumerable<(Group group, EventType type, EventSystemUser? systemUser, DateTime? date)> events);
Task LogPolicyEventAsync(Policy policy, EventType type, DateTime? date = null);
Task LogOrganizationUserEventAsync(OrganizationUser organizationUser, EventType type, DateTime? date = null);
Task LogOrganizationUserEventAsync(OrganizationUser organizationUser, EventType type, EventSystemUser systemUser, DateTime? date = null);

View File

@ -34,9 +34,9 @@ public interface IOrganizationService
Task<List<OrganizationUser>> InviteUsersAsync(Guid organizationId, EventSystemUser systemUser,
IEnumerable<(OrganizationUserInvite invite, string externalId)> invites);
Task<OrganizationUser> InviteUserAsync(Guid organizationId, Guid? invitingUserId, string email,
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<SelectionReadOnly> collections);
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<CollectionAccessSelection> collections, IEnumerable<Guid> groups);
Task<OrganizationUser> InviteUserAsync(Guid organizationId, EventSystemUser systemUser, string email,
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<SelectionReadOnly> collections);
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<CollectionAccessSelection> collections, IEnumerable<Guid> groups);
Task<IEnumerable<Tuple<OrganizationUser, string>>> ResendInvitesAsync(Guid organizationId, Guid? invitingUserId, IEnumerable<Guid> organizationUsersId);
Task ResendInviteAsync(Guid organizationId, Guid? invitingUserId, Guid organizationUserId);
Task<OrganizationUser> AcceptUserAsync(Guid organizationUserId, User user, string token,
@ -46,7 +46,7 @@ public interface IOrganizationService
Guid confirmingUserId, IUserService userService);
Task<List<Tuple<OrganizationUser, string>>> ConfirmUsersAsync(Guid organizationId, Dictionary<Guid, string> keys,
Guid confirmingUserId, IUserService userService);
Task SaveUserAsync(OrganizationUser user, Guid? savingUserId, IEnumerable<SelectionReadOnly> collections);
Task SaveUserAsync(OrganizationUser user, Guid? savingUserId, IEnumerable<CollectionAccessSelection> collections, IEnumerable<Guid> groups);
[Obsolete("IDeleteOrganizationUserCommand should be used instead. To be removed by EC-607.")]
Task DeleteUserAsync(Guid organizationId, Guid organizationUserId, Guid? deletingUserId);
[Obsolete("IDeleteOrganizationUserCommand should be used instead. To be removed by EC-607.")]

View File

@ -39,8 +39,8 @@ public class CollectionService : ICollectionService
_currentContext = currentContext;
}
public async Task SaveAsync(Collection collection, IEnumerable<SelectionReadOnly> groups = null,
Guid? assignUserId = null)
public async Task SaveAsync(Collection collection, IEnumerable<CollectionAccessSelection> groups = null,
IEnumerable<CollectionAccessSelection> users = null, Guid? assignUserId = null)
{
var org = await _organizationRepository.GetByIdAsync(collection.OrganizationId);
if (org == null)
@ -60,14 +60,7 @@ public class CollectionService : ICollectionService
}
}
if (groups == null || !org.UseGroups)
{
await _collectionRepository.CreateAsync(collection);
}
else
{
await _collectionRepository.CreateAsync(collection, groups);
}
await _collectionRepository.CreateAsync(collection, org.UseGroups ? groups : null, users);
// Assign a user to the newly created collection.
if (assignUserId.HasValue)
@ -76,8 +69,8 @@ public class CollectionService : ICollectionService
if (orgUser != null && orgUser.Status == Enums.OrganizationUserStatusType.Confirmed)
{
await _collectionRepository.UpdateUsersAsync(collection.Id,
new List<SelectionReadOnly> {
new SelectionReadOnly { Id = orgUser.Id, ReadOnly = false } });
new List<CollectionAccessSelection> {
new CollectionAccessSelection { Id = orgUser.Id, ReadOnly = false } });
}
}
@ -86,25 +79,11 @@ public class CollectionService : ICollectionService
}
else
{
if (!org.UseGroups)
{
await _collectionRepository.ReplaceAsync(collection);
}
else
{
await _collectionRepository.ReplaceAsync(collection, groups ?? new List<SelectionReadOnly>());
}
await _collectionRepository.ReplaceAsync(collection, org.UseGroups ? groups : null, users);
await _eventService.LogCollectionEventAsync(collection, Enums.EventType.Collection_Updated);
}
}
public async Task DeleteAsync(Collection collection)
{
await _collectionRepository.DeleteAsync(collection);
await _eventService.LogCollectionEventAsync(collection, Enums.EventType.Collection_Deleted);
}
public async Task DeleteUserAsync(Collection collection, Guid organizationUserId)
{
var orgUser = await _organizationUserRepository.GetByIdAsync(organizationUserId);

View File

@ -135,15 +135,22 @@ public class EventService : IEventService
};
}
public async Task LogCollectionEventAsync(Collection collection, EventType type, DateTime? date = null)
public async Task LogCollectionEventAsync(Collection collection, EventType type, DateTime? date = null) =>
await LogCollectionEventsAsync(new[] { (collection, type, date) });
public async Task LogCollectionEventsAsync(IEnumerable<(Collection collection, EventType type, DateTime? date)> events)
{
var orgAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync();
var eventMessages = new List<IEvent>();
foreach (var (collection, type, date) in events)
{
if (!CanUseEvents(orgAbilities, collection.OrganizationId))
{
return;
continue;
}
var e = new EventMessage(_currentContext)
eventMessages.Add(new EventMessage(_currentContext)
{
OrganizationId = collection.OrganizationId,
CollectionId = collection.Id,
@ -151,42 +158,43 @@ public class EventService : IEventService
ActingUserId = _currentContext?.UserId,
ProviderId = await GetProviderIdAsync(collection.OrganizationId),
Date = date.GetValueOrDefault(DateTime.UtcNow)
};
await _eventWriteService.CreateAsync(e);
});
}
public async Task LogGroupEventAsync(Group group, EventType type,
DateTime? date = null)
{
await CreateLogGroupEventAsync(group, type, systemUser: null, date);
await _eventWriteService.CreateManyAsync(eventMessages);
}
public async Task LogGroupEventAsync(Group group, EventType type, EventSystemUser systemUser,
DateTime? date = null)
{
await CreateLogGroupEventAsync(group, type, systemUser, date);
}
public async Task LogGroupEventAsync(Group group, EventType type, DateTime? date = null) =>
await LogGroupEventsAsync(new[] { (group, type, (EventSystemUser?)null, date) });
private async Task CreateLogGroupEventAsync(Group group, EventType type, EventSystemUser? systemUser, DateTime? date = null)
public async Task LogGroupEventAsync(Group group, EventType type, EventSystemUser systemUser, DateTime? date = null) =>
await LogGroupEventsAsync(new[] { (group, type, (EventSystemUser?)systemUser, date) });
public async Task LogGroupEventsAsync(IEnumerable<(Group group, EventType type, EventSystemUser? systemUser, DateTime? date)> events)
{
var orgAbilities = await _applicationCacheService.GetOrganizationAbilitiesAsync();
var eventMessages = new List<IEvent>();
foreach (var (group, type, systemUser, date) in events)
{
if (!CanUseEvents(orgAbilities, group.OrganizationId))
{
return;
continue;
}
var e = new EventMessage(_currentContext)
eventMessages.Add(new EventMessage(_currentContext)
{
OrganizationId = group.OrganizationId,
GroupId = group.Id,
Type = type,
ActingUserId = _currentContext?.UserId,
ProviderId = await GetProviderIdAsync(@group.OrganizationId),
Date = date.GetValueOrDefault(DateTime.UtcNow),
SystemUser = systemUser
};
await _eventWriteService.CreateAsync(e);
ProviderId = await GetProviderIdAsync(group.OrganizationId),
SystemUser = systemUser,
Date = date.GetValueOrDefault(DateTime.UtcNow)
});
}
await _eventWriteService.CreateManyAsync(eventMessages);
}
public async Task LogPolicyEventAsync(Policy policy, EventType type, DateTime? date = null)
{

View File

@ -1207,7 +1207,8 @@ public class OrganizationService : IOrganizationService
}
var orgUsers = new List<OrganizationUser>();
var limitedCollectionOrgUsers = new List<(OrganizationUser, IEnumerable<SelectionReadOnly>)>();
var limitedCollectionOrgUsers = new List<(OrganizationUser, IEnumerable<CollectionAccessSelection>)>();
var orgUserGroups = new List<(OrganizationUser, IEnumerable<Guid>)>();
var orgUserInvitedCount = 0;
var exceptions = new List<Exception>();
var events = new List<(OrganizationUser, EventType, DateTime?)>();
@ -1252,6 +1253,11 @@ public class OrganizationService : IOrganizationService
orgUsers.Add(orgUser);
}
if (invite.Groups != null && invite.Groups.Any())
{
orgUserGroups.Add((orgUser, invite.Groups));
}
events.Add((orgUser, EventType.OrganizationUser_Invited, DateTime.UtcNow));
orgUserInvitedCount++;
}
@ -1276,6 +1282,11 @@ public class OrganizationService : IOrganizationService
await _organizationUserRepository.CreateAsync(orgUser, collections);
}
foreach (var (orgUser, groups) in orgUserGroups)
{
await _organizationUserRepository.UpdateGroupsAsync(orgUser.Id, groups);
}
if (!await _currentContext.ManageUsers(organization.Id))
{
throw new BadRequestException("Cannot add seats. Cannot manage organization users.");
@ -1659,7 +1670,8 @@ public class OrganizationService : IOrganizationService
}
public async Task SaveUserAsync(OrganizationUser user, Guid? savingUserId,
IEnumerable<SelectionReadOnly> collections)
IEnumerable<CollectionAccessSelection> collections,
IEnumerable<Guid> groups)
{
if (user.Id.Equals(default(Guid)))
{
@ -1688,9 +1700,15 @@ public class OrganizationService : IOrganizationService
if (user.AccessAll)
{
// We don't need any collections if we're flagged to have all access.
collections = new List<SelectionReadOnly>();
collections = new List<CollectionAccessSelection>();
}
await _organizationUserRepository.ReplaceAsync(user, collections);
if (groups != null)
{
await _organizationUserRepository.UpdateGroupsAsync(user.Id, groups);
}
await _eventService.LogOrganizationUserEventAsync(user, EventType.OrganizationUser_Updated);
}
@ -1915,19 +1933,21 @@ public class OrganizationService : IOrganizationService
}
public async Task<OrganizationUser> InviteUserAsync(Guid organizationId, Guid? invitingUserId, string email,
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<SelectionReadOnly> collections)
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<CollectionAccessSelection> collections,
IEnumerable<Guid> groups)
{
return await SaveUserSendInviteAsync(organizationId, invitingUserId, systemUser: null, email, type, accessAll, externalId, collections);
return await SaveUserSendInviteAsync(organizationId, invitingUserId, systemUser: null, email, type, accessAll, externalId, collections, groups);
}
public async Task<OrganizationUser> InviteUserAsync(Guid organizationId, EventSystemUser systemUser, string email,
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<SelectionReadOnly> collections)
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<CollectionAccessSelection> collections,
IEnumerable<Guid> groups)
{
return await SaveUserSendInviteAsync(organizationId, invitingUserId: null, systemUser, email, type, accessAll, externalId, collections);
return await SaveUserSendInviteAsync(organizationId, invitingUserId: null, systemUser, email, type, accessAll, externalId, collections, groups);
}
private async Task<OrganizationUser> SaveUserSendInviteAsync(Guid organizationId, Guid? invitingUserId, EventSystemUser? systemUser, string email,
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<SelectionReadOnly> collections)
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<CollectionAccessSelection> collections, IEnumerable<Guid> groups)
{
var invite = new OrganizationUserInvite()
{
@ -1935,6 +1955,7 @@ public class OrganizationService : IOrganizationService
Type = type,
AccessAll = accessAll,
Collections = collections,
Groups = groups
};
var results = systemUser.HasValue ? await InviteUsersAsync(organizationId, systemUser.Value,
new (OrganizationUserInvite, string)[] { (invite, externalId) }) : await InviteUsersAsync(organizationId, invitingUserId,
@ -2048,7 +2069,7 @@ public class OrganizationService : IOrganizationService
Emails = new List<string> { user.Email },
Type = OrganizationUserType.User,
AccessAll = false,
Collections = new List<SelectionReadOnly>(),
Collections = new List<CollectionAccessSelection>(),
};
userInvites.Add((invite, user.ExternalId));
}

View File

@ -21,6 +21,17 @@ public class NoopEventService : IEventService
return Task.FromResult(0);
}
Task IEventService.LogCollectionEventsAsync(IEnumerable<(Collection collection, EventType type, DateTime? date)> events)
{
return Task.FromResult(0);
}
public Task LogGroupEventsAsync(
IEnumerable<(Group group, EventType type, EventSystemUser? systemUser, DateTime? date)> events)
{
return Task.FromResult(0);
}
public Task LogPolicyEventAsync(Policy policy, EventType type, DateTime? date = null)
{
return Task.FromResult(0);
@ -82,4 +93,5 @@ public class NoopEventService : IEventService
{
return Task.FromResult(0);
}
}

View File

@ -29,7 +29,7 @@ public static class DapperHelpers
return table;
}
public static DataTable ToArrayTVP(this IEnumerable<SelectionReadOnly> values)
public static DataTable ToArrayTVP(this IEnumerable<CollectionAccessSelection> values)
{
var table = new DataTable();
table.SetTypeName("[dbo].[SelectionReadOnlyArray]");

View File

@ -32,36 +32,53 @@ public class CollectionRepository : Repository<Collection, Guid>, ICollectionRep
}
}
public async Task<Tuple<Collection, ICollection<SelectionReadOnly>>> GetByIdWithGroupsAsync(Guid id)
public async Task<Tuple<Collection, CollectionAccessDetails>> GetByIdWithAccessAsync(Guid id)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryMultipleAsync(
$"[{Schema}].[Collection_ReadWithGroupsById]",
$"[{Schema}].[Collection_ReadWithGroupsAndUsersById]",
new { Id = id },
commandType: CommandType.StoredProcedure);
var collection = await results.ReadFirstOrDefaultAsync<Collection>();
var groups = (await results.ReadAsync<SelectionReadOnly>()).ToList();
var groups = (await results.ReadAsync<CollectionAccessSelection>()).ToList();
var users = (await results.ReadAsync<CollectionAccessSelection>()).ToList();
var access = new CollectionAccessDetails { Groups = groups, Users = users };
return new Tuple<Collection, ICollection<SelectionReadOnly>>(collection, groups);
return new Tuple<Collection, CollectionAccessDetails>(collection, access);
}
}
public async Task<Tuple<CollectionDetails, ICollection<SelectionReadOnly>>> GetByIdWithGroupsAsync(
public async Task<Tuple<CollectionDetails, CollectionAccessDetails>> GetByIdWithAccessAsync(
Guid id, Guid userId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryMultipleAsync(
$"[{Schema}].[Collection_ReadWithGroupsByIdUserId]",
$"[{Schema}].[Collection_ReadWithGroupsAndUsersByIdUserId]",
new { Id = id, UserId = userId },
commandType: CommandType.StoredProcedure);
var collection = await results.ReadFirstOrDefaultAsync<CollectionDetails>();
var groups = (await results.ReadAsync<SelectionReadOnly>()).ToList();
var groups = (await results.ReadAsync<CollectionAccessSelection>()).ToList();
var users = (await results.ReadAsync<CollectionAccessSelection>()).ToList();
var access = new CollectionAccessDetails { Groups = groups, Users = users };
return new Tuple<CollectionDetails, ICollection<SelectionReadOnly>>(collection, groups);
return new Tuple<CollectionDetails, CollectionAccessDetails>(collection, access);
}
}
public async Task<ICollection<Collection>> GetManyByManyIdsAsync(IEnumerable<Guid> collectionIds)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<Collection>(
$"[{Schema}].[Collection_ReadByIds]",
new { Ids = collectionIds.ToGuidIdArrayTVP() },
commandType: CommandType.StoredProcedure);
return results.ToList();
}
}
@ -78,6 +95,91 @@ public class CollectionRepository : Repository<Collection, Guid>, ICollectionRep
}
}
public async Task<ICollection<Tuple<Collection, CollectionAccessDetails>>> GetManyByOrganizationIdWithAccessAsync(Guid organizationId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryMultipleAsync(
$"[{Schema}].[Collection_ReadWithGroupsAndUsersByOrganizationId]",
new { OrganizationId = organizationId },
commandType: CommandType.StoredProcedure);
var collections = (await results.ReadAsync<Collection>());
var groups = (await results.ReadAsync<CollectionGroup>())
.GroupBy(g => g.CollectionId);
var users = (await results.ReadAsync<CollectionUser>())
.GroupBy(u => u.CollectionId);
return collections.Select(collection =>
new Tuple<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<Collection, CollectionAccessDetails>>> GetManyByUserIdWithAccessAsync(Guid userId, Guid organizationId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryMultipleAsync(
$"[{Schema}].[Collection_ReadWithGroupsAndUsersByUserId]",
new { UserId = userId },
commandType: CommandType.StoredProcedure);
var collections = (await results.ReadAsync<Collection>()).Where(c => c.OrganizationId == organizationId);
var groups = (await results.ReadAsync<CollectionGroup>())
.GroupBy(g => g.CollectionId);
var users = (await results.ReadAsync<CollectionUser>())
.GroupBy(u => u.CollectionId);
return collections.Select(collection =>
new Tuple<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<CollectionDetails> GetByIdAsync(Guid id, Guid userId)
{
using (var connection = new SqlConnection(ConnectionString))
@ -104,35 +206,48 @@ public class CollectionRepository : Repository<Collection, Guid>, ICollectionRep
}
}
public async Task CreateAsync(Collection obj, IEnumerable<SelectionReadOnly> groups)
public async Task CreateAsync(Collection obj, IEnumerable<CollectionAccessSelection> groups, IEnumerable<CollectionAccessSelection> users)
{
obj.SetNewId();
var objWithGroups = JsonSerializer.Deserialize<CollectionWithGroups>(JsonSerializer.Serialize(obj));
objWithGroups.Groups = groups.ToArrayTVP();
var objWithGroupsAndUsers = JsonSerializer.Deserialize<CollectionWithGroupsAndUsers>(JsonSerializer.Serialize(obj));
objWithGroupsAndUsers.Groups = groups != null ? groups.ToArrayTVP() : Enumerable.Empty<CollectionAccessSelection>().ToArrayTVP();
objWithGroupsAndUsers.Users = users != null ? users.ToArrayTVP() : Enumerable.Empty<CollectionAccessSelection>().ToArrayTVP();
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.ExecuteAsync(
$"[{Schema}].[Collection_CreateWithGroups]",
objWithGroups,
$"[{Schema}].[Collection_CreateWithGroupsAndUsers]",
objWithGroupsAndUsers,
commandType: CommandType.StoredProcedure);
}
}
public async Task ReplaceAsync(Collection obj, IEnumerable<SelectionReadOnly> groups)
public async Task ReplaceAsync(Collection obj, IEnumerable<CollectionAccessSelection> groups, IEnumerable<CollectionAccessSelection> users)
{
var objWithGroups = JsonSerializer.Deserialize<CollectionWithGroups>(JsonSerializer.Serialize(obj));
objWithGroups.Groups = groups.ToArrayTVP();
var objWithGroupsAndUsers = JsonSerializer.Deserialize<CollectionWithGroupsAndUsers>(JsonSerializer.Serialize(obj));
objWithGroupsAndUsers.Groups = groups != null ? groups.ToArrayTVP() : Enumerable.Empty<CollectionAccessSelection>().ToArrayTVP();
objWithGroupsAndUsers.Users = users != null ? users.ToArrayTVP() : Enumerable.Empty<CollectionAccessSelection>().ToArrayTVP();
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.ExecuteAsync(
$"[{Schema}].[Collection_UpdateWithGroups]",
objWithGroups,
$"[{Schema}].[Collection_UpdateWithGroupsAndUsers]",
objWithGroupsAndUsers,
commandType: CommandType.StoredProcedure);
}
}
public async Task DeleteManyAsync(IEnumerable<Guid> collectionIds)
{
using (var connection = new SqlConnection(ConnectionString))
{
await connection.ExecuteAsync("[dbo].[Collection_DeleteByIds]",
new { Ids = collectionIds.ToGuidIdArrayTVP() }, commandType: CommandType.StoredProcedure);
}
}
public async Task CreateUserAsync(Guid collectionId, Guid organizationUserId)
{
using (var connection = new SqlConnection(ConnectionString))
@ -155,7 +270,7 @@ public class CollectionRepository : Repository<Collection, Guid>, ICollectionRep
}
}
public async Task UpdateUsersAsync(Guid id, IEnumerable<SelectionReadOnly> users)
public async Task UpdateUsersAsync(Guid id, IEnumerable<CollectionAccessSelection> users)
{
using (var connection = new SqlConnection(ConnectionString))
{
@ -166,11 +281,11 @@ public class CollectionRepository : Repository<Collection, Guid>, ICollectionRep
}
}
public async Task<ICollection<SelectionReadOnly>> GetManyUsersByIdAsync(Guid id)
public async Task<ICollection<CollectionAccessSelection>> GetManyUsersByIdAsync(Guid id)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<SelectionReadOnly>(
var results = await connection.QueryAsync<CollectionAccessSelection>(
$"[{Schema}].[CollectionUser_ReadByCollectionId]",
new { CollectionId = id },
commandType: CommandType.StoredProcedure);
@ -179,8 +294,9 @@ public class CollectionRepository : Repository<Collection, Guid>, ICollectionRep
}
}
public class CollectionWithGroups : Collection
public class CollectionWithGroupsAndUsers : Collection
{
public DataTable Groups { get; set; }
public DataTable Users { get; set; }
}
}

View File

@ -19,7 +19,7 @@ public class GroupRepository : Repository<Group, Guid>, IGroupRepository
: base(connectionString, readOnlyConnectionString)
{ }
public async Task<Tuple<Group, ICollection<SelectionReadOnly>>> GetByIdWithCollectionsAsync(Guid id)
public async Task<Tuple<Group, ICollection<CollectionAccessSelection>>> GetByIdWithCollectionsAsync(Guid id)
{
using (var connection = new SqlConnection(ConnectionString))
{
@ -29,9 +29,9 @@ public class GroupRepository : Repository<Group, Guid>, IGroupRepository
commandType: CommandType.StoredProcedure);
var group = await results.ReadFirstOrDefaultAsync<Group>();
var colletions = (await results.ReadAsync<SelectionReadOnly>()).ToList();
var colletions = (await results.ReadAsync<CollectionAccessSelection>()).ToList();
return new Tuple<Group, ICollection<SelectionReadOnly>>(group, colletions);
return new Tuple<Group, ICollection<CollectionAccessSelection>>(group, colletions);
}
}
@ -48,6 +48,48 @@ public class GroupRepository : Repository<Group, Guid>, IGroupRepository
}
}
public async Task<ICollection<Tuple<Group, ICollection<CollectionAccessSelection>>>> GetManyWithCollectionsByOrganizationIdAsync(Guid organizationId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryMultipleAsync(
$"[{Schema}].[Group_ReadWithCollectionsByOrganizationId]",
new { OrganizationId = organizationId },
commandType: CommandType.StoredProcedure);
var groups = (await results.ReadAsync<Group>()).ToList();
var collections = (await results.ReadAsync<CollectionGroup>())
.GroupBy(c => c.GroupId)
.ToList();
return groups.Select(group =>
new Tuple<Group, ICollection<CollectionAccessSelection>>(
group,
collections.FirstOrDefault(c => c.Key == group.Id)?
.Select(c => new CollectionAccessSelection
{
Id = c.CollectionId,
HidePasswords = c.HidePasswords,
ReadOnly = c.ReadOnly
}
).ToList() ?? new List<CollectionAccessSelection>())
).ToList();
}
}
public async Task<ICollection<Group>> GetManyByManyIds(IEnumerable<Guid> groupIds)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<Group>(
$"[{Schema}].[Group_ReadByIds]",
new { Ids = groupIds.ToGuidIdArrayTVP() },
commandType: CommandType.StoredProcedure);
return results.ToList();
}
}
public async Task<ICollection<Guid>> GetManyIdsByUserIdAsync(Guid organizationUserId)
{
using (var connection = new SqlConnection(ConnectionString))
@ -87,7 +129,7 @@ public class GroupRepository : Repository<Group, Guid>, IGroupRepository
}
}
public async Task CreateAsync(Group obj, IEnumerable<SelectionReadOnly> collections)
public async Task CreateAsync(Group obj, IEnumerable<CollectionAccessSelection> collections)
{
obj.SetNewId();
var objWithCollections = JsonSerializer.Deserialize<GroupWithCollections>(JsonSerializer.Serialize(obj));
@ -102,7 +144,7 @@ public class GroupRepository : Repository<Group, Guid>, IGroupRepository
}
}
public async Task ReplaceAsync(Group obj, IEnumerable<SelectionReadOnly> collections)
public async Task ReplaceAsync(Group obj, IEnumerable<CollectionAccessSelection> collections)
{
var objWithCollections = JsonSerializer.Deserialize<GroupWithCollections>(JsonSerializer.Serialize(obj));
objWithCollections.Collections = collections.ToArrayTVP();
@ -137,4 +179,13 @@ public class GroupRepository : Repository<Group, Guid>, IGroupRepository
commandType: CommandType.StoredProcedure);
}
}
public async Task DeleteManyAsync(IEnumerable<Guid> groupIds)
{
using (var connection = new SqlConnection(ConnectionString))
{
await connection.ExecuteAsync("[dbo].[Group_DeleteByIds]",
new { Ids = groupIds.ToGuidIdArrayTVP() }, commandType: CommandType.StoredProcedure);
}
}
}

View File

@ -142,7 +142,7 @@ public class OrganizationUserRepository : Repository<OrganizationUser, Guid>, IO
}
}
public async Task<Tuple<OrganizationUser, ICollection<SelectionReadOnly>>> GetByIdWithCollectionsAsync(Guid id)
public async Task<Tuple<OrganizationUser, ICollection<CollectionAccessSelection>>> GetByIdWithCollectionsAsync(Guid id)
{
using (var connection = new SqlConnection(ConnectionString))
{
@ -152,8 +152,8 @@ public class OrganizationUserRepository : Repository<OrganizationUser, Guid>, IO
commandType: CommandType.StoredProcedure);
var user = (await results.ReadAsync<OrganizationUser>()).SingleOrDefault();
var collections = (await results.ReadAsync<SelectionReadOnly>()).ToList();
return new Tuple<OrganizationUser, ICollection<SelectionReadOnly>>(user, collections);
var collections = (await results.ReadAsync<CollectionAccessSelection>()).ToList();
return new Tuple<OrganizationUser, ICollection<CollectionAccessSelection>>(user, collections);
}
}
@ -169,7 +169,7 @@ public class OrganizationUserRepository : Repository<OrganizationUser, Guid>, IO
return results.SingleOrDefault();
}
}
public async Task<Tuple<OrganizationUserUserDetails, ICollection<SelectionReadOnly>>>
public async Task<Tuple<OrganizationUserUserDetails, ICollection<CollectionAccessSelection>>>
GetDetailsByIdWithCollectionsAsync(Guid id)
{
using (var connection = new SqlConnection(ConnectionString))
@ -180,12 +180,12 @@ public class OrganizationUserRepository : Repository<OrganizationUser, Guid>, IO
commandType: CommandType.StoredProcedure);
var user = (await results.ReadAsync<OrganizationUserUserDetails>()).SingleOrDefault();
var collections = (await results.ReadAsync<SelectionReadOnly>()).ToList();
return new Tuple<OrganizationUserUserDetails, ICollection<SelectionReadOnly>>(user, collections);
var collections = (await results.ReadAsync<CollectionAccessSelection>()).ToList();
return new Tuple<OrganizationUserUserDetails, ICollection<CollectionAccessSelection>>(user, collections);
}
}
public async Task<ICollection<OrganizationUserUserDetails>> GetManyDetailsByOrganizationAsync(Guid organizationId)
public async Task<ICollection<OrganizationUserUserDetails>> GetManyDetailsByOrganizationAsync(Guid organizationId, bool includeGroups, bool includeCollections)
{
using (var connection = new SqlConnection(ConnectionString))
{
@ -194,7 +194,58 @@ public class OrganizationUserRepository : Repository<OrganizationUser, Guid>, IO
new { OrganizationId = organizationId },
commandType: CommandType.StoredProcedure);
return results.ToList();
List<IGrouping<Guid, GroupUser>> userGroups = null;
List<IGrouping<Guid, CollectionUser>> userCollections = null;
var users = results.ToList();
if (!includeCollections && !includeGroups)
{
return users;
}
var orgUserIds = users.Select(u => u.Id).ToGuidIdArrayTVP();
if (includeGroups)
{
userGroups = (await connection.QueryAsync<GroupUser>(
"[dbo].[GroupUser_ReadByOrganizationUserIds]",
new { OrganizationUserIds = orgUserIds },
commandType: CommandType.StoredProcedure)).GroupBy(u => u.OrganizationUserId).ToList();
}
if (includeCollections)
{
userCollections = (await connection.QueryAsync<CollectionUser>(
"[dbo].[CollectionUser_ReadByOrganizationUserIds]",
new { OrganizationUserIds = orgUserIds },
commandType: CommandType.StoredProcedure)).GroupBy(u => u.OrganizationUserId).ToList();
}
// Map any queried collections and groups to their respective users
foreach (var user in users)
{
if (userGroups != null)
{
user.Groups = userGroups
.FirstOrDefault(u => u.Key == user.Id)?
.Select(ug => ug.GroupId).ToList() ?? new List<Guid>();
}
if (userCollections != null)
{
user.Collections = userCollections
.FirstOrDefault(u => u.Key == user.Id)?
.Select(uc => new CollectionAccessSelection
{
Id = uc.CollectionId,
ReadOnly = uc.ReadOnly,
HidePasswords = uc.HidePasswords
}).ToList() ?? new List<CollectionAccessSelection>();
}
}
return users;
}
}
@ -237,7 +288,7 @@ public class OrganizationUserRepository : Repository<OrganizationUser, Guid>, IO
}
}
public async Task<Guid> CreateAsync(OrganizationUser obj, IEnumerable<SelectionReadOnly> collections)
public async Task<Guid> CreateAsync(OrganizationUser obj, IEnumerable<CollectionAccessSelection> collections)
{
obj.SetNewId();
var objWithCollections = JsonSerializer.Deserialize<OrganizationUserWithCollections>(
@ -255,7 +306,7 @@ public class OrganizationUserRepository : Repository<OrganizationUser, Guid>, IO
return obj.Id;
}
public async Task ReplaceAsync(OrganizationUser obj, IEnumerable<SelectionReadOnly> collections)
public async Task ReplaceAsync(OrganizationUser obj, IEnumerable<CollectionAccessSelection> collections)
{
var objWithCollections = JsonSerializer.Deserialize<OrganizationUserWithCollections>(
JsonSerializer.Serialize(obj));

View File

@ -48,17 +48,20 @@ public class CollectionRepository : Repository<Core.Entities.Collection, Collect
}
}
public async Task CreateAsync(Core.Entities.Collection obj, IEnumerable<SelectionReadOnly> groups)
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);
var availibleGroups = await (from g in dbContext.Groups
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 => availibleGroups.Contains(g.Id))
.Where(g => availableGroups.Contains(g.Id))
.Select(g => new CollectionGroup
{
CollectionId = obj.Id,
@ -67,6 +70,24 @@ public class CollectionRepository : Repository<Core.Entities.Collection, Collect
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();
}
@ -96,41 +117,169 @@ public class CollectionRepository : Repository<Core.Entities.Collection, Collect
}
}
public async Task<Tuple<Core.Entities.Collection, ICollection<SelectionReadOnly>>> GetByIdWithGroupsAsync(Guid 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 collectionGroups = await (from cg in dbContext.CollectionGroups
where cg.CollectionId == id
select cg).ToListAsync();
var selectionReadOnlys = collectionGroups.Select(cg => new SelectionReadOnly
{
Id = cg.GroupId,
ReadOnly = cg.ReadOnly,
HidePasswords = cg.HidePasswords,
}).ToList();
return new Tuple<Core.Entities.Collection, ICollection<SelectionReadOnly>>(collection, selectionReadOnlys);
}
}
public async Task<Tuple<CollectionDetails, ICollection<SelectionReadOnly>>> GetByIdWithGroupsAsync(Guid id, Guid userId)
{
var collection = await GetByIdAsync(id, userId);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = from cg in dbContext.CollectionGroups
var groupQuery = from cg in dbContext.CollectionGroups
where cg.CollectionId.Equals(id)
select new SelectionReadOnly
select new CollectionAccessSelection
{
Id = cg.GroupId,
ReadOnly = cg.ReadOnly,
HidePasswords = cg.HidePasswords,
};
var configurations = await query.ToArrayAsync();
return new Tuple<CollectionDetails, ICollection<SelectionReadOnly>>(collection, configurations);
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;
}
}
@ -174,7 +323,7 @@ public class CollectionRepository : Repository<Core.Entities.Collection, Collect
}
}
public async Task<ICollection<SelectionReadOnly>> GetManyUsersByIdAsync(Guid id)
public async Task<ICollection<CollectionAccessSelection>> GetManyUsersByIdAsync(Guid id)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
@ -183,7 +332,7 @@ public class CollectionRepository : Repository<Core.Entities.Collection, Collect
where cu.CollectionId == id
select cu;
var collectionUsers = await query.ToListAsync();
return collectionUsers.Select(cu => new SelectionReadOnly
return collectionUsers.Select(cu => new CollectionAccessSelection
{
Id = cu.OrganizationUserId,
ReadOnly = cu.ReadOnly,
@ -192,12 +341,89 @@ public class CollectionRepository : Repository<Core.Entities.Collection, Collect
}
}
public async Task ReplaceAsync(Core.Entities.Collection collection, IEnumerable<SelectionReadOnly> groups)
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
@ -255,53 +481,68 @@ public class CollectionRepository : Repository<Core.Entities.Collection, Collect
await dbContext.AddRangeAsync(insert);
dbContext.UpdateRange(update);
dbContext.RemoveRange(delete);
await dbContext.UserBumpAccountRevisionDateByCollectionIdAsync(collection.Id, collection.OrganizationId);
await dbContext.SaveChangesAsync();
}
}
public async Task UpdateUsersAsync(Guid id, IEnumerable<SelectionReadOnly> requestedUsers)
private async Task ReplaceCollectionUsersAsync(DatabaseContext dbContext, Core.Entities.Collection collection, IEnumerable<CollectionAccessSelection> users)
{
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)
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();
foreach (var requestedUser in requestedUsers)
var insert = union.Where(x => x.u == null && usersInOrg.Any(c => x.u.Id == c.Id))
.Select(x => new CollectionUser
{
var existingCollectionUser = existingCollectionUsers.FirstOrDefault(cu => cu.OrganizationUserId == requestedUser.Id);
if (existingCollectionUser == null)
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
{
// This is a brand new entry
dbContext.CollectionUsers.Add(new CollectionUser
{
CollectionId = id,
OrganizationUserId = requestedUser.Id,
HidePasswords = requestedUser.HidePasswords,
ReadOnly = requestedUser.ReadOnly,
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,
});
continue;
}
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();
// 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.AddRangeAsync(insert);
dbContext.UpdateRange(update);
dbContext.RemoveRange(delete);
await dbContext.SaveChangesAsync();
}
}
}

View File

@ -13,7 +13,7 @@ public class GroupRepository : Repository<Core.Entities.Group, Group, Guid>, IGr
: base(serviceScopeFactory, mapper, (DatabaseContext context) => context.Groups)
{ }
public async Task CreateAsync(Core.Entities.Group obj, IEnumerable<SelectionReadOnly> collections)
public async Task CreateAsync(Core.Entities.Group obj, IEnumerable<CollectionAccessSelection> collections)
{
var grp = await base.CreateAsync(obj);
using (var scope = ServiceScopeFactory.CreateScope())
@ -51,7 +51,7 @@ public class GroupRepository : Repository<Core.Entities.Group, Group, Guid>, IGr
}
}
public async Task<Tuple<Core.Entities.Group, ICollection<SelectionReadOnly>>> GetByIdWithCollectionsAsync(Guid id)
public async Task<Tuple<Core.Entities.Group, ICollection<CollectionAccessSelection>>> GetByIdWithCollectionsAsync(Guid id)
{
var grp = await base.GetByIdAsync(id);
using (var scope = ServiceScopeFactory.CreateScope())
@ -61,13 +61,13 @@ public class GroupRepository : Repository<Core.Entities.Group, Group, Guid>, IGr
from cg in dbContext.CollectionGroups
where cg.GroupId == id
select cg).ToListAsync();
var collections = query.Select(c => new SelectionReadOnly
var collections = query.Select(c => new CollectionAccessSelection
{
Id = c.CollectionId,
ReadOnly = c.ReadOnly,
HidePasswords = c.HidePasswords,
}).ToList();
return new Tuple<Core.Entities.Group, ICollection<SelectionReadOnly>>(
return new Tuple<Core.Entities.Group, ICollection<CollectionAccessSelection>>(
grp, collections);
}
}
@ -85,6 +85,49 @@ public class GroupRepository : Repository<Core.Entities.Group, Group, Guid>, IGr
}
}
public async Task<ICollection<Tuple<Core.Entities.Group, ICollection<CollectionAccessSelection>>>>
GetManyWithCollectionsByOrganizationIdAsync(Guid organizationId)
{
var groups = await GetManyByOrganizationIdAsync(organizationId);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = await (
from cg in dbContext.CollectionGroups
where cg.Group.OrganizationId == organizationId
select cg).ToListAsync();
var collections = query.GroupBy(c => c.GroupId).ToList();
return groups.Select(group =>
new Tuple<Core.Entities.Group, ICollection<CollectionAccessSelection>>(
group,
collections
.FirstOrDefault(c => c.Key == group.Id)?
.Select(c => new CollectionAccessSelection
{
Id = c.CollectionId,
HidePasswords = c.HidePasswords,
ReadOnly = c.ReadOnly
}
).ToList() ?? new List<CollectionAccessSelection>())
).ToList();
}
}
public async Task<ICollection<Core.Entities.Group>> GetManyByManyIds(IEnumerable<Guid> groupIds)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = from g in dbContext.Groups
where groupIds.Contains(g.Id)
select g;
var groups = await query.ToListAsync();
return Mapper.Map<List<Core.Entities.Group>>(groups);
}
}
public async Task<ICollection<Core.Entities.GroupUser>> GetManyGroupUsersByOrganizationIdAsync(Guid organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
@ -129,7 +172,7 @@ public class GroupRepository : Repository<Core.Entities.Group, Group, Guid>, IGr
}
}
public async Task ReplaceAsync(Core.Entities.Group group, IEnumerable<SelectionReadOnly> requestedCollections)
public async Task ReplaceAsync(Core.Entities.Group group, IEnumerable<CollectionAccessSelection> requestedCollections)
{
await base.ReplaceAsync(group);
using (var scope = ServiceScopeFactory.CreateScope())
@ -204,4 +247,23 @@ public class GroupRepository : Repository<Core.Entities.Group, Group, Guid>, IGr
await dbContext.SaveChangesAsync();
}
}
public async Task DeleteManyAsync(IEnumerable<Guid> groupIds)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var entities = await dbContext.Groups
.Where(g => groupIds.Contains(g.Id))
.ToListAsync();
dbContext.Groups.RemoveRange(entities);
await dbContext.SaveChangesAsync();
foreach (var group in entities.GroupBy(g => g.Organization.Id))
{
await dbContext.UserBumpAccountRevisionDateByOrganizationIdAsync(group.Key);
}
}
}
}

View File

@ -16,7 +16,7 @@ public class OrganizationUserRepository : Repository<Core.Entities.OrganizationU
: base(serviceScopeFactory, mapper, (DatabaseContext context) => context.OrganizationUsers)
{ }
public async Task<Guid> CreateAsync(Core.Entities.OrganizationUser obj, IEnumerable<SelectionReadOnly> collections)
public async Task<Guid> CreateAsync(Core.Entities.OrganizationUser obj, IEnumerable<CollectionAccessSelection> collections)
{
var organizationUser = await base.CreateAsync(obj);
using (var scope = ServiceScopeFactory.CreateScope())
@ -123,7 +123,7 @@ public class OrganizationUserRepository : Repository<Core.Entities.OrganizationU
}
}
public async Task<Tuple<Core.Entities.OrganizationUser, ICollection<SelectionReadOnly>>> GetByIdWithCollectionsAsync(Guid id)
public async Task<Tuple<Core.Entities.OrganizationUser, ICollection<CollectionAccessSelection>>> GetByIdWithCollectionsAsync(Guid id)
{
var organizationUser = await base.GetByIdAsync(id);
using (var scope = ServiceScopeFactory.CreateScope())
@ -136,13 +136,13 @@ public class OrganizationUserRepository : Repository<Core.Entities.OrganizationU
where !ou.AccessAll &&
ou.Id == id
select cu).ToListAsync();
var collections = query.Select(cu => new SelectionReadOnly
var collections = query.Select(cu => new CollectionAccessSelection
{
Id = cu.CollectionId,
ReadOnly = cu.ReadOnly,
HidePasswords = cu.HidePasswords,
});
return new Tuple<Core.Entities.OrganizationUser, ICollection<SelectionReadOnly>>(
return new Tuple<Core.Entities.OrganizationUser, ICollection<CollectionAccessSelection>>(
organizationUser, collections.ToList());
}
}
@ -214,7 +214,7 @@ public class OrganizationUserRepository : Repository<Core.Entities.OrganizationU
}
}
public async Task<Tuple<OrganizationUserUserDetails, ICollection<SelectionReadOnly>>> GetDetailsByIdWithCollectionsAsync(Guid id)
public async Task<Tuple<OrganizationUserUserDetails, ICollection<CollectionAccessSelection>>> GetDetailsByIdWithCollectionsAsync(Guid id)
{
var organizationUserUserDetails = await GetDetailsByIdAsync(id);
using (var scope = ServiceScopeFactory.CreateScope())
@ -224,13 +224,13 @@ public class OrganizationUserRepository : Repository<Core.Entities.OrganizationU
join cu in dbContext.CollectionUsers on ou.Id equals cu.OrganizationUserId
where !ou.AccessAll && ou.Id == id
select cu;
var collections = await query.Select(cu => new SelectionReadOnly
var collections = await query.Select(cu => new CollectionAccessSelection
{
Id = cu.CollectionId,
ReadOnly = cu.ReadOnly,
HidePasswords = cu.HidePasswords,
}).ToListAsync();
return new Tuple<OrganizationUserUserDetails, ICollection<SelectionReadOnly>>(organizationUserUserDetails, collections);
return new Tuple<OrganizationUserUserDetails, ICollection<CollectionAccessSelection>>(organizationUserUserDetails, collections);
}
}
@ -299,16 +299,67 @@ public class OrganizationUserRepository : Repository<Core.Entities.OrganizationU
}
}
public async Task<ICollection<OrganizationUserUserDetails>> GetManyDetailsByOrganizationAsync(Guid organizationId)
public async Task<ICollection<OrganizationUserUserDetails>> GetManyDetailsByOrganizationAsync(Guid organizationId, bool includeGroups, bool includeCollections)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var view = new OrganizationUserUserDetailsViewQuery();
var query = from ou in view.Run(dbContext)
var users = await (from ou in view.Run(dbContext)
where ou.OrganizationId == organizationId
select ou;
return await query.ToListAsync();
select ou).ToListAsync();
if (!includeCollections && !includeGroups)
{
return users;
}
List<IGrouping<Guid, GroupUser>> groups = null;
List<IGrouping<Guid, CollectionUser>> collections = null;
var userIds = users.Select(u => u.Id);
var userIdEntities = dbContext.OrganizationUsers.Where(x => userIds.Contains(x.Id));
// Query groups/collections separately to avoid cartesian explosion
if (includeGroups)
{
groups = (await (from gu in dbContext.GroupUsers
join ou in userIdEntities on gu.OrganizationUserId equals ou.Id
select gu).ToListAsync())
.GroupBy(g => g.OrganizationUserId).ToList();
}
if (includeCollections)
{
collections = (await (from cu in dbContext.CollectionUsers
join ou in userIdEntities on cu.OrganizationUserId equals ou.Id
select cu).ToListAsync())
.GroupBy(c => c.OrganizationUserId).ToList();
}
// Map any queried collections and groups to their respective users
foreach (var user in users)
{
if (groups != null)
{
user.Groups = groups
.FirstOrDefault(g => g.Key == user.Id)?
.Select(g => g.GroupId).ToList() ?? new List<Guid>();
}
if (collections != null)
{
user.Collections = collections
.FirstOrDefault(c => c.Key == user.Id)?
.Select(cu => new CollectionAccessSelection
{
Id = cu.CollectionId,
ReadOnly = cu.ReadOnly,
HidePasswords = cu.HidePasswords
}).ToList() ?? new List<CollectionAccessSelection>();
}
}
return users;
}
}
@ -360,7 +411,7 @@ public class OrganizationUserRepository : Repository<Core.Entities.OrganizationU
}
}
public async Task ReplaceAsync(Core.Entities.OrganizationUser obj, IEnumerable<SelectionReadOnly> requestedCollections)
public async Task ReplaceAsync(Core.Entities.OrganizationUser obj, IEnumerable<CollectionAccessSelection> requestedCollections)
{
await ReplaceAsync(obj);
using (var scope = ServiceScopeFactory.CreateScope())

View File

@ -120,8 +120,11 @@
<Build Include="dbo\Stored Procedures\CollectionCipher_UpdateCollections.sql" />
<Build Include="dbo\Stored Procedures\CollectionCipher_UpdateCollectionsAdmin.sql" />
<Build Include="dbo\Stored Procedures\CollectionCipher_UpdateCollectionsForCiphers.sql" />
<Build Include="dbo\Stored Procedures\CollectionGroup_ReadByCollectionId.sql" />
<Build Include="dbo\Stored Procedures\CollectionGroup_ReadByOrganizationId.sql" />
<Build Include="dbo\Stored Procedures\CollectionUser_Delete.sql" />
<Build Include="dbo\Stored Procedures\CollectionUser_ReadByCollectionId.sql" />
<Build Include="dbo\Stored Procedures\CollectionUser_ReadByOrganizationUserIds.sql" />
<Build Include="dbo\Stored Procedures\CollectionUser_UpdateUsers.sql" />
<Build Include="dbo\Stored Procedures\Collection_Create.sql" />
<Build Include="dbo\Stored Procedures\Collection_CreateWithGroups.sql" />
@ -131,6 +134,8 @@
<Build Include="dbo\Stored Procedures\Collection_ReadByOrganizationId.sql" />
<Build Include="dbo\Stored Procedures\Collection_ReadByUserId.sql" />
<Build Include="dbo\Stored Procedures\Collection_ReadCountByOrganizationId.sql" />
<Build Include="dbo\Stored Procedures\Collection_ReadWithGroupsAndUsersById.sql" />
<Build Include="dbo\Stored Procedures\Collection_ReadWithGroupsAndUsersByIdUserId.sql" />
<Build Include="dbo\Stored Procedures\Collection_ReadWithGroupsById.sql" />
<Build Include="dbo\Stored Procedures\Collection_ReadWithGroupsByIdUserId.sql" />
<Build Include="dbo\Stored Procedures\Collection_Update.sql" />
@ -174,6 +179,7 @@
<Build Include="dbo\Stored Procedures\Grant_Save.sql" />
<Build Include="dbo\Stored Procedures\GroupUser_Delete.sql" />
<Build Include="dbo\Stored Procedures\GroupUser_ReadByOrganizationId.sql" />
<Build Include="dbo\Stored Procedures\GroupUser_ReadByOrganizationUserIds.sql" />
<Build Include="dbo\Stored Procedures\GroupUser_ReadGroupIdsByOrganizationUserId.sql" />
<Build Include="dbo\Stored Procedures\GroupUser_ReadOrganizationUserIdsByGroupId.sql" />
<Build Include="dbo\Stored Procedures\GroupUser_UpdateGroups.sql" />
@ -181,9 +187,12 @@
<Build Include="dbo\Stored Procedures\Group_Create.sql" />
<Build Include="dbo\Stored Procedures\Group_CreateWithCollections.sql" />
<Build Include="dbo\Stored Procedures\Group_DeleteById.sql" />
<Build Include="dbo\Stored Procedures\Group_DeleteByIds.sql" />
<Build Include="dbo\Stored Procedures\Group_ReadById.sql" />
<Build Include="dbo\Stored Procedures\Group_ReadByIds.sql" />
<Build Include="dbo\Stored Procedures\Group_ReadByOrganizationId.sql" />
<Build Include="dbo\Stored Procedures\Group_ReadWithCollectionsById.sql" />
<Build Include="dbo\Stored Procedures\Group_ReadWithCollectionsByOrganizationId.sql" />
<Build Include="dbo\Stored Procedures\Group_Update.sql" />
<Build Include="dbo\Stored Procedures\Group_UpdateWithCollections.sql" />
<Build Include="dbo\Stored Procedures\Installation_Create.sql" />
@ -330,6 +339,7 @@
<Build Include="dbo\Stored Procedures\User_BumpAccountRevisionDateByCollectionId.sql" />
<Build Include="dbo\Stored Procedures\User_BumpAccountRevisionDateByEmergencyAccessGranteeId.sql" />
<Build Include="dbo\Stored Procedures\User_BumpAccountRevisionDateByOrganizationId.sql" />
<Build Include="dbo\Stored Procedures\User_BumpAccountRevisionDateByOrganizationIds.sql" />
<Build Include="dbo\Stored Procedures\User_BumpAccountRevisionDateByOrganizationUserId.sql" />
<Build Include="dbo\Stored Procedures\User_BumpAccountRevisionDateByOrganizationUserIds.sql" />
<Build Include="dbo\Stored Procedures\User_BumpAccountRevisionDateByProviderId.sql" />

View File

@ -0,0 +1,15 @@
CREATE PROCEDURE [dbo].[CollectionGroup_ReadByCollectionId]
@CollectionId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
[GroupId] [Id],
[ReadOnly],
[HidePasswords]
FROM
[dbo].[CollectionGroup]
WHERE
[CollectionId] = @CollectionId
END

View File

@ -0,0 +1,15 @@
CREATE PROCEDURE [dbo].[CollectionGroup_ReadByOrganizationId]
@OrganizationId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
CG.*
FROM
[dbo].[CollectionGroup] CG
INNER JOIN
[dbo].[Group] G ON G.[Id] = CG.[GroupId]
WHERE
G.[OrganizationId] = @OrganizationId
END

View File

@ -0,0 +1,16 @@
CREATE PROCEDURE [dbo].[CollectionUser_ReadByOrganizationId]
@OrganizationId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
CU.*
FROM
[dbo].[CollectionUser] CU
INNER JOIN
[dbo].[OrganizationUser] OU ON OU.[Id] = CU.[OrganizationUserId]
WHERE
OU.[OrganizationId] = @OrganizationId
END

View File

@ -0,0 +1,15 @@
CREATE PROCEDURE [dbo].[CollectionUser_ReadByOrganizationUserIds]
@OrganizationUserIds [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
SELECT
CU.*
FROM
[dbo].[OrganizationUser] OU
INNER JOIN
[dbo].[CollectionUser] CU ON OU.[AccessAll] = 0 AND CU.[OrganizationUserId] = OU.[Id]
INNER JOIN
@OrganizationUserIds OUI ON OUI.[Id] = OU.[Id]
END

View File

@ -0,0 +1,69 @@
CREATE PROCEDURE [dbo].[Collection_CreateWithGroupsAndUsers]
@Id UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Name VARCHAR(MAX),
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@Groups AS [dbo].[SelectionReadOnlyArray] READONLY,
@Users AS [dbo].[SelectionReadOnlyArray] READONLY
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_Create] @Id, @OrganizationId, @Name, @ExternalId, @CreationDate, @RevisionDate
-- Groups
;WITH [AvailableGroupsCTE] AS(
SELECT
[Id]
FROM
[dbo].[Group]
WHERE
[OrganizationId] = @OrganizationId
)
INSERT INTO [dbo].[CollectionGroup]
(
[CollectionId],
[GroupId],
[ReadOnly],
[HidePasswords]
)
SELECT
@Id,
[Id],
[ReadOnly],
[HidePasswords]
FROM
@Groups
WHERE
[Id] IN (SELECT [Id] FROM [AvailableGroupsCTE])
-- Users
;WITH [AvailableUsersCTE] AS(
SELECT
[Id]
FROM
[dbo].[OrganizationUser]
WHERE
[OrganizationId] = @OrganizationId
)
INSERT INTO [dbo].[CollectionUser]
(
[CollectionId],
[OrganizationUserId],
[ReadOnly],
[HidePasswords]
)
SELECT
@Id,
[Id],
[ReadOnly],
[HidePasswords]
FROM
@Users
WHERE
[Id] IN (SELECT [Id] FROM [AvailableUsersCTE])
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationId] @OrganizationId
END

View File

@ -0,0 +1,54 @@
CREATE PROCEDURE [dbo].[Collection_DeleteByIds]
@Ids AS [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
DECLARE @OrgIds AS [dbo].[GuidIdArray]
INSERT INTO @OrgIds (Id)
SELECT
[OrganizationId]
FROM
[dbo].[Collection]
WHERE
[Id] in (SELECT [Id] FROM @Ids)
GROUP BY
[OrganizationId]
DECLARE @BatchSize INT = 100
-- Delete Collection Groups
WHILE @BatchSize > 0
BEGIN
BEGIN TRANSACTION CollectionGroup_DeleteMany
DELETE TOP(@BatchSize)
FROM
[dbo].[CollectionGroup]
WHERE
[CollectionId] IN (SELECT [Id] FROM @Ids)
SET @BatchSize = @@ROWCOUNT
COMMIT TRANSACTION CollectionGroup_DeleteMany
END
-- Reset batch size
SET @BatchSize = 100
-- Delete Collections
WHILE @BatchSize > 0
BEGIN
BEGIN TRANSACTION Collection_DeleteMany
DELETE TOP(@BatchSize)
FROM
[dbo].[Collection]
WHERE
[Id] IN (SELECT [Id] FROM @Ids)
SET @BatchSize = @@ROWCOUNT
COMMIT TRANSACTION CollectionGroup_DeleteMany
END
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationIds] @OrgIds
END

View File

@ -0,0 +1,18 @@
CREATE PROCEDURE [dbo].[Collection_ReadByIds]
@Ids AS [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
IF (SELECT COUNT(1) FROM @Ids) < 1
BEGIN
RETURN(-1)
END
SELECT
*
FROM
[dbo].[Collection]
WHERE
[Id] IN (SELECT [Id] FROM @Ids)
END

View File

@ -0,0 +1,12 @@
CREATE PROCEDURE [dbo].[Collection_ReadWithGroupsAndUsersById]
@Id UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_ReadById] @Id
EXEC [dbo].[CollectionGroup_ReadByCollectionId] @Id
EXEC [dbo].[CollectionUser_ReadByCollectionId] @Id
END

View File

@ -0,0 +1,13 @@
CREATE PROCEDURE [dbo].[Collection_ReadWithGroupsAndUsersByIdUserId]
@Id UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_ReadByIdUserId] @Id, @UserId
EXEC [dbo].[CollectionGroup_ReadByCollectionId] @Id
EXEC [dbo].[CollectionUser_ReadByCollectionId] @Id
END

View File

@ -0,0 +1,13 @@
CREATE PROCEDURE [dbo].[Collection_ReadWithGroupsAndUsersByOrganizationId]
@OrganizationId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_ReadByOrganizationId] @OrganizationId
EXEC [dbo].[CollectionGroup_ReadByOrganizationId] @OrganizationId
EXEC [dbo].[CollectionUser_ReadByOrganizationId] @OrganizationId
END

View File

@ -0,0 +1,38 @@
CREATE PROCEDURE [dbo].[Collection_ReadWithGroupsAndUsersByUserId]
@UserId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
DECLARE @TempUserCollections TABLE(
Id UNIQUEIDENTIFIER,
OrganizationId UNIQUEIDENTIFIER,
Name VARCHAR(MAX),
CreationDate DATETIME2(7),
RevisionDate DATETIME2(7),
ExternalId NVARCHAR(300),
ReadOnly BIT,
HidePasswords BIT)
INSERT INTO @TempUserCollections EXEC [dbo].[Collection_ReadByUserId] @UserId
SELECT
*
FROM
@TempUserCollections C
SELECT
CG.*
FROM
[dbo].[CollectionGroup] CG
INNER JOIN
@TempUserCollections C ON C.[Id] = CG.[CollectionId]
SELECT
CU.*
FROM
[dbo].[CollectionUser] CU
INNER JOIN
@TempUserCollections C ON C.[Id] = CU.[CollectionId]
END

View File

@ -0,0 +1,89 @@
CREATE PROCEDURE [dbo].[Collection_UpdateWithGroupsAndUsers]
@Id UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Name VARCHAR(MAX),
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@Groups AS [dbo].[SelectionReadOnlyArray] READONLY,
@Users AS [dbo].[SelectionReadOnlyArray] READONLY
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_Update] @Id, @OrganizationId, @Name, @ExternalId, @CreationDate, @RevisionDate
-- Groups
;WITH [AvailableGroupsCTE] AS(
SELECT
Id
FROM
[dbo].[Group]
WHERE
OrganizationId = @OrganizationId
)
MERGE
[dbo].[CollectionGroup] AS [Target]
USING
@Groups AS [Source]
ON
[Target].[CollectionId] = @Id
AND [Target].[GroupId] = [Source].[Id]
WHEN NOT MATCHED BY TARGET
AND [Source].[Id] IN (SELECT [Id] FROM [AvailableGroupsCTE]) THEN
INSERT VALUES
(
@Id,
[Source].[Id],
[Source].[ReadOnly],
[Source].[HidePasswords]
)
WHEN MATCHED AND (
[Target].[ReadOnly] != [Source].[ReadOnly]
OR [Target].[HidePasswords] != [Source].[HidePasswords]
) THEN
UPDATE SET [Target].[ReadOnly] = [Source].[ReadOnly],
[Target].[HidePasswords] = [Source].[HidePasswords]
WHEN NOT MATCHED BY SOURCE
AND [Target].[CollectionId] = @Id THEN
DELETE
;
-- Users
;WITH [AvailableGroupsCTE] AS(
SELECT
Id
FROM
[dbo].[OrganizationUser]
WHERE
OrganizationId = @OrganizationId
)
MERGE
[dbo].[CollectionUser] AS [Target]
USING
@Users AS [Source]
ON
[Target].[CollectionId] = @Id
AND [Target].[OrganizationUserId] = [Source].[Id]
WHEN NOT MATCHED BY TARGET
AND [Source].[Id] IN (SELECT [Id] FROM [AvailableGroupsCTE]) THEN
INSERT VALUES
(
@Id,
[Source].[Id],
[Source].[ReadOnly],
[Source].[HidePasswords]
)
WHEN MATCHED AND (
[Target].[ReadOnly] != [Source].[ReadOnly]
OR [Target].[HidePasswords] != [Source].[HidePasswords]
) THEN
UPDATE SET [Target].[ReadOnly] = [Source].[ReadOnly],
[Target].[HidePasswords] = [Source].[HidePasswords]
WHEN NOT MATCHED BY SOURCE
AND [Target].[CollectionId] = @Id THEN
DELETE
;
EXEC [dbo].[User_BumpAccountRevisionDateByCollectionId] @Id, @OrganizationId
END

View File

@ -0,0 +1,13 @@
CREATE PROCEDURE [dbo].[GroupUser_ReadByOrganizationUserIds]
@OrganizationUserIds [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
SELECT
GU.*
FROM
[dbo].[GroupUser] GU
INNER JOIN
@OrganizationUserIds OUI ON OUI.[Id] = GU.[OrganizationUserId]
END

View File

@ -0,0 +1,35 @@
CREATE PROCEDURE [dbo].[Group_DeleteByIds]
@Ids AS [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
DECLARE @OrgIds AS [dbo].[GuidIdArray]
INSERT INTO @OrgIds (Id)
SELECT
[OrganizationId]
FROM
[dbo].[Group]
WHERE
[Id] in (SELECT [Id] FROM @Ids)
GROUP BY
[OrganizationId]
DECLARE @BatchSize INT = 100
WHILE @BatchSize > 0
BEGIN
BEGIN TRANSACTION Group_DeleteMany_Groups
DELETE TOP(@BatchSize)
FROM
[dbo].[Group]
WHERE
[Id] IN (SELECT [Id] FROM @Ids)
SET @BatchSize = @@ROWCOUNT
COMMIT TRANSACTION Group_DeleteMany_Groups
END
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationIds] @OrgIds
END

View File

@ -0,0 +1,18 @@
CREATE PROCEDURE [dbo].[Group_ReadByIds]
@Ids AS [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
IF (SELECT COUNT(1) FROM @Ids) < 1
BEGIN
RETURN(-1)
END
SELECT
*
FROM
[dbo].[Group]
WHERE
[Id] IN (SELECT [Id] FROM @Ids)
END

View File

@ -0,0 +1,10 @@
CREATE PROCEDURE [dbo].[Group_ReadWithCollectionsByOrganizationId]
@OrganizationId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Group_ReadByOrganizationId] @OrganizationId
EXEC [dbo].[CollectionGroup_ReadByOrganizationId] @OrganizationId
END

View File

@ -0,0 +1,18 @@
CREATE PROCEDURE [dbo].[User_BumpAccountRevisionDateByOrganizationIds]
@OrganizationIds AS [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
UPDATE
U
SET
U.[AccountRevisionDate] = GETUTCDATE()
FROM
[dbo].[User] U
INNER JOIN
[dbo].[OrganizationUser] OU ON OU.[UserId] = U.[Id]
WHERE
OU.[OrganizationId] IN (SELECT [Id] FROM @OrganizationIds)
AND OU.[Status] = 2 -- Confirmed
END

View File

@ -0,0 +1,2 @@
-- Created 2022-11
-- DELETE FILE

View File

@ -0,0 +1,2 @@
-- Created 2022-11
-- DELETE FILE

View File

@ -0,0 +1,2 @@
-- Created 2022-11
-- DELETE FILE

View File

@ -0,0 +1,2 @@
-- Created 2022-11
-- DELETE FILE

View File

@ -4,6 +4,7 @@ using Bit.Core.Context;
using Bit.Core.Entities;
using Bit.Core.Exceptions;
using Bit.Core.Models.Data;
using Bit.Core.OrganizationFeatures.OrganizationCollections.Interfaces;
using Bit.Core.Repositories;
using Bit.Core.Services;
using Bit.Test.Common.AutoFixture;
@ -38,7 +39,7 @@ public class CollectionsControllerTests
await sutProvider.GetDependency<ICollectionService>()
.Received(1)
.SaveAsync(Arg.Any<Collection>(), Arg.Any<IEnumerable<SelectionReadOnly>>(), null);
.SaveAsync(Arg.Any<Collection>(), Arg.Any<IEnumerable<CollectionAccessSelection>>(), null);
}
[Theory, BitAutoData]
@ -85,4 +86,168 @@ public class CollectionsControllerTests
_ = await Assert.ThrowsAsync<NotFoundException>(async () => await sutProvider.Sut.Put(orgId, collectionId, collectionRequest));
}
[Theory, BitAutoData]
public async Task GetOrganizationCollectionsWithGroups_NoManagerPermissions_ThrowsNotFound(Organization organization, SutProvider<CollectionsController> sutProvider)
{
sutProvider.GetDependency<ICurrentContext>().ViewAssignedCollections(organization.Id).Returns(false);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.GetManyWithDetails(organization.Id));
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().GetManyByOrganizationIdWithAccessAsync(default);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().GetManyByUserIdWithAccessAsync(default, default);
}
[Theory, BitAutoData]
public async Task GetOrganizationCollectionsWithGroups_AdminPermissions_GetsAllCollections(Organization organization, User user, SutProvider<CollectionsController> sutProvider)
{
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(user.Id);
sutProvider.GetDependency<ICurrentContext>().ViewAllCollections(organization.Id).Returns(true);
sutProvider.GetDependency<ICurrentContext>().OrganizationAdmin(organization.Id).Returns(true);
await sutProvider.Sut.GetManyWithDetails(organization.Id);
await sutProvider.GetDependency<ICollectionRepository>().Received().GetManyByOrganizationIdWithAccessAsync(organization.Id);
await sutProvider.GetDependency<ICollectionRepository>().Received().GetManyByUserIdWithAccessAsync(user.Id, organization.Id);
}
[Theory, BitAutoData]
public async Task GetOrganizationCollectionsWithGroups_MissingViewAllPermissions_GetsAssignedCollections(Organization organization, User user, SutProvider<CollectionsController> sutProvider)
{
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(user.Id);
sutProvider.GetDependency<ICurrentContext>().ViewAssignedCollections(organization.Id).Returns(true);
sutProvider.GetDependency<ICurrentContext>().OrganizationManager(organization.Id).Returns(true);
await sutProvider.Sut.GetManyWithDetails(organization.Id);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().GetManyByOrganizationIdWithAccessAsync(default);
await sutProvider.GetDependency<ICollectionRepository>().Received().GetManyByUserIdWithAccessAsync(user.Id, organization.Id);
}
[Theory, BitAutoData]
public async Task GetOrganizationCollectionsWithGroups_CustomUserWithManagerPermissions_GetsAssignedCollections(Organization organization, User user, SutProvider<CollectionsController> sutProvider)
{
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(user.Id);
sutProvider.GetDependency<ICurrentContext>().ViewAssignedCollections(organization.Id).Returns(true);
sutProvider.GetDependency<ICurrentContext>().EditAssignedCollections(organization.Id).Returns(true);
await sutProvider.Sut.GetManyWithDetails(organization.Id);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().GetManyByOrganizationIdWithAccessAsync(default);
await sutProvider.GetDependency<ICollectionRepository>().Received().GetManyByUserIdWithAccessAsync(user.Id, organization.Id);
}
[Theory, BitAutoData]
public async Task DeleteMany_Success(Guid orgId, User user, Collection collection1, Collection collection2, SutProvider<CollectionsController> sutProvider)
{
// Arrange
var model = new CollectionBulkDeleteRequestModel
{
Ids = new[] { collection1.Id.ToString(), collection2.Id.ToString() },
OrganizationId = orgId.ToString()
};
var collections = new List<CollectionDetails>
{
new CollectionDetails
{
Id = collection1.Id,
OrganizationId = orgId,
},
new CollectionDetails
{
Id = collection2.Id,
OrganizationId = orgId,
},
};
sutProvider.GetDependency<ICurrentContext>()
.DeleteAssignedCollections(orgId)
.Returns(true);
sutProvider.GetDependency<ICurrentContext>()
.UserId
.Returns(user.Id);
sutProvider.GetDependency<ICollectionRepository>()
.GetManyByUserIdAsync(user.Id)
.Returns(collections);
// Act
await sutProvider.Sut.DeleteMany(model);
// Assert
await sutProvider.GetDependency<IDeleteCollectionCommand>()
.Received(1)
.DeleteManyAsync(Arg.Is<IEnumerable<Collection>>(coll => coll.Select(c => c.Id).SequenceEqual(collections.Select(c => c.Id))));
}
[Theory, BitAutoData]
public async Task DeleteMany_CanNotDeleteAssignedCollection_ThrowsNotFound(Guid orgId, Collection collection1, Collection collection2, SutProvider<CollectionsController> sutProvider)
{
// Arrange
var model = new CollectionBulkDeleteRequestModel
{
Ids = new[] { collection1.Id.ToString(), collection2.Id.ToString() },
OrganizationId = orgId.ToString()
};
sutProvider.GetDependency<ICurrentContext>()
.DeleteAssignedCollections(orgId)
.Returns(false);
// Assert
await Assert.ThrowsAsync<NotFoundException>(() =>
sutProvider.Sut.DeleteMany(model));
await sutProvider.GetDependency<IDeleteCollectionCommand>()
.DidNotReceiveWithAnyArgs()
.DeleteManyAsync((IEnumerable<Collection>)default);
}
[Theory, BitAutoData]
public async Task DeleteMany_UserCanNotAccessCollections_FiltersOutInvalid(Guid orgId, User user, Collection collection1, Collection collection2, SutProvider<CollectionsController> sutProvider)
{
// Arrange
var model = new CollectionBulkDeleteRequestModel
{
Ids = new[] { collection1.Id.ToString(), collection2.Id.ToString() },
OrganizationId = orgId.ToString()
};
var collections = new List<CollectionDetails>
{
new CollectionDetails
{
Id = collection2.Id,
OrganizationId = orgId,
},
};
sutProvider.GetDependency<ICurrentContext>()
.DeleteAssignedCollections(orgId)
.Returns(true);
sutProvider.GetDependency<ICurrentContext>()
.UserId
.Returns(user.Id);
sutProvider.GetDependency<ICollectionRepository>()
.GetManyByUserIdAsync(user.Id)
.Returns(collections);
// Act
await sutProvider.Sut.DeleteMany(model);
// Assert
await sutProvider.GetDependency<IDeleteCollectionCommand>()
.Received(1)
.DeleteManyAsync(Arg.Is<IEnumerable<Collection>>(coll => coll.Select(c => c.Id).SequenceEqual(collections.Select(c => c.Id))));
}
}

View File

@ -31,7 +31,8 @@ public class GroupsControllerTests
g.OrganizationId == organization.Id && g.Name == groupRequestModel.Name &&
g.AccessAll == groupRequestModel.AccessAll && g.ExternalId == groupRequestModel.ExternalId),
organization,
Arg.Any<IEnumerable<SelectionReadOnly>>());
Arg.Any<IEnumerable<CollectionAccessSelection>>(),
Arg.Any<IEnumerable<Guid>>());
Assert.NotNull(response.Id);
Assert.Equal(groupRequestModel.Name, response.Name);
@ -58,7 +59,8 @@ public class GroupsControllerTests
g.OrganizationId == organization.Id && g.Name == groupRequestModel.Name &&
g.AccessAll == groupRequestModel.AccessAll && g.ExternalId == groupRequestModel.ExternalId),
Arg.Is<Organization>(o => o.Id == organization.Id),
Arg.Any<IEnumerable<SelectionReadOnly>>());
Arg.Any<IEnumerable<CollectionAccessSelection>>(),
Arg.Any<IEnumerable<Guid>>());
Assert.NotNull(response.Id);
Assert.Equal(groupRequestModel.Name, response.Name);

View File

@ -33,7 +33,7 @@ public class GroupsControllerTests
g.OrganizationId == organization.Id && g.Name == groupRequestModel.Name &&
g.AccessAll == groupRequestModel.AccessAll && g.ExternalId == groupRequestModel.ExternalId),
organization,
Arg.Any<IEnumerable<SelectionReadOnly>>());
Arg.Any<IEnumerable<CollectionAccessSelection>>());
Assert.Equal(groupRequestModel.Name, responseValue.Name);
Assert.Equal(groupRequestModel.AccessAll, responseValue.AccessAll);
@ -58,7 +58,7 @@ public class GroupsControllerTests
g.OrganizationId == organization.Id && g.Name == groupRequestModel.Name &&
g.AccessAll == groupRequestModel.AccessAll && g.ExternalId == groupRequestModel.ExternalId),
Arg.Is<Organization>(o => o.Id == organization.Id),
Arg.Any<IEnumerable<SelectionReadOnly>>());
Arg.Any<IEnumerable<CollectionAccessSelection>>());
Assert.Equal(groupRequestModel.Name, responseValue.Name);
Assert.Equal(groupRequestModel.AccessAll, responseValue.AccessAll);

View File

@ -31,7 +31,7 @@ public class CreateGroupCommandTests
}
[Theory, OrganizationCustomize(UseGroups = true), BitAutoData]
public async Task CreateGroup_WithCollections_Success(SutProvider<CreateGroupCommand> sutProvider, Organization organization, Group group, List<SelectionReadOnly> collections)
public async Task CreateGroup_WithCollections_Success(SutProvider<CreateGroupCommand> sutProvider, Organization organization, Group group, List<CollectionAccessSelection> collections)
{
await sutProvider.Sut.CreateGroupAsync(group, organization, collections);

View File

@ -4,6 +4,7 @@ using Bit.Core.Exceptions;
using Bit.Core.OrganizationFeatures.Groups;
using Bit.Core.Repositories;
using Bit.Core.Services;
using Bit.Core.Test.AutoFixture.OrganizationFixtures;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using NSubstitute;
@ -52,7 +53,8 @@ public class DeleteGroupCommandTests
[Theory]
[BitAutoData]
public async Task DeleteGroup_WithEventSystemUser_Success(SutProvider<DeleteGroupCommand> sutProvider, Group group, EventSystemUser eventSystemUser)
public async Task DeleteGroup_WithEventSystemUser_Success(SutProvider<DeleteGroupCommand> sutProvider, Group group,
EventSystemUser eventSystemUser)
{
sutProvider.GetDependency<IGroupRepository>()
.GetByIdAsync(group.Id)
@ -61,6 +63,38 @@ public class DeleteGroupCommandTests
await sutProvider.Sut.DeleteGroupAsync(group.OrganizationId, group.Id, eventSystemUser);
await sutProvider.GetDependency<IGroupRepository>().Received(1).DeleteAsync(group);
await sutProvider.GetDependency<IEventService>().Received(1).LogGroupEventAsync(group, Core.Enums.EventType.Group_Deleted, eventSystemUser);
await sutProvider.GetDependency<IEventService>().Received(1)
.LogGroupEventAsync(group, Core.Enums.EventType.Group_Deleted, eventSystemUser);
}
[Theory, BitAutoData]
public async Task DeleteAsync_DeletesGroup(Group group, SutProvider<DeleteGroupCommand> sutProvider)
{
// Act
await sutProvider.Sut.DeleteAsync(group);
// Assert
await sutProvider.GetDependency<IGroupRepository>().Received().DeleteAsync(group);
await sutProvider.GetDependency<IEventService>().Received().LogGroupEventAsync(group, EventType.Group_Deleted);
}
[Theory, BitAutoData]
[OrganizationCustomize]
public async Task DeleteManyAsync_DeletesManyGroup(Group group, Group group2, SutProvider<DeleteGroupCommand> sutProvider)
{
// Arrange
var groups = new[] { group, group2 };
// Act
await sutProvider.Sut.DeleteManyAsync(groups);
// Assert
await sutProvider.GetDependency<IGroupRepository>().Received()
.DeleteManyAsync(Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(groups.Select(g => g.Id))));
await sutProvider.GetDependency<IEventService>().Received().LogGroupEventsAsync(
Arg.Is<IEnumerable<(Group, EventType, EventSystemUser?, DateTime?)>>(a =>
a.All(g => groups.Contains(g.Item1) && g.Item2 == EventType.Group_Deleted))
);
}
}

View File

@ -28,7 +28,7 @@ public class UpdateGroupCommandTests
}
[Theory, OrganizationCustomize(UseGroups = true), BitAutoData]
public async Task UpdateGroup_WithCollections_Success(SutProvider<UpdateGroupCommand> sutProvider, Group group, Organization organization, List<SelectionReadOnly> collections)
public async Task UpdateGroup_WithCollections_Success(SutProvider<UpdateGroupCommand> sutProvider, Group group, Organization organization, List<CollectionAccessSelection> collections)
{
await sutProvider.Sut.UpdateGroupAsync(group, organization, collections);

View File

@ -0,0 +1,55 @@

using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.OrganizationFeatures.OrganizationCollections;
using Bit.Core.Repositories;
using Bit.Core.Services;
using Bit.Core.Test.AutoFixture.OrganizationFixtures;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.OrganizationFeatures.OrganizationConnections;
[SutProviderCustomize]
public class DeleteCollectionCommandTests
{
[Theory, BitAutoData]
[OrganizationCustomize]
public async Task DeleteAsync_DeletesCollection(Collection collection, SutProvider<DeleteCollectionCommand> sutProvider)
{
// Act
await sutProvider.Sut.DeleteAsync(collection);
// Assert
await sutProvider.GetDependency<ICollectionRepository>().Received().DeleteAsync(collection);
await sutProvider.GetDependency<IEventService>().Received().LogCollectionEventAsync(collection, EventType.Collection_Deleted, Arg.Any<DateTime>());
}
[Theory, BitAutoData]
[OrganizationCustomize]
public async Task DeleteManyAsync_DeletesManyCollections(Collection collection, Collection collection2, SutProvider<DeleteCollectionCommand> sutProvider)
{
// Arrange
var collectionIds = new[] { collection.Id, collection2.Id };
sutProvider.GetDependency<ICollectionRepository>()
.GetManyByManyIdsAsync(collectionIds)
.Returns(new List<Collection> { collection, collection2 });
// Act
await sutProvider.Sut.DeleteManyAsync(collectionIds);
// Assert
await sutProvider.GetDependency<ICollectionRepository>().Received()
.DeleteManyAsync(Arg.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(collectionIds)));
await sutProvider.GetDependency<IEventService>().Received().LogCollectionEventsAsync(
Arg.Is<IEnumerable<(Collection, EventType, DateTime?)>>(a =>
a.All(c => collectionIds.Contains(c.Item1.Id) && c.Item2 == EventType.Collection_Deleted)));
}
}

View File

@ -25,7 +25,7 @@ public class CollectionServiceTest
await sutProvider.Sut.SaveAsync(collection);
await sutProvider.GetDependency<ICollectionRepository>().Received().CreateAsync(collection);
await sutProvider.GetDependency<ICollectionRepository>().Received().CreateAsync(collection, null, null);
await sutProvider.GetDependency<IEventService>().Received()
.LogCollectionEventAsync(collection, EventType.Collection_Created);
Assert.True(collection.CreationDate - utcNow < TimeSpan.FromSeconds(1));
@ -33,17 +33,33 @@ public class CollectionServiceTest
}
[Theory, BitAutoData]
public async Task SaveAsync_DefaultIdWithGroups_CreateCollectionWithGroupsInRepository(Collection collection,
IEnumerable<SelectionReadOnly> groups, Organization organization, SutProvider<CollectionService> sutProvider)
public async Task SaveAsync_DefaultIdWithUsers_CreatesCollectionInTheRepository(Collection collection, Organization organization, IEnumerable<CollectionAccessSelection> users, SutProvider<CollectionService> sutProvider)
{
collection.Id = default;
sutProvider.GetDependency<IOrganizationRepository>().GetByIdAsync(organization.Id).Returns(organization);
var utcNow = DateTime.UtcNow;
await sutProvider.Sut.SaveAsync(collection, null, users);
await sutProvider.GetDependency<ICollectionRepository>().Received().CreateAsync(collection, null, users);
await sutProvider.GetDependency<IEventService>().Received()
.LogCollectionEventAsync(collection, EventType.Collection_Created);
Assert.True(collection.CreationDate - utcNow < TimeSpan.FromSeconds(1));
Assert.True(collection.RevisionDate - utcNow < TimeSpan.FromSeconds(1));
}
[Theory, BitAutoData]
public async Task SaveAsync_DefaultIdWithGroupsAndUsers_CreateCollectionWithGroupsAndUsersInRepository(Collection collection,
IEnumerable<CollectionAccessSelection> groups, IEnumerable<CollectionAccessSelection> users, Organization organization, SutProvider<CollectionService> sutProvider)
{
collection.Id = default;
organization.UseGroups = true;
sutProvider.GetDependency<IOrganizationRepository>().GetByIdAsync(organization.Id).Returns(organization);
var utcNow = DateTime.UtcNow;
await sutProvider.Sut.SaveAsync(collection, groups);
await sutProvider.Sut.SaveAsync(collection, groups, users);
await sutProvider.GetDependency<ICollectionRepository>().Received().CreateAsync(collection, groups);
await sutProvider.GetDependency<ICollectionRepository>().Received().CreateAsync(collection, groups, users);
await sutProvider.GetDependency<IEventService>().Received()
.LogCollectionEventAsync(collection, EventType.Collection_Created);
Assert.True(collection.CreationDate - utcNow < TimeSpan.FromSeconds(1));
@ -59,7 +75,7 @@ public class CollectionServiceTest
await sutProvider.Sut.SaveAsync(collection);
await sutProvider.GetDependency<ICollectionRepository>().Received().ReplaceAsync(collection);
await sutProvider.GetDependency<ICollectionRepository>().Received().ReplaceAsync(collection, null, null);
await sutProvider.GetDependency<IEventService>().Received()
.LogCollectionEventAsync(collection, EventType.Collection_Updated);
Assert.Equal(collection.CreationDate, creationDate);
@ -67,7 +83,7 @@ public class CollectionServiceTest
}
[Theory, BitAutoData]
public async Task SaveAsync_OrganizationNotUseGroup_CreateCollectionWithoutGroupsInRepository(Collection collection, IEnumerable<SelectionReadOnly> groups,
public async Task SaveAsync_OrganizationNotUseGroup_CreateCollectionWithoutGroupsInRepository(Collection collection, IEnumerable<CollectionAccessSelection> groups,
Organization organization, SutProvider<CollectionService> sutProvider)
{
collection.Id = default;
@ -76,7 +92,7 @@ public class CollectionServiceTest
await sutProvider.Sut.SaveAsync(collection, groups);
await sutProvider.GetDependency<ICollectionRepository>().Received().CreateAsync(collection);
await sutProvider.GetDependency<ICollectionRepository>().Received().CreateAsync(collection, null, null);
await sutProvider.GetDependency<IEventService>().Received()
.LogCollectionEventAsync(collection, EventType.Collection_Created);
Assert.True(collection.CreationDate - utcNow < TimeSpan.FromSeconds(1));
@ -94,12 +110,12 @@ public class CollectionServiceTest
.Returns(organizationUser);
var utcNow = DateTime.UtcNow;
await sutProvider.Sut.SaveAsync(collection, null, organizationUser.Id);
await sutProvider.Sut.SaveAsync(collection, null, null, organizationUser.Id);
await sutProvider.GetDependency<ICollectionRepository>().Received().CreateAsync(collection);
await sutProvider.GetDependency<ICollectionRepository>().Received().CreateAsync(collection, null, null);
await sutProvider.GetDependency<IOrganizationUserRepository>().Received()
.GetByOrganizationAsync(organization.Id, organizationUser.Id);
await sutProvider.GetDependency<ICollectionRepository>().Received().UpdateUsersAsync(collection.Id, Arg.Any<List<SelectionReadOnly>>());
await sutProvider.GetDependency<ICollectionRepository>().Received().UpdateUsersAsync(collection.Id, Arg.Any<List<CollectionAccessSelection>>());
await sutProvider.GetDependency<IEventService>().Received()
.LogCollectionEventAsync(collection, EventType.Collection_Created);
Assert.True(collection.CreationDate - utcNow < TimeSpan.FromSeconds(1));
@ -112,7 +128,7 @@ public class CollectionServiceTest
var ex = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.SaveAsync(collection));
Assert.Contains("Organization not found", ex.Message);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().CreateAsync(default);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().CreateAsync(default, default);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().CreateAsync(default, default, default);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().ReplaceAsync(default);
await sutProvider.GetDependency<IEventService>().DidNotReceiveWithAnyArgs().LogCollectionEventAsync(default, default);
}
@ -128,7 +144,7 @@ public class CollectionServiceTest
var ex = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.SaveAsync(collection));
Assert.Equal($@"You have reached the maximum number of collections ({organization.MaxCollections.Value}) for this organization.", ex.Message);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().CreateAsync(default);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().CreateAsync(default, default);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().CreateAsync(default, default, default);
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().ReplaceAsync(default);
await sutProvider.GetDependency<IEventService>().DidNotReceiveWithAnyArgs().LogCollectionEventAsync(default, default);
}
@ -168,4 +184,5 @@ public class CollectionServiceTest
await sutProvider.GetDependency<IEventService>().DidNotReceiveWithAnyArgs()
.LogOrganizationUserEventAsync(default, default);
}
}

View File

@ -23,7 +23,7 @@ public class EventServiceTests
[Theory, BitAutoData]
public async Task LogGroupEvent_LogsRequiredInfo(Group group, EventType eventType, DateTime date,
Guid actingUserId, Guid providerId, DeviceType deviceType, SutProvider<EventService> sutProvider)
Guid actingUserId, Guid providerId, string ipAddress, DeviceType deviceType, SutProvider<EventService> sutProvider)
{
var orgAbilities = new Dictionary<Guid, OrganizationAbility>()
{
@ -31,24 +31,33 @@ public class EventServiceTests
};
sutProvider.GetDependency<IApplicationCacheService>().GetOrganizationAbilitiesAsync().Returns(orgAbilities);
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
sutProvider.GetDependency<ICurrentContext>().IpAddress.Returns(ipAddress);
sutProvider.GetDependency<ICurrentContext>().DeviceType.Returns(deviceType);
sutProvider.GetDependency<ICurrentContext>().ProviderIdForOrg(Arg.Any<Guid>()).Returns(providerId);
await sutProvider.Sut.LogGroupEventAsync(group, eventType, date);
await sutProvider.GetDependency<IEventWriteService>().Received(1).CreateAsync(Arg.Is<IEvent>(e =>
e.OrganizationId == group.OrganizationId &&
e.GroupId == group.Id &&
e.Type == eventType &&
e.ActingUserId == actingUserId &&
e.ProviderId == providerId &&
e.Date == date &&
e.SystemUser == null));
var expected = new List<IEvent>() {
new EventMessage()
{
IpAddress = ipAddress,
DeviceType = deviceType,
OrganizationId = group.OrganizationId,
GroupId = group.Id,
Type = eventType,
ActingUserId = actingUserId,
ProviderId = providerId,
Date = date,
SystemUser = null
}
};
await sutProvider.GetDependency<IEventWriteService>().Received(1).CreateManyAsync(Arg.Is(AssertHelper.AssertPropertyEqual<IEvent>(expected, new[] { "IdempotencyId" })));
}
[Theory, BitAutoData]
public async Task LogGroupEvent_WithEventSystemUser_LogsRequiredInfo(Group group, EventType eventType, EventSystemUser eventSystemUser, DateTime date,
Guid actingUserId, Guid providerId, DeviceType deviceType, SutProvider<EventService> sutProvider)
Guid actingUserId, Guid providerId, string ipAddress, DeviceType deviceType, SutProvider<EventService> sutProvider)
{
var orgAbilities = new Dictionary<Guid, OrganizationAbility>()
{
@ -56,19 +65,28 @@ public class EventServiceTests
};
sutProvider.GetDependency<IApplicationCacheService>().GetOrganizationAbilitiesAsync().Returns(orgAbilities);
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
sutProvider.GetDependency<ICurrentContext>().IpAddress.Returns(ipAddress);
sutProvider.GetDependency<ICurrentContext>().DeviceType.Returns(deviceType);
sutProvider.GetDependency<ICurrentContext>().ProviderIdForOrg(Arg.Any<Guid>()).Returns(providerId);
await sutProvider.Sut.LogGroupEventAsync(group, eventType, eventSystemUser, date);
await sutProvider.GetDependency<IEventWriteService>().Received(1).CreateAsync(Arg.Is<IEvent>(e =>
e.OrganizationId == group.OrganizationId &&
e.GroupId == group.Id &&
e.Type == eventType &&
e.ActingUserId == actingUserId &&
e.ProviderId == providerId &&
e.Date == date &&
e.SystemUser == eventSystemUser));
var expected = new List<IEvent>() {
new EventMessage()
{
IpAddress = ipAddress,
DeviceType = deviceType,
OrganizationId = group.OrganizationId,
GroupId = group.Id,
Type = eventType,
ActingUserId = actingUserId,
ProviderId = providerId,
Date = date,
SystemUser = eventSystemUser
}
};
await sutProvider.GetDependency<IEventWriteService>().Received(1).CreateManyAsync(Arg.Is(AssertHelper.AssertPropertyEqual<IEvent>(expected, new[] { "IdempotencyId" })));
}
[Theory]

View File

@ -499,22 +499,22 @@ public class OrganizationServiceTests
[Theory, BitAutoData]
public async Task SaveUser_NoUserId_Throws(OrganizationUser user, Guid? savingUserId,
IEnumerable<SelectionReadOnly> collections, SutProvider<OrganizationService> sutProvider)
IEnumerable<CollectionAccessSelection> collections, IEnumerable<Guid> groups, SutProvider<OrganizationService> sutProvider)
{
user.Id = default(Guid);
var exception = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveUserAsync(user, savingUserId, collections));
() => sutProvider.Sut.SaveUserAsync(user, savingUserId, collections, groups));
Assert.Contains("invite the user first", exception.Message.ToLowerInvariant());
}
[Theory, BitAutoData]
public async Task SaveUser_NoChangeToData_Throws(OrganizationUser user, Guid? savingUserId,
IEnumerable<SelectionReadOnly> collections, SutProvider<OrganizationService> sutProvider)
IEnumerable<CollectionAccessSelection> collections, IEnumerable<Guid> groups, SutProvider<OrganizationService> sutProvider)
{
var organizationUserRepository = sutProvider.GetDependency<IOrganizationUserRepository>();
organizationUserRepository.GetByIdAsync(user.Id).Returns(user);
var exception = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveUserAsync(user, savingUserId, collections));
() => sutProvider.Sut.SaveUserAsync(user, savingUserId, collections, groups));
Assert.Contains("make changes before saving", exception.Message.ToLowerInvariant());
}
@ -523,7 +523,8 @@ public class OrganizationServiceTests
Organization organization,
OrganizationUser oldUserData,
OrganizationUser newUserData,
IEnumerable<SelectionReadOnly> collections,
IEnumerable<CollectionAccessSelection> collections,
IEnumerable<Guid> groups,
[OrganizationUser(type: OrganizationUserType.Owner)] OrganizationUser savingUser,
SutProvider<OrganizationService> sutProvider)
{
@ -541,7 +542,7 @@ public class OrganizationServiceTests
.Returns(new List<OrganizationUser> { savingUser });
currentContext.OrganizationOwner(savingUser.OrganizationId).Returns(true);
await sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections);
await sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections, groups);
}
[Theory, BitAutoData]
@ -549,7 +550,8 @@ public class OrganizationServiceTests
Organization organization,
OrganizationUser oldUserData,
[OrganizationUser(type: OrganizationUserType.Custom)] OrganizationUser newUserData,
IEnumerable<SelectionReadOnly> collections,
IEnumerable<CollectionAccessSelection> collections,
IEnumerable<Guid> groups,
[OrganizationUser(type: OrganizationUserType.Owner)] OrganizationUser savingUser,
SutProvider<OrganizationService> sutProvider)
{
@ -570,7 +572,7 @@ public class OrganizationServiceTests
currentContext.OrganizationOwner(savingUser.OrganizationId).Returns(true);
var exception = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections));
() => sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections, groups));
Assert.Contains("to enable custom permissions", exception.Message.ToLowerInvariant());
}
@ -584,7 +586,8 @@ public class OrganizationServiceTests
Organization organization,
OrganizationUser oldUserData,
OrganizationUser newUserData,
IEnumerable<SelectionReadOnly> collections,
IEnumerable<CollectionAccessSelection> collections,
IEnumerable<Guid> groups,
[OrganizationUser(type: OrganizationUserType.Owner)] OrganizationUser savingUser,
SutProvider<OrganizationService> sutProvider)
{
@ -605,7 +608,7 @@ public class OrganizationServiceTests
.Returns(new List<OrganizationUser> { savingUser });
currentContext.OrganizationOwner(savingUser.OrganizationId).Returns(true);
await sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections);
await sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections, groups);
}
[Theory, BitAutoData]
@ -613,7 +616,8 @@ public class OrganizationServiceTests
Organization organization,
OrganizationUser oldUserData,
[OrganizationUser(type: OrganizationUserType.Custom)] OrganizationUser newUserData,
IEnumerable<SelectionReadOnly> collections,
IEnumerable<CollectionAccessSelection> collections,
IEnumerable<Guid> groups,
[OrganizationUser(type: OrganizationUserType.Owner)] OrganizationUser savingUser,
SutProvider<OrganizationService> sutProvider)
{
@ -633,7 +637,7 @@ public class OrganizationServiceTests
.Returns(new List<OrganizationUser> { savingUser });
currentContext.OrganizationOwner(savingUser.OrganizationId).Returns(true);
await sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections);
await sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections, groups);
}
[Theory, BitAutoData]

View File

@ -140,8 +140,8 @@ public class CipherRepositoryTests
orgUsers = await efOrgUserRepos[i].CreateMany(orgUsers);
var selectionReadOnlyList = new List<SelectionReadOnly>();
orgUsers.ForEach(ou => selectionReadOnlyList.Add(new SelectionReadOnly() { Id = ou.Id }));
var selectionReadOnlyList = new List<CollectionAccessSelection>();
orgUsers.ForEach(ou => selectionReadOnlyList.Add(new CollectionAccessSelection() { Id = ou.Id }));
await efCollectionRepos[i].UpdateUsersAsync(efCollection.Id, selectionReadOnlyList);
efCollectionRepos[i].ClearChangeTracking();

View File

@ -0,0 +1,181 @@
-- Collection_ReadWithGroupsAndUsersByOrganizationId
IF OBJECT_ID('[dbo].[Collection_ReadWithGroupsAndUsersByOrganizationId]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[Collection_ReadWithGroupsAndUsersByOrganizationId]
END
GO
CREATE PROCEDURE [dbo].[Collection_ReadWithGroupsAndUsersByOrganizationId]
@OrganizationId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_ReadByOrganizationId] @OrganizationId
EXEC [dbo].[CollectionGroup_ReadByOrganizationId] @OrganizationId
EXEC [dbo].[CollectionUser_ReadByOrganizationId] @OrganizationId
END
GO
-- Collection_ReadWithGroupsAndUsersByUserId
IF OBJECT_ID('[dbo].[Collection_ReadWithGroupsAndUsersByUserId]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[Collection_ReadWithGroupsAndUsersByUserId]
END
GO
CREATE PROCEDURE [dbo].[Collection_ReadWithGroupsAndUsersByUserId]
@UserId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
DECLARE @TempUserCollections TABLE(
Id UNIQUEIDENTIFIER,
OrganizationId UNIQUEIDENTIFIER,
Name VARCHAR(MAX),
CreationDate DATETIME2(7),
RevisionDate DATETIME2(7),
ExternalId NVARCHAR(300),
ReadOnly BIT,
HidePasswords BIT)
INSERT INTO @TempUserCollections EXEC [dbo].[Collection_ReadByUserId] @UserId
SELECT
*
FROM
@TempUserCollections C
SELECT
CG.*
FROM
[dbo].[CollectionGroup] CG
INNER JOIN
@TempUserCollections C ON C.[Id] = CG.[CollectionId]
SELECT
CU.*
FROM
[dbo].[CollectionUser] CU
INNER JOIN
@TempUserCollections C ON C.[Id] = CU.[CollectionId]
END
GO
-- CollectionUser_ReadByOrganizationId
CREATE PROCEDURE [dbo].[CollectionUser_ReadByOrganizationId]
@OrganizationId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
CU.*
FROM
[dbo].[CollectionUser] CU
INNER JOIN
[dbo].[OrganizationUser] OU ON OU.[Id] = CU.[OrganizationUserId]
WHERE
OU.[OrganizationId] = @OrganizationId
END
GO
-- Collection_ReadByIds
IF OBJECT_ID('[dbo].[Collection_ReadByIds]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[Collection_ReadByIds]
END
GO
CREATE PROCEDURE [dbo].[Collection_ReadByIds]
@Ids AS [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
IF (SELECT COUNT(1) FROM @Ids) < 1
BEGIN
RETURN(-1)
END
SELECT
*
FROM
[dbo].[Collection]
WHERE
[Id] IN (SELECT [Id] FROM @Ids)
END
GO
-- Collection_DeleteByIds
IF OBJECT_ID('[dbo].[Collection_DeleteByIds]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[Collection_DeleteByIds]
END
GO
CREATE PROCEDURE [dbo].[Collection_DeleteByIds]
@Ids AS [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
DECLARE @OrgIds AS [dbo].[GuidIdArray]
INSERT INTO @OrgIds (Id)
SELECT
[OrganizationId]
FROM
[dbo].[Collection]
WHERE
[Id] in (SELECT [Id] FROM @Ids)
GROUP BY
[OrganizationId]
DECLARE @BatchSize INT = 100
-- Delete Collection Groups
WHILE @BatchSize > 0
BEGIN
BEGIN TRANSACTION CollectionGroup_DeleteMany
DELETE TOP(@BatchSize)
FROM
[dbo].[CollectionGroup]
WHERE
[CollectionId] IN (SELECT [Id] FROM @Ids)
SET @BatchSize = @@ROWCOUNT
COMMIT TRANSACTION CollectionGroup_DeleteMany
END
-- Reset batch size
SET @BatchSize = 100
-- Delete Collections
WHILE @BatchSize > 0
BEGIN
BEGIN TRANSACTION Collection_DeleteMany
DELETE TOP(@BatchSize)
FROM
[dbo].[Collection]
WHERE
[Id] IN (SELECT [Id] FROM @Ids)
SET @BatchSize = @@ROWCOUNT
COMMIT TRANSACTION CollectionGroup_DeleteMany
END
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationIds] @OrgIds
END
GO

View File

@ -0,0 +1,134 @@
IF OBJECT_ID('[dbo].[CollectionGroup_ReadByOrganizationId]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[CollectionGroup_ReadByOrganizationId];
END
GO
CREATE PROCEDURE [dbo].[CollectionGroup_ReadByOrganizationId]
@OrganizationId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
CG.*
FROM
[dbo].[CollectionGroup] CG
INNER JOIN
[dbo].[Group] G ON G.[Id] = CG.[GroupId]
WHERE
G.[OrganizationId] = @OrganizationId
END
GO
IF OBJECT_ID('[dbo].[Group_ReadWithCollectionsByOrganizationId]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[Group_ReadWithCollectionsByOrganizationId];
END
GO
CREATE PROCEDURE [dbo].[Group_ReadWithCollectionsByOrganizationId]
@OrganizationId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Group_ReadByOrganizationId] @OrganizationId
EXEC [dbo].[CollectionGroup_ReadByOrganizationId] @OrganizationId
END
GO
IF OBJECT_ID('[dbo].[Group_ReadByIds]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[Group_ReadByIds];
END
GO
CREATE PROCEDURE [dbo].[Group_ReadByIds]
@Ids AS [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
IF (SELECT COUNT(1) FROM @Ids) < 1
BEGIN
RETURN(-1)
END
SELECT
*
FROM
[dbo].[Group]
WHERE
[Id] IN (SELECT [Id] FROM @Ids)
END
GO
IF OBJECT_ID('[dbo].[User_BumpAccountRevisionDateByOrganizationIds]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[User_BumpAccountRevisionDateByOrganizationIds];
END
GO
CREATE PROCEDURE [dbo].[User_BumpAccountRevisionDateByOrganizationIds]
@OrganizationIds AS [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
UPDATE
U
SET
U.[AccountRevisionDate] = GETUTCDATE()
FROM
[dbo].[User] U
INNER JOIN
[dbo].[OrganizationUser] OU ON OU.[UserId] = U.[Id]
WHERE
OU.[OrganizationId] IN (SELECT [Id] FROM @OrganizationIds)
AND OU.[Status] = 2 -- Confirmed
END
GO
IF OBJECT_ID('[dbo].[Group_DeleteByIds]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[Group_DeleteByIds];
END
GO
CREATE PROCEDURE [dbo].[Group_DeleteByIds]
@Ids AS [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
DECLARE @OrgIds AS [dbo].[GuidIdArray]
INSERT INTO @OrgIds (Id)
SELECT
[OrganizationId]
FROM
[dbo].[Group]
WHERE
[Id] in (SELECT [Id] FROM @Ids)
GROUP BY
[OrganizationId]
DECLARE @BatchSize INT = 100
WHILE @BatchSize > 0
BEGIN
BEGIN TRANSACTION Group_DeleteMany_Groups
DELETE TOP(@BatchSize)
FROM
[dbo].[Group]
WHERE
[Id] IN (SELECT [Id] FROM @Ids)
SET @BatchSize = @@ROWCOUNT
COMMIT TRANSACTION Group_DeleteMany_Groups
END
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationIds] @OrgIds
END

View File

@ -0,0 +1,211 @@
-- Stored Procedure: CollectionGroup_ReadByCollectionId
CREATE OR ALTER PROCEDURE [dbo].[CollectionGroup_ReadByCollectionId]
@CollectionId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
[GroupId] [Id],
[ReadOnly],
[HidePasswords]
FROM
[dbo].[CollectionGroup]
WHERE
[CollectionId] = @CollectionId
END
GO
-- Stored Procedure: Collection_ReadWithGroupsAndUsersById
CREATE OR ALTER PROCEDURE [dbo].[Collection_ReadWithGroupsAndUsersById]
@Id UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_ReadById] @Id
EXEC [dbo].[CollectionGroup_ReadByCollectionId] @Id
EXEC [dbo].[CollectionUser_ReadByCollectionId] @Id
END
GO
-- Stored Procedure: Collection_ReadWithGroupsAndUsersByIdUserId
CREATE OR ALTER PROCEDURE [dbo].[Collection_ReadWithGroupsAndUsersByIdUserId]
@Id UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_ReadByIdUserId] @Id, @UserId
EXEC [dbo].[CollectionGroup_ReadByCollectionId] @Id
EXEC [dbo].[CollectionUser_ReadByCollectionId] @Id
END
GO
-- Stored Procedure: Collection_CreateWithGroupsAndUsers
CREATE OR ALTER PROCEDURE [dbo].[Collection_CreateWithGroupsAndUsers]
@Id UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Name VARCHAR(MAX),
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@Groups AS [dbo].[SelectionReadOnlyArray] READONLY,
@Users AS [dbo].[SelectionReadOnlyArray] READONLY
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_Create] @Id, @OrganizationId, @Name, @ExternalId, @CreationDate, @RevisionDate
-- Groups
;WITH [AvailableGroupsCTE] AS(
SELECT
[Id]
FROM
[dbo].[Group]
WHERE
[OrganizationId] = @OrganizationId
)
INSERT INTO [dbo].[CollectionGroup]
(
[CollectionId],
[GroupId],
[ReadOnly],
[HidePasswords]
)
SELECT
@Id,
[Id],
[ReadOnly],
[HidePasswords]
FROM
@Groups
WHERE
[Id] IN (SELECT [Id] FROM [AvailableGroupsCTE])
-- Users
;WITH [AvailableUsersCTE] AS(
SELECT
[Id]
FROM
[dbo].[OrganizationUser]
WHERE
[OrganizationId] = @OrganizationId
)
INSERT INTO [dbo].[CollectionUser]
(
[CollectionId],
[OrganizationUserId],
[ReadOnly],
[HidePasswords]
)
SELECT
@Id,
[Id],
[ReadOnly],
[HidePasswords]
FROM
@Users
WHERE
[Id] IN (SELECT [Id] FROM [AvailableUsersCTE])
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationId] @OrganizationId
END
GO
-- Stored Procedure: Collection_UpdateWithGroupsAndUsers
CREATE OR ALTER PROCEDURE [dbo].[Collection_UpdateWithGroupsAndUsers]
@Id UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@Name VARCHAR(MAX),
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@Groups AS [dbo].[SelectionReadOnlyArray] READONLY,
@Users AS [dbo].[SelectionReadOnlyArray] READONLY
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[Collection_Update] @Id, @OrganizationId, @Name, @ExternalId, @CreationDate, @RevisionDate
-- Groups
;WITH [AvailableGroupsCTE] AS(
SELECT
Id
FROM
[dbo].[Group]
WHERE
OrganizationId = @OrganizationId
)
MERGE
[dbo].[CollectionGroup] AS [Target]
USING
@Groups AS [Source]
ON
[Target].[CollectionId] = @Id
AND [Target].[GroupId] = [Source].[Id]
WHEN NOT MATCHED BY TARGET
AND [Source].[Id] IN (SELECT [Id] FROM [AvailableGroupsCTE]) THEN
INSERT VALUES
(
@Id,
[Source].[Id],
[Source].[ReadOnly],
[Source].[HidePasswords]
)
WHEN MATCHED AND (
[Target].[ReadOnly] != [Source].[ReadOnly]
OR [Target].[HidePasswords] != [Source].[HidePasswords]
) THEN
UPDATE SET [Target].[ReadOnly] = [Source].[ReadOnly],
[Target].[HidePasswords] = [Source].[HidePasswords]
WHEN NOT MATCHED BY SOURCE
AND [Target].[CollectionId] = @Id THEN
DELETE
;
-- Users
;WITH [AvailableGroupsCTE] AS(
SELECT
Id
FROM
[dbo].[OrganizationUser]
WHERE
OrganizationId = @OrganizationId
)
MERGE
[dbo].[CollectionUser] AS [Target]
USING
@Users AS [Source]
ON
[Target].[CollectionId] = @Id
AND [Target].[OrganizationUserId] = [Source].[Id]
WHEN NOT MATCHED BY TARGET
AND [Source].[Id] IN (SELECT [Id] FROM [AvailableGroupsCTE]) THEN
INSERT VALUES
(
@Id,
[Source].[Id],
[Source].[ReadOnly],
[Source].[HidePasswords]
)
WHEN MATCHED AND (
[Target].[ReadOnly] != [Source].[ReadOnly]
OR [Target].[HidePasswords] != [Source].[HidePasswords]
) THEN
UPDATE SET [Target].[ReadOnly] = [Source].[ReadOnly],
[Target].[HidePasswords] = [Source].[HidePasswords]
WHEN NOT MATCHED BY SOURCE
AND [Target].[CollectionId] = @Id THEN
DELETE
;
EXEC [dbo].[User_BumpAccountRevisionDateByCollectionId] @Id, @OrganizationId
END

View File

@ -0,0 +1,42 @@
IF OBJECT_ID('[dbo].[CollectionUser_ReadByOrganizationUserIds]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[CollectionUser_ReadByOrganizationUserIds];
END
GO
CREATE PROCEDURE [dbo].[CollectionUser_ReadByOrganizationUserIds]
@OrganizationUserIds [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
SELECT
CU.*
FROM
[dbo].[OrganizationUser] OU
INNER JOIN
[dbo].[CollectionUser] CU ON OU.[AccessAll] = 0 AND CU.[OrganizationUserId] = OU.[Id]
INNER JOIN
@OrganizationUserIds OUI ON OUI.[Id] = OU.[Id]
END
GO
IF OBJECT_ID('[dbo].[GroupUser_ReadByOrganizationUserIds]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[GroupUser_ReadByOrganizationUserIds];
END
GO
CREATE PROCEDURE [dbo].[GroupUser_ReadByOrganizationUserIds]
@OrganizationUserIds [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
SELECT
GU.*
FROM
[dbo].[GroupUser] GU
INNER JOIN
@OrganizationUserIds OUI ON OUI.[Id] = GU.[OrganizationUserId]
END

View File

@ -0,0 +1,14 @@
-- Stored Procedure: Collection_ReadWithGroupsById
DROP PROCEDURE [dbo].[Collection_ReadWithGroupsById];
GO
-- Stored Procedure: Collection_ReadWithGroupsByIdUserId
DROP PROCEDURE [dbo].[Collection_ReadWithGroupsByIdUserId];
GO
-- Stored Procedure: Collection_CreateWithGroups
DROP PROCEDURE [dbo].[Collection_CreateWithGroups];
GO
-- Stored Procedure: Collection_UpdateWithGroups
DROP PROCEDURE [dbo].[Collection_UpdateWithGroups];