1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-25 12:45:18 +01:00

Resolve error when deleting an account connected to a provider (#1580)

This commit is contained in:
Oscar Hinton 2021-09-15 20:34:06 +02:00 committed by GitHub
parent 00332e72e4
commit c22e48c1b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 264 additions and 9 deletions

View File

@ -155,5 +155,11 @@ namespace Bit.Core.Repositories.EntityFramework
return organizationUsers;
}
}
public async Task<int> GetCountByOnlyOwnerAsync(Guid userId)
{
var query = new ProviderUserReadCountByOnlyOwnerQuery(userId);
return await GetCountFromQuery(query);
}
}
}

View File

@ -19,11 +19,12 @@ namespace Bit.Core.Repositories.EntityFramework.Queries
{
var owners = from ou in dbContext.OrganizationUsers
where ou.Type == OrganizationUserType.Owner &&
ou.Status == OrganizationUserStatusType.Confirmed
ou.Status == OrganizationUserStatusType.Confirmed
group ou by ou.OrganizationId into g
select new
{
OrgUser = g.Select(x => new {x.UserId, x.Id}).FirstOrDefault(), ConfirmedOwnerCount = g.Count()
OrgUser = g.Select(x => new {x.UserId, x.Id}).FirstOrDefault(),
ConfirmedOwnerCount = g.Count(),
};
var query = from owner in owners

View File

@ -0,0 +1,39 @@
using System.Linq;
using System;
using Bit.Core.Enums.Provider;
using Bit.Core.Models.EntityFramework.Provider;
namespace Bit.Core.Repositories.EntityFramework.Queries
{
public class ProviderUserReadCountByOnlyOwnerQuery : IQuery<ProviderUser>
{
private readonly Guid _userId;
public ProviderUserReadCountByOnlyOwnerQuery(Guid userId)
{
_userId = userId;
}
public IQueryable<ProviderUser> Run(DatabaseContext dbContext)
{
var owners = from pu in dbContext.ProviderUsers
where pu.Type == ProviderUserType.ProviderAdmin &&
pu.Status == ProviderUserStatusType.Confirmed
group pu by pu.ProviderId into g
select new
{
ProviderUser = g.Select(x => new {x.UserId, x.Id}).FirstOrDefault(),
ConfirmedOwnerCount = g.Count(),
};
var query = from owner in owners
join pu in dbContext.ProviderUsers
on owner.ProviderUser.Id equals pu.Id
where owner.ProviderUser.UserId == _userId &&
owner.ConfirmedOwnerCount == 1
select pu;
return query;
}
}
}

View File

@ -20,5 +20,6 @@ namespace Bit.Core.Repositories
Task<IEnumerable<ProviderUserOrganizationDetails>> GetManyOrganizationDetailsByUserAsync(Guid userId, ProviderUserStatusType? status = null);
Task DeleteManyAsync(IEnumerable<Guid> userIds);
Task<IEnumerable<ProviderUserPublicKey>> GetManyPublicKeysByProviderUserAsync(Guid providerId, IEnumerable<Guid> Ids);
Task<int> GetCountByOnlyOwnerAsync(Guid userId);
}
}

View File

@ -151,5 +151,18 @@ namespace Bit.Core.Repositories.SqlServer
return results.ToList();
}
}
public async Task<int> GetCountByOnlyOwnerAsync(Guid userId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.ExecuteScalarAsync<int>(
"[dbo].[ProviderUser_ReadCountByOnlyOwner]",
new { UserId = userId },
commandType: CommandType.StoredProcedure);
return results;
}
}
}
}

View File

@ -52,7 +52,7 @@ namespace Bit.Core.Services
private readonly ICurrentContext _currentContext;
private readonly GlobalSettings _globalSettings;
private readonly IOrganizationService _organizationService;
private readonly ISendRepository _sendRepository;
private readonly IProviderUserRepository _providerUserRepository;
public UserService(
IUserRepository userRepository,
@ -81,7 +81,7 @@ namespace Bit.Core.Services
ICurrentContext currentContext,
GlobalSettings globalSettings,
IOrganizationService organizationService,
ISendRepository sendRepository)
IProviderUserRepository providerUserRepository)
: base(
store,
optionsAccessor,
@ -115,7 +115,7 @@ namespace Bit.Core.Services
_currentContext = currentContext;
_globalSettings = globalSettings;
_organizationService = organizationService;
_sendRepository = sendRepository;
_providerUserRepository = providerUserRepository;
}
public Guid? GetProperUserId(ClaimsPrincipal principal)
@ -216,11 +216,20 @@ namespace Bit.Core.Services
{
return IdentityResult.Failed(new IdentityError
{
Description = "You must leave or delete any organizations that you are the only owner of first."
Description = "Cannot delete this user because it is the sole owner of at least one organization. Please delete these organizations or upgrade another user.",
});
}
}
var onlyOwnerProviderCount = await _providerUserRepository.GetCountByOnlyOwnerAsync(user.Id);
if (onlyOwnerProviderCount > 0)
{
return IdentityResult.Failed(new IdentityError
{
Description = "Cannot delete this user because it is the sole owner of at least one provider. Please delete these providers or upgrade another user.",
});
}
if (!string.IsNullOrWhiteSpace(user.GatewaySubscriptionId))
{
try

View File

@ -74,6 +74,7 @@
<Build Include="dbo\Stored Procedures\Event_ReadPageByProviderIdActingUserId.sql" />
<Build Include="dbo\Stored Procedures\ProviderOrganization_ReadByOrganizationId.sql" />
<Build Include="dbo\Stored Procedures\ProviderUserProviderOrganizationDetails_ReadByUserIdStatus.sql" />
<Build Include="dbo\Stored Procedures\ProviderUser_ReadCountByOnlyOwner.sql" />
<Build Include="dbo\Stored Procedures\SsoConfig_Create.sql" />
<Build Include="dbo\Stored Procedures\SsoConfig_ReadByIdentifier.sql" />
<Build Include="dbo\Stored Procedures\SsoConfig_ReadByOrganizationId.sql" />

View File

@ -0,0 +1,25 @@
CREATE PROCEDURE [dbo].[ProviderUser_ReadCountByOnlyOwner]
@UserId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
;WITH [OwnerCountCTE] AS
(
SELECT
PU.[UserId],
COUNT(1) OVER (PARTITION BY PU.[ProviderId]) [ConfirmedOwnerCount]
FROM
[dbo].[ProviderUser] PU
WHERE
PU.[Type] = 0 -- 0 = ProviderAdmin
AND PU.[Status] = 2 -- 2 = Confirmed
)
SELECT
COUNT(1)
FROM
[OwnerCountCTE] OC
WHERE
OC.[UserId] = @UserId
AND OC.[ConfirmedOwnerCount] = 1
END

View File

@ -65,6 +65,13 @@ BEGIN
WHERE
[UserId] = @Id
-- Delete provider users
DELETE
FROM
[dbo].[ProviderUser]
WHERE
[UserId] = @Id
-- Delete U2F logins
DELETE
FROM

View File

@ -45,7 +45,7 @@ namespace Bit.Core.Test.Services
private readonly CurrentContext _currentContext;
private readonly GlobalSettings _globalSettings;
private readonly IOrganizationService _organizationService;
private readonly ISendRepository _sendRepository;
private readonly IProviderUserRepository _providerUserRepository;
public UserServiceTests()
{
@ -75,7 +75,7 @@ namespace Bit.Core.Test.Services
_currentContext = new CurrentContext(null);
_globalSettings = new GlobalSettings();
_organizationService = Substitute.For<IOrganizationService>();
_sendRepository = Substitute.For<ISendRepository>();
_providerUserRepository = Substitute.For<IProviderUserRepository>();
_sut = new UserService(
_userRepository,
@ -104,7 +104,7 @@ namespace Bit.Core.Test.Services
_currentContext,
_globalSettings,
_organizationService,
_sendRepository
_providerUserRepository
);
}

View File

@ -0,0 +1,153 @@
IF OBJECT_ID('[dbo].[ProviderUser_ReadCountByOnlyOwner]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[ProviderUser_ReadCountByOnlyOwner]
END
GO
CREATE PROCEDURE [dbo].[ProviderUser_ReadCountByOnlyOwner]
@UserId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
;WITH [OwnerCountCTE] AS
(
SELECT
PU.[UserId],
COUNT(1) OVER (PARTITION BY PU.[ProviderId]) [ConfirmedOwnerCount]
FROM
[dbo].[ProviderUser] PU
WHERE
PU.[Type] = 0 -- 0 = ProviderAdmin
AND PU.[Status] = 2 -- 2 = Confirmed
)
SELECT
COUNT(1)
FROM
[OwnerCountCTE] OC
WHERE
OC.[UserId] = @UserId
AND OC.[ConfirmedOwnerCount] = 1
END
GO
IF OBJECT_ID('[dbo].[User_DeleteById]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[User_DeleteById]
END
GO
CREATE PROCEDURE [dbo].[User_DeleteById]
@Id UNIQUEIDENTIFIER
WITH RECOMPILE
AS
BEGIN
SET NOCOUNT ON
DECLARE @BatchSize INT = 100
-- Delete ciphers
WHILE @BatchSize > 0
BEGIN
BEGIN TRANSACTION User_DeleteById_Ciphers
DELETE TOP(@BatchSize)
FROM
[dbo].[Cipher]
WHERE
[UserId] = @Id
SET @BatchSize = @@ROWCOUNT
COMMIT TRANSACTION User_DeleteById_Ciphers
END
BEGIN TRANSACTION User_DeleteById
-- Delete folders
DELETE
FROM
[dbo].[Folder]
WHERE
[UserId] = @Id
-- Delete devices
DELETE
FROM
[dbo].[Device]
WHERE
[UserId] = @Id
-- Delete collection users
DELETE
CU
FROM
[dbo].[CollectionUser] CU
INNER JOIN
[dbo].[OrganizationUser] OU ON OU.[Id] = CU.[OrganizationUserId]
WHERE
OU.[UserId] = @Id
-- Delete group users
DELETE
GU
FROM
[dbo].[GroupUser] GU
INNER JOIN
[dbo].[OrganizationUser] OU ON OU.[Id] = GU.[OrganizationUserId]
WHERE
OU.[UserId] = @Id
-- Delete organization users
DELETE
FROM
[dbo].[OrganizationUser]
WHERE
[UserId] = @Id
-- Delete provider users
DELETE
FROM
[dbo].[ProviderUser]
WHERE
[UserId] = @Id
-- Delete U2F logins
DELETE
FROM
[dbo].[U2f]
WHERE
[UserId] = @Id
-- Delete SSO Users
DELETE
FROM
[dbo].[SsoUser]
WHERE
[UserId] = @Id
-- Delete Emergency Accesses
DELETE
FROM
[dbo].[EmergencyAccess]
WHERE
[GrantorId] = @Id
OR
[GranteeId] = @Id
-- Delete Sends
DELETE
FROM
[dbo].[Send]
WHERE
[UserId] = @Id
-- Finally, delete the user
DELETE
FROM
[dbo].[User]
WHERE
[Id] = @Id
COMMIT TRANSACTION User_DeleteById
END
go