1
0
mirror of https://github.com/bitwarden/server.git synced 2025-03-13 13:39:35 +01:00
bitwarden-server/util/Migrator/DbScripts/2025-01-10_00_ReadActiveWithPendingAuthRequestsByUserId.sql
Jared Snider 72bb06a9d7
Auth/PM-16947 - Device Management - Adjust Device + pending auth request get query (#5250)
* Added userId check on query

* Added required field to inner select

* PM-16947 - Update to filter inner subquery on user id per discussion with Robert

* Updated to use new query with ROW_NUMBER

* More query optimizations to eliminate returning old requests for a device

* Fixed approval condition to be NULL as 0 means denied.

* Added negation of @ExpirationMinutes

---------

Co-authored-by: Todd Martin <tmartin@bitwarden.com>
2025-01-10 21:55:34 -05:00

30 lines
1.2 KiB
Transact-SQL

CREATE OR ALTER PROCEDURE [dbo].[Device_ReadActiveWithPendingAuthRequestsByUserId]
@UserId UNIQUEIDENTIFIER,
@ExpirationMinutes INT
AS
BEGIN
SET NOCOUNT ON;
SELECT
D.*,
AR.Id as AuthRequestId,
AR.CreationDate as AuthRequestCreationDate
FROM dbo.DeviceView D
LEFT JOIN (
SELECT
Id,
CreationDate,
RequestDeviceIdentifier,
Approved,
ROW_NUMBER() OVER (PARTITION BY RequestDeviceIdentifier ORDER BY CreationDate DESC) as rn
FROM dbo.AuthRequestView
WHERE Type IN (0, 1) -- AuthenticateAndUnlock and Unlock types only
AND CreationDate >= DATEADD(MINUTE, -@ExpirationMinutes, GETUTCDATE()) -- Ensure the request hasn't expired
AND UserId = @UserId -- Requests for this user only
) AR -- This join will get the most recent request per device, regardless of approval status
ON D.Identifier = AR.RequestDeviceIdentifier AND AR.rn = 1 AND AR.Approved IS NULL -- Get only the most recent unapproved request per device
WHERE
D.UserId = @UserId -- Include only devices for this user
AND D.Active = 1; -- Include only active devices
END;