1
0
mirror of https://github.com/bitwarden/server.git synced 2024-12-05 14:23:30 +01:00
bitwarden-server/util/Migrator/DbScripts/2021-09-16_00_PolicyApplicableToUser.sql
Thomas Rittson 66629b2f1c
Refactor policy checks (#1536)
* Move policy checking logic inside PolicyService

* Refactor to use currentContext.ManagePolicies

* Make orgUser status check more semantic

* Fix single org user checks

* Use CoreHelper implementation to deserialize json

* Refactor policy checks to use db query

* Use new db query for enforcing 2FA Policy

* Add Policy_ReadByTypeApplicableToUser

* Stub out EF implementations

* Refactor: use PolicyRepository only

* Refactor tests

* Copy SQL queries to proj and update sqlproj file

* Refactor importCiphersAsync to use new method

* Add EF implementations and tests

* Refactor SQL to remove unnecessary operations
2021-09-28 06:54:28 +10:00

83 lines
2.0 KiB
Transact-SQL

-- PolicyApplicableToUser
IF OBJECT_ID('[dbo].[PolicyApplicableToUser]') IS NOT NULL
BEGIN
DROP FUNCTION [dbo].[PolicyApplicableToUser]
END
GO
CREATE FUNCTION [dbo].[PolicyApplicableToUser]
(
@UserId UNIQUEIDENTIFIER,
@PolicyType TINYINT,
@MinimumStatus TINYINT
)
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.[UserId] = @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
-- Policy_ReadByTypeApplicableToUser
IF OBJECT_ID('[dbo].[Policy_ReadByTypeApplicableToUser]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[Policy_ReadByTypeApplicableToUser]
END
GO
CREATE PROCEDURE [dbo].[Policy_ReadByTypeApplicableToUser]
@UserId UNIQUEIDENTIFIER,
@PolicyType TINYINT,
@MinimumStatus TINYINT
AS
BEGIN
SET NOCOUNT ON
SELECT *
FROM [dbo].[PolicyApplicableToUser](@UserId, @PolicyType, @MinimumStatus)
END
GO
-- Policy_CountByTypeApplicableToUser
IF OBJECT_ID('[dbo].[Policy_CountByTypeApplicableToUser]') IS NOT NULL
BEGIN
DROP PROCEDURE [dbo].[Policy_CountByTypeApplicableToUser]
END
GO
CREATE PROCEDURE [dbo].[Policy_CountByTypeApplicableToUser]
@UserId UNIQUEIDENTIFIER,
@PolicyType TINYINT,
@MinimumStatus TINYINT
AS
BEGIN
SET NOCOUNT ON
SELECT COUNT(1)
FROM [dbo].[PolicyApplicableToUser](@UserId, @PolicyType, @MinimumStatus)
END