1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-22 12:15:36 +01:00

EC-262 - implement org user deactivated flag and behavior server (#2050)

* SM-47 - Add Disabled status to enum + schema

* SM-47 - Enable and disable sprocs and repositories

* SM-47 - Organization service enble/disable user

* SM-47 - Fix lint errors

* SM-47 - add disable/enable endpoints to API

* SM-47 - Add bulk operations for enable/disable

* SM-47 - Fix linting errors, one of these days I'll do this first

* SM-47 - Codesense fix DRY warnings

* EC-262 - Code review changes, async cleanup

* EC-262 - Fix build issues, async refs

* EC-262 - Update controller param types

* EC-262 - Ensure mutable state is correct

* EC-262 - rename disabled to deactivated
This commit is contained in:
Chad Scharf 2022-06-16 15:59:57 -04:00 committed by GitHub
parent 8e79c20dce
commit b2a0aa2860
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 2507 additions and 13 deletions

View File

@ -6,6 +6,7 @@ using Bit.Api.Models.Request.Organizations;
using Bit.Api.Models.Response;
using Bit.Api.Models.Response.Organizations;
using Bit.Core.Context;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Exceptions;
using Bit.Core.Models.Business;
@ -375,5 +376,69 @@ namespace Bit.Api.Controllers
return new ListResponseModel<OrganizationUserBulkResponseModel>(result.Select(r =>
new OrganizationUserBulkResponseModel(r.Item1.Id, r.Item2)));
}
[HttpPatch("{id}/deactivate")]
[HttpPut("{id}/deactivate")]
public async Task Deactivate(Guid orgId, Guid id)
{
await ActivateOrDeactivateUserAsync(orgId, id, _organizationService.DeactivateUserAsync);
}
[HttpPatch("deactivate")]
[HttpPut("deactivate")]
public async Task<ListResponseModel<OrganizationUserBulkResponseModel>> BulkDeactivate(Guid orgId, [FromBody] OrganizationUserBulkRequestModel model)
{
return await ActivateOrDeactivateUsersAsync(orgId, model, _organizationService.DeactivateUsersAsync);
}
[HttpPatch("{id}/activate")]
[HttpPut("{id}/activate")]
public async Task Activate(Guid orgId, Guid id)
{
await ActivateOrDeactivateUserAsync(orgId, id, _organizationService.ActivateUserAsync);
}
[HttpPatch("activate")]
[HttpPut("activate")]
public async Task<ListResponseModel<OrganizationUserBulkResponseModel>> BulkActivate(Guid orgId, [FromBody] OrganizationUserBulkRequestModel model)
{
return await ActivateOrDeactivateUsersAsync(orgId, model, _organizationService.ActivateUsersAsync);
}
private async Task ActivateOrDeactivateUserAsync(
Guid orgId,
Guid id,
Func<OrganizationUser, Guid?, Task> statusAction)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User);
var orgUser = await _organizationUserRepository.GetByIdAsync(id);
if (orgUser == null || orgUser.OrganizationId != orgId)
{
throw new NotFoundException();
}
await statusAction(orgUser, userId);
}
private async Task<ListResponseModel<OrganizationUserBulkResponseModel>> ActivateOrDeactivateUsersAsync(
Guid orgId,
OrganizationUserBulkRequestModel model,
Func<Guid, IEnumerable<Guid>, Guid?, Task<List<Tuple<OrganizationUser, string>>>> statusAction)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User);
var result = await statusAction(orgId, model.Ids, userId.Value);
return new ListResponseModel<OrganizationUserBulkResponseModel>(result.Select(r =>
new OrganizationUserBulkResponseModel(r.Item1.Id, r.Item2)));
}
}
}

View File

@ -51,6 +51,8 @@
OrganizationUser_AdminResetPassword = 1508,
OrganizationUser_ResetSsoLink = 1509,
OrganizationUser_FirstSsoLogin = 1510,
OrganizationUser_Deactivated = 1511,
OrganizationUser_Activated = 1512,
Organization_Updated = 1600,
Organization_PurgedVault = 1601,

View File

@ -1,9 +1,10 @@
namespace Bit.Core.Enums
{
public enum OrganizationUserStatusType : byte
public enum OrganizationUserStatusType : short
{
Invited = 0,
Accepted = 1,
Confirmed = 2
Confirmed = 2,
Deactivated = -1,
}
}

View File

@ -39,5 +39,7 @@ namespace Bit.Core.Repositories
Task<OrganizationUser> GetByOrganizationEmailAsync(Guid organizationId, string email);
Task<IEnumerable<OrganizationUserPublicKey>> GetManyPublicKeysByOrganizationUserAsync(Guid organizationId, IEnumerable<Guid> Ids);
Task<IEnumerable<OrganizationUserUserDetails>> GetManyByMinimumRoleAsync(Guid organizationId, OrganizationUserType minRole);
Task DeactivateAsync(Guid id);
Task ActivateAsync(Guid id, OrganizationUserStatusType status);
}
}

View File

@ -61,5 +61,11 @@ namespace Bit.Core.Services
Task DeleteSsoUserAsync(Guid userId, Guid? organizationId);
Task<Organization> UpdateOrganizationKeysAsync(Guid orgId, string publicKey, string privateKey);
Task<bool> HasConfirmedOwnersExceptAsync(Guid organizationId, IEnumerable<Guid> organizationUsersId, bool includeProvider = true);
Task DeactivateUserAsync(OrganizationUser organizationUser, Guid? disablingUserId);
Task<List<Tuple<OrganizationUser, string>>> DeactivateUsersAsync(Guid organizationId,
IEnumerable<Guid> organizationUserIds, Guid? disablingUserId);
Task ActivateUserAsync(OrganizationUser organizationUser, Guid? enablingUserId);
Task<List<Tuple<OrganizationUser, string>>> ActivateUsersAsync(Guid organizationId,
IEnumerable<Guid> organizationUserIds, Guid? enablingUserId);
}
}

View File

@ -2186,5 +2186,186 @@ namespace Bit.Core.Services
throw new BadRequestException("You cannot delete an Organization that is using Key Connector.");
}
}
public async Task DeactivateUserAsync(OrganizationUser organizationUser, Guid? disablingUserId)
{
if (organizationUser.Status == OrganizationUserStatusType.Deactivated)
{
throw new BadRequestException("Already deactivated.");
}
if (disablingUserId.HasValue && organizationUser.UserId == disablingUserId.Value)
{
throw new BadRequestException("You cannot deactivate yourself.");
}
if (organizationUser.Type == OrganizationUserType.Owner && disablingUserId.HasValue &&
!await _currentContext.OrganizationOwner(organizationUser.OrganizationId))
{
throw new BadRequestException("Only owners can deactivate other owners.");
}
if (!await HasConfirmedOwnersExceptAsync(organizationUser.OrganizationId, new[] { organizationUser.Id }))
{
throw new BadRequestException("Organization must have at least one confirmed owner.");
}
await _organizationUserRepository.DeactivateAsync(organizationUser.Id);
organizationUser.Status = OrganizationUserStatusType.Deactivated;
await _eventService.LogOrganizationUserEventAsync(organizationUser, EventType.OrganizationUser_Deactivated);
}
public async Task<List<Tuple<OrganizationUser, string>>> DeactivateUsersAsync(Guid organizationId,
IEnumerable<Guid> organizationUserIds, Guid? disablingUserId)
{
var orgUsers = await _organizationUserRepository.GetManyAsync(organizationUserIds);
var filteredUsers = orgUsers.Where(u => u.OrganizationId == organizationId)
.ToList();
if (!filteredUsers.Any())
{
throw new BadRequestException("Users invalid.");
}
if (!await HasConfirmedOwnersExceptAsync(organizationId, organizationUserIds))
{
throw new BadRequestException("Organization must have at least one confirmed owner.");
}
var deletingUserIsOwner = false;
if (disablingUserId.HasValue)
{
deletingUserIsOwner = await _currentContext.OrganizationOwner(organizationId);
}
var result = new List<Tuple<OrganizationUser, string>>();
foreach (var organizationUser in filteredUsers)
{
try
{
if (disablingUserId.HasValue && organizationUser.UserId == disablingUserId)
{
throw new BadRequestException("You cannot deactivate yourself.");
}
if (organizationUser.Type == OrganizationUserType.Owner && disablingUserId.HasValue && !deletingUserIsOwner)
{
throw new BadRequestException("Only owners can deactivate other owners.");
}
await _organizationUserRepository.DeactivateAsync(organizationUser.Id);
organizationUser.Status = OrganizationUserStatusType.Deactivated;
await _eventService.LogOrganizationUserEventAsync(organizationUser, EventType.OrganizationUser_Deactivated);
result.Add(Tuple.Create(organizationUser, ""));
}
catch (BadRequestException e)
{
result.Add(Tuple.Create(organizationUser, e.Message));
}
}
return result;
}
public async Task ActivateUserAsync(OrganizationUser organizationUser, Guid? enablingUserId)
{
if (organizationUser.Status != OrganizationUserStatusType.Deactivated)
{
throw new BadRequestException("Already active.");
}
if (enablingUserId.HasValue && organizationUser.UserId == enablingUserId.Value)
{
throw new BadRequestException("You cannot activate yourself.");
}
if (organizationUser.Type == OrganizationUserType.Owner && enablingUserId.HasValue &&
!await _currentContext.OrganizationOwner(organizationUser.OrganizationId))
{
throw new BadRequestException("Only owners can activate other owners.");
}
var status = GetPriorActiveOrganizationUserStatusType(organizationUser);
await _organizationUserRepository.ActivateAsync(organizationUser.Id, status);
organizationUser.Status = status;
await _eventService.LogOrganizationUserEventAsync(organizationUser, EventType.OrganizationUser_Activated);
}
public async Task<List<Tuple<OrganizationUser, string>>> ActivateUsersAsync(Guid organizationId,
IEnumerable<Guid> organizationUserIds, Guid? enablingUserId)
{
var orgUsers = await _organizationUserRepository.GetManyAsync(organizationUserIds);
var filteredUsers = orgUsers.Where(u => u.OrganizationId == organizationId)
.ToList();
if (!filteredUsers.Any())
{
throw new BadRequestException("Users invalid.");
}
var deletingUserIsOwner = false;
if (enablingUserId.HasValue)
{
deletingUserIsOwner = await _currentContext.OrganizationOwner(organizationId);
}
var result = new List<Tuple<OrganizationUser, string>>();
foreach (var organizationUser in filteredUsers)
{
try
{
if (organizationUser.Status != OrganizationUserStatusType.Deactivated)
{
throw new BadRequestException("Already active.");
}
if (enablingUserId.HasValue && organizationUser.UserId == enablingUserId)
{
throw new BadRequestException("You cannot activate yourself.");
}
if (organizationUser.Type == OrganizationUserType.Owner && enablingUserId.HasValue && !deletingUserIsOwner)
{
throw new BadRequestException("Only owners can activate other owners.");
}
var status = GetPriorActiveOrganizationUserStatusType(organizationUser);
await _organizationUserRepository.ActivateAsync(organizationUser.Id, status);
organizationUser.Status = status;
await _eventService.LogOrganizationUserEventAsync(organizationUser, EventType.OrganizationUser_Activated);
result.Add(Tuple.Create(organizationUser, ""));
}
catch (BadRequestException e)
{
result.Add(Tuple.Create(organizationUser, e.Message));
}
}
return result;
}
static OrganizationUserStatusType GetPriorActiveOrganizationUserStatusType(OrganizationUser organizationUser)
{
// Determine status to revert back to
var status = OrganizationUserStatusType.Invited;
if (organizationUser.UserId.HasValue && string.IsNullOrWhiteSpace(organizationUser.Email))
{
// Has UserId & Email is null, then Accepted
status = OrganizationUserStatusType.Accepted;
if (!string.IsNullOrWhiteSpace(organizationUser.Key))
{
// We have an org key for this user, user was confirmed
status = OrganizationUserStatusType.Confirmed;
}
}
return status;
}
}
}

View File

@ -409,5 +409,27 @@ namespace Bit.Infrastructure.Dapper.Repositories
return results.ToList();
}
}
public async Task DeactivateAsync(Guid id)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.ExecuteAsync(
$"[{Schema}].[{Table}_Deactivate]",
new { Id = id },
commandType: CommandType.StoredProcedure);
}
}
public async Task ActivateAsync(Guid id, OrganizationUserStatusType status)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.ExecuteAsync(
$"[{Schema}].[{Table}_Activate]",
new { Id = id, Status = status },
commandType: CommandType.StoredProcedure);
}
}
}
}

View File

@ -427,5 +427,43 @@ namespace Bit.Infrastructure.EntityFramework.Repositories
return await query.ToListAsync();
}
}
public async Task DeactivateAsync(Guid id)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var orgUser = await GetDbSet(dbContext).FindAsync(id);
if (orgUser != null)
{
dbContext.Update(orgUser);
orgUser.Status = OrganizationUserStatusType.Deactivated;
await dbContext.SaveChangesAsync();
if (orgUser.UserId.HasValue)
{
await UserBumpAccountRevisionDate(orgUser.UserId.Value);
}
}
}
}
public async Task ActivateAsync(Guid id, OrganizationUserStatusType status)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var orgUser = await GetDbSet(dbContext).FindAsync(id);
if (orgUser != null)
{
dbContext.Update(orgUser);
orgUser.Status = status;
await dbContext.SaveChangesAsync();
if (orgUser.UserId.HasValue)
{
await UserBumpAccountRevisionDate(orgUser.UserId.Value);
}
}
}
}
}
}

View File

@ -122,6 +122,8 @@
<Build Include="dbo\Stored Procedures\Grant_DeleteByKey.sql" />
<Build Include="dbo\Stored Procedures\OrganizationUser_DeleteById.sql" />
<Build Include="dbo\Stored Procedures\OrganizationUser_DeleteByIds.sql" />
<Build Include="dbo\Stored Procedures\OrganizationUser_Deactivate.sql" />
<Build Include="dbo\Stored Procedures\OrganizationUser_Activate.sql" />
<Build Include="dbo\Stored Procedures\Grant_Delete.sql" />
<Build Include="dbo\Stored Procedures\OrganizationUser_ReadById.sql" />
<Build Include="dbo\Stored Procedures\OrganizationUser_ReadByIds.sql" />

View File

@ -2,7 +2,7 @@ CREATE FUNCTION [dbo].[PolicyApplicableToUser]
(
@UserId UNIQUEIDENTIFIER,
@PolicyType TINYINT,
@MinimumStatus TINYINT
@MinimumStatus SMALLINT
)
RETURNS TABLE
AS RETURN

View File

@ -1,6 +1,6 @@
CREATE PROCEDURE [dbo].[OrganizationUserOrganizationDetails_ReadByUserIdStatus]
@UserId UNIQUEIDENTIFIER,
@Status TINYINT
@Status SMALLINT
AS
BEGIN
SET NOCOUNT ON

View File

@ -1,6 +1,6 @@
CREATE PROCEDURE [dbo].[OrganizationUserOrganizationDetails_ReadByUserIdStatusOrganizationId]
@UserId UNIQUEIDENTIFIER,
@Status TINYINT,
@Status SMALLINT,
@OrganizationId UNIQUEIDENTIFIER
AS
BEGIN

View File

@ -0,0 +1,17 @@
CREATE PROCEDURE [dbo].[OrganizationUser_Activate]
@Id UNIQUEIDENTIFIER,
@Status SMALLINT
AS
BEGIN
SET NOCOUNT ON
UPDATE
[dbo].[OrganizationUser]
SET
[Status] = @Status
WHERE
[Id] = @Id
AND [Status] = -1 -- Deactivated
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationUserId] @Id
END

View File

@ -4,7 +4,7 @@
@UserId UNIQUEIDENTIFIER,
@Email NVARCHAR(256),
@Key VARCHAR(MAX),
@Status TINYINT,
@Status SMALLINT,
@Type TINYINT,
@AccessAll BIT,
@ExternalId NVARCHAR(300),

View File

@ -4,7 +4,7 @@
@UserId UNIQUEIDENTIFIER,
@Email NVARCHAR(256),
@Key VARCHAR(MAX),
@Status TINYINT,
@Status SMALLINT,
@Type TINYINT,
@AccessAll BIT,
@ExternalId NVARCHAR(300),

View File

@ -0,0 +1,15 @@
CREATE PROCEDURE [dbo].[OrganizationUser_Deactivate]
@Id UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
UPDATE
[dbo].[OrganizationUser]
SET
[Status] = -1 -- Deactivated
WHERE
[Id] = @Id
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationUserId] @Id
END

View File

@ -4,7 +4,7 @@
@UserId UNIQUEIDENTIFIER,
@Email NVARCHAR(256),
@Key VARCHAR(MAX),
@Status TINYINT,
@Status SMALLINT,
@Type TINYINT,
@AccessAll BIT,
@ExternalId NVARCHAR(300),

View File

@ -4,7 +4,7 @@
@UserId UNIQUEIDENTIFIER,
@Email NVARCHAR(256),
@Key VARCHAR(MAX),
@Status TINYINT,
@Status SMALLINT,
@Type TINYINT,
@AccessAll BIT,
@ExternalId NVARCHAR(300),

View File

@ -5,7 +5,7 @@
[Email] NVARCHAR (256) NULL,
[Key] VARCHAR (MAX) NULL,
[ResetPasswordKey] VARCHAR (MAX) NULL,
[Status] TINYINT NOT NULL,
[Status] SMALLINT NOT NULL,
[Type] TINYINT NOT NULL,
[AccessAll] BIT NOT NULL,
[ExternalId] NVARCHAR (300) NULL,

View File

@ -4,7 +4,7 @@ CREATE TYPE [dbo].[OrganizationUserType] AS TABLE(
[UserId] UNIQUEIDENTIFIER,
[Email] NVARCHAR(256),
[Key] VARCHAR(MAX),
[Status] TINYINT,
[Status] SMALLINT,
[Type] TINYINT,
[AccessAll] BIT,
[ExternalId] NVARCHAR(300),

View File

@ -0,0 +1,515 @@
/****************************************************************
*
* WARNING: Index Rebuild on OrganizationUser Table!
* Ensure [IX_OrganizationUser_UserIdOrganizationIdStatus] impact is done after-hours
* or scale DB instance up to handle increased load during update.
*
***************************************************************/
PRINT N'Starting migration for 2022-06-08_00_DeactivatedUserStatus';
GO
PRINT N'Checking dbo.OrganizationUser.Status is TINYINT...';
GO
IF EXISTS (
SELECT TOP 1 NULL
FROM [information_schema].[columns]
WHERE [table_name] = 'OrganizationUser'
AND [table_schema] = 'dbo'
AND [column_name] = 'Status'
AND [data_type] = 'TINYINT'
)
BEGIN
PRINT N'Dropping index IX_OrganizationUser_UserIdOrganizationIdStatus...';
DROP INDEX IF EXISTS [IX_OrganizationUser_UserIdOrganizationIdStatus]
ON [dbo].[OrganizationUser];
PRINT N'Altering dbo.OrganizationUser.Status to SMALLINT...';
ALTER TABLE [dbo].[OrganizationUser]
ALTER COLUMN [Status] SMALLINT NOT NULL;
PRINT N'Recreating index IX_OrganizationUser_UserIdOrganizationIdStatus...';
CREATE NONCLUSTERED INDEX [IX_OrganizationUser_UserIdOrganizationIdStatus]
ON [dbo].[OrganizationUser]([UserId] ASC, [OrganizationId] ASC, [Status] ASC)
INCLUDE ([AccessAll]);
END
GO
PRINT N'Dropping stored procedure, dbo.OrganizationUser_CreateMany...';
GO
IF OBJECT_ID('[dbo].[OrganizationUser_CreateMany]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[OrganizationUser_CreateMany]
END
GO
PRINT N'Dropping stored procedure, dbo.OrganizationUser_UpdateMany...';
GO
IF OBJECT_ID('[dbo].[OrganizationUser_UpdateMany]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[OrganizationUser_UpdateMany]
END
GO
PRINT N'Dropping type dbo.OrganizationUserType...';
GO
IF TYPE_ID(N'[dbo].[OrganizationUserType]') IS NOT NULL
BEGIN
DROP TYPE [dbo].[OrganizationUserType];
END
GO
PRINT N'Recreating Type dbo.OrganizationUserType...';
GO
CREATE TYPE [dbo].[OrganizationUserType] AS TABLE(
[Id] UNIQUEIDENTIFIER,
[OrganizationId] UNIQUEIDENTIFIER,
[UserId] UNIQUEIDENTIFIER,
[Email] NVARCHAR(256),
[Key] VARCHAR(MAX),
[Status] SMALLINT,
[Type] TINYINT,
[AccessAll] BIT,
[ExternalId] NVARCHAR(300),
[CreationDate] DATETIME2(7),
[RevisionDate] DATETIME2(7),
[Permissions] NVARCHAR(MAX),
[ResetPasswordKey] VARCHAR(MAX)
);
GO
PRINT N'Altering stored procedure, dbo.OrganizationUser_CreateMany...';
GO
CREATE OR ALTER PROCEDURE [dbo].[OrganizationUser_CreateMany]
@OrganizationUsersInput [dbo].[OrganizationUserType] READONLY
AS
BEGIN
SET NOCOUNT ON
INSERT INTO [dbo].[OrganizationUser]
(
[Id],
[OrganizationId],
[UserId],
[Email],
[Key],
[Status],
[Type],
[AccessAll],
[ExternalId],
[CreationDate],
[RevisionDate],
[Permissions],
[ResetPasswordKey]
)
SELECT
OU.[Id],
OU.[OrganizationId],
OU.[UserId],
OU.[Email],
OU.[Key],
OU.[Status],
OU.[Type],
OU.[AccessAll],
OU.[ExternalId],
OU.[CreationDate],
OU.[RevisionDate],
OU.[Permissions],
OU.[ResetPasswordKey]
FROM
@OrganizationUsersInput OU
END
GO
PRINT N'Altering stored procedure, dbo.OrganizationUser_UpdateMany...';
GO
CREATE OR ALTER PROCEDURE [dbo].[OrganizationUser_UpdateMany]
@OrganizationUsersInput [dbo].[OrganizationUserType] READONLY
AS
BEGIN
SET NOCOUNT ON
UPDATE
OU
SET
[OrganizationId] = OUI.[OrganizationId],
[UserId] = OUI.[UserId],
[Email] = OUI.[Email],
[Key] = OUI.[Key],
[Status] = OUI.[Status],
[Type] = OUI.[Type],
[AccessAll] = OUI.[AccessAll],
[ExternalId] = OUI.[ExternalId],
[CreationDate] = OUI.[CreationDate],
[RevisionDate] = OUI.[RevisionDate],
[Permissions] = OUI.[Permissions],
[ResetPasswordKey] = OUI.[ResetPasswordKey]
FROM
[dbo].[OrganizationUser] OU
INNER JOIN
@OrganizationUsersInput OUI ON OU.Id = OUI.Id
EXEC [dbo].[User_BumpManyAccountRevisionDates]
(
SELECT UserId
FROM @OrganizationUsersInput
)
END
GO
PRINT N'Altering stored procedure, dbo.OrganizationUser_Create...';
GO
CREATE OR ALTER PROCEDURE [dbo].[OrganizationUser_Create]
@Id UNIQUEIDENTIFIER OUTPUT,
@OrganizationId UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@Email NVARCHAR(256),
@Key VARCHAR(MAX),
@Status SMALLINT,
@Type TINYINT,
@AccessAll BIT,
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@Permissions NVARCHAR(MAX),
@ResetPasswordKey VARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO [dbo].[OrganizationUser]
(
[Id],
[OrganizationId],
[UserId],
[Email],
[Key],
[Status],
[Type],
[AccessAll],
[ExternalId],
[CreationDate],
[RevisionDate],
[Permissions],
[ResetPasswordKey]
)
VALUES
(
@Id,
@OrganizationId,
@UserId,
@Email,
@Key,
@Status,
@Type,
@AccessAll,
@ExternalId,
@CreationDate,
@RevisionDate,
@Permissions,
@ResetPasswordKey
)
END
GO
PRINT N'Altering stored procedure, dbo.OrganizationUser_CreateWithCollections...';
GO
CREATE OR ALTER PROCEDURE [dbo].[OrganizationUser_CreateWithCollections]
@Id UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@Email NVARCHAR(256),
@Key VARCHAR(MAX),
@Status SMALLINT,
@Type TINYINT,
@AccessAll BIT,
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@Permissions NVARCHAR(MAX),
@ResetPasswordKey VARCHAR(MAX),
@Collections AS [dbo].[SelectionReadOnlyArray] READONLY
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[OrganizationUser_Create] @Id, @OrganizationId, @UserId, @Email, @Key, @Status, @Type, @AccessAll, @ExternalId, @CreationDate, @RevisionDate, @Permissions, @ResetPasswordKey
;WITH [AvailableCollectionsCTE] AS(
SELECT
[Id]
FROM
[dbo].[Collection]
WHERE
[OrganizationId] = @OrganizationId
)
INSERT INTO [dbo].[CollectionUser]
(
[CollectionId],
[OrganizationUserId],
[ReadOnly],
[HidePasswords]
)
SELECT
[Id],
@Id,
[ReadOnly],
[HidePasswords]
FROM
@Collections
WHERE
[Id] IN (SELECT [Id] FROM [AvailableCollectionsCTE])
END
GO
PRINT N'Altering stored procedure, dbo.OrganizationUser_Update...';
GO
CREATE OR ALTER PROCEDURE [dbo].[OrganizationUser_Update]
@Id UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@Email NVARCHAR(256),
@Key VARCHAR(MAX),
@Status SMALLINT,
@Type TINYINT,
@AccessAll BIT,
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@Permissions NVARCHAR(MAX),
@ResetPasswordKey VARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON
UPDATE
[dbo].[OrganizationUser]
SET
[OrganizationId] = @OrganizationId,
[UserId] = @UserId,
[Email] = @Email,
[Key] = @Key,
[Status] = @Status,
[Type] = @Type,
[AccessAll] = @AccessAll,
[ExternalId] = @ExternalId,
[CreationDate] = @CreationDate,
[RevisionDate] = @RevisionDate,
[Permissions] = @Permissions,
[ResetPasswordKey] = @ResetPasswordKey
WHERE
[Id] = @Id
EXEC [dbo].[User_BumpAccountRevisionDate] @UserId
END
GO
PRINT N'Altering stored procedure, dbo.OrganizationUser_UpdateWithCollections...';
GO
CREATE OR ALTER PROCEDURE [dbo].[OrganizationUser_UpdateWithCollections]
@Id UNIQUEIDENTIFIER,
@OrganizationId UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER,
@Email NVARCHAR(256),
@Key VARCHAR(MAX),
@Status SMALLINT,
@Type TINYINT,
@AccessAll BIT,
@ExternalId NVARCHAR(300),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@Permissions NVARCHAR(MAX),
@ResetPasswordKey VARCHAR(MAX),
@Collections AS [dbo].[SelectionReadOnlyArray] READONLY
AS
BEGIN
SET NOCOUNT ON
EXEC [dbo].[OrganizationUser_Update] @Id, @OrganizationId, @UserId, @Email, @Key, @Status, @Type, @AccessAll, @ExternalId, @CreationDate, @RevisionDate, @Permissions, @ResetPasswordKey
-- Update
UPDATE
[Target]
SET
[Target].[ReadOnly] = [Source].[ReadOnly],
[Target].[HidePasswords] = [Source].[HidePasswords]
FROM
[dbo].[CollectionUser] AS [Target]
INNER JOIN
@Collections AS [Source] ON [Source].[Id] = [Target].[CollectionId]
WHERE
[Target].[OrganizationUserId] = @Id
AND (
[Target].[ReadOnly] != [Source].[ReadOnly]
OR [Target].[HidePasswords] != [Source].[HidePasswords]
)
-- Insert
INSERT INTO
[dbo].[CollectionUser]
SELECT
[Source].[Id],
@Id,
[Source].[ReadOnly],
[Source].[HidePasswords]
FROM
@Collections AS [Source]
INNER JOIN
[dbo].[Collection] C ON C.[Id] = [Source].[Id] AND C.[OrganizationId] = @OrganizationId
WHERE
NOT EXISTS (
SELECT
1
FROM
[dbo].[CollectionUser]
WHERE
[CollectionId] = [Source].[Id]
AND [OrganizationUserId] = @Id
)
-- Delete
DELETE
CU
FROM
[dbo].[CollectionUser] CU
WHERE
CU.[OrganizationUserId] = @Id
AND NOT EXISTS (
SELECT
1
FROM
@Collections
WHERE
[Id] = CU.[CollectionId]
)
END
GO
PRINT N'Altering stored procedure, dbo.OrganizationUserOrganizationDetails_ReadByUserIdStatus...';
GO
CREATE OR ALTER PROCEDURE [dbo].[OrganizationUserOrganizationDetails_ReadByUserIdStatus]
@UserId UNIQUEIDENTIFIER,
@Status SMALLINT
AS
BEGIN
SET NOCOUNT ON
SELECT
*
FROM
[dbo].[OrganizationUserOrganizationDetailsView]
WHERE
[UserId] = @UserId
AND (@Status IS NULL OR [Status] = @Status)
END
GO
PRINT N'Altering stored procedure, dbo.OrganizationUserOrganizationDetails_ReadByUserIdStatusOrganizationId...';
GO
CREATE OR ALTER PROCEDURE [dbo].[OrganizationUserOrganizationDetails_ReadByUserIdStatusOrganizationId]
@UserId UNIQUEIDENTIFIER,
@Status SMALLINT,
@OrganizationId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
*
FROM
[dbo].[OrganizationUserOrganizationDetailsView]
WHERE
[UserId] = @UserId
AND [OrganizationId] = @OrganizationId
AND (@Status IS NULL OR [Status] = @Status)
END
GO
PRINT N'Altering function, dbo.PolicyApplicableToUser...';
GO
CREATE OR ALTER FUNCTION [dbo].[PolicyApplicableToUser]
(
@UserId UNIQUEIDENTIFIER,
@PolicyType TINYINT,
@MinimumStatus SMALLINT
)
RETURNS TABLE
AS RETURN
SELECT
P.*
FROM
[dbo].[PolicyView] P
INNER JOIN
[dbo].[OrganizationUserView] OU ON P.[OrganizationId] = OU.[OrganizationId]
LEFT JOIN
(SELECT
PU.UserId,
PO.OrganizationId
FROM
[dbo].[ProviderUserView] PU
INNER JOIN
[ProviderOrganizationView] PO ON PO.[ProviderId] = PU.[ProviderId]) PUPO
ON PUPO.UserId = OU.UserId
AND PUPO.OrganizationId = P.OrganizationId
WHERE
(
(
OU.[Status] > 0
AND OU.[UserId] = @UserId
)
OR (
OU.[Status] = 0 -- 'Invited' OrgUsers are not linked to a UserId yet, so we have to look up their email
AND OU.[Email] IN (SELECT U.Email FROM [dbo].[UserView] U WHERE U.Id = @UserId)
)
)
AND P.[Type] = @PolicyType
AND P.[Enabled] = 1
AND OU.[Status] >= @MinimumStatus
AND OU.[Type] >= 2 -- Not an owner (0) or admin (1)
AND ( -- Can't manage policies
OU.[Permissions] IS NULL
OR COALESCE(JSON_VALUE(OU.[Permissions], '$.managePolicies'), 'false') = 'false'
)
AND PUPO.[UserId] IS NULL -- Not a provider
GO
PRINT N'Altering stored procedure, dbo.OrganizationUser_Deactivate';
GO
CREATE OR ALTER PROCEDURE [dbo].[OrganizationUser_Deactivate]
@Id UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
UPDATE
[dbo].[OrganizationUser]
SET
[Status] = -1 -- Deactivated
WHERE
[Id] = @Id
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationUserId] @Id
END
GO
PRINT N'Altering stored procedure, dbo.OrganizationUser_Activate';
GO
CREATE OR ALTER PROCEDURE [dbo].[OrganizationUser_Activate]
@Id UNIQUEIDENTIFIER,
@Status SMALLINT
AS
BEGIN
SET NOCOUNT ON
UPDATE
[dbo].[OrganizationUser]
SET
[Status] = @Status
WHERE
[Id] = @Id
AND [Status] = -1 -- Deactivated
EXEC [dbo].[User_BumpAccountRevisionDateByOrganizationUserId] @Id
END
GO
PRINT N'Finished migration for 2022-06-08_00_DeactivatedUserStatus';
GO

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
namespace Bit.MySqlMigrations.Migrations
{
public partial class DeactivatedUserStatus : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<short>(
name: "Status",
table: "OrganizationUser",
type: "smallint",
nullable: false,
oldClrType: typeof(byte),
oldType: "tinyint unsigned");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<byte>(
name: "Status",
table: "OrganizationUser",
type: "tinyint unsigned",
nullable: false,
oldClrType: typeof(short),
oldType: "smallint");
}
}
}

View File

@ -713,8 +713,8 @@ namespace Bit.MySqlMigrations.Migrations
b.Property<DateTime>("RevisionDate")
.HasColumnType("datetime(6)");
b.Property<byte>("Status")
.HasColumnType("tinyint unsigned");
b.Property<short>("Status")
.HasColumnType("smallint");
b.Property<byte>("Type")
.HasColumnType("tinyint unsigned");

View File

@ -0,0 +1,8 @@
START TRANSACTION;
ALTER TABLE `OrganizationUser` MODIFY COLUMN `Status` smallint NOT NULL;
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('20220608191914_DeactivatedUserStatus', '5.0.12');
COMMIT;