1
0
mirror of https://github.com/bitwarden/server synced 2026-02-28 02:13:19 +00:00

Auth/PM-32035 - Emergency Access - DeleteEmergencyAccessCommand refactor (#7054)

* PM-32035 - EmergencyAccessService - fix interface docs, method docs, and tests to cover grantee / grantor deletion which is supported today.

* PM-32035 - EmergencyAccessService - mark existing delete as deprecated

* PM-32035 - EmergencyAccess readme docs - fix deletion docs

* PM-32035 - Add new EmergencyAccessDetails_ReadByUserIds stored proc

* PM-32035 - Add migration script for EmergencyAccessDetails_ReadByUserIds

* PM-32035 - Build out GetManyDetailsByUserIdsAsync in repository layer plus add tests

* PM-32035 - EmergencyAccessRepo - DeleteManyAsync - remove grantee revision bump as not necessary since no EA sync data exists + update tests

* PM-32035 - Fix incorrect nullability annotation on EmergencyAccessDetails.GrantorEmail. Both the SQL view and EF projection use a LEFT JOIN to the User table, meaning the value can be null if the grantor's account no longer exists. Changed to string? and removed the required modifier since the class is only ever materialized from database queries, never directly instantiated.

* PM-32035 - Refactor DeleteEmergencyAccess command to offer new DeleteAllByUserIdAsync and DeleteAllByUserIdsAsync methods. Need to build out DeleteByIdAndUserIdAsync with a new stored proc.

* PM-32035 - Build out IEmergencyAccessRepository.GetDetailsByIdAsync because we need such a method in order to meet the product requirements to send grantor email notifications for normal deletions in the future.

* PM-32035 - Wire up DeleteEmergencyAccessCommand.DeleteByIdAndUserIdAsync to use new repository method emergencyAccessRepository.GetDetailsByIdAsync so we can send notifications. Now, it is full replacement for the existing emergency access service deletion method + has the new notification functionaliy requested.

* PM-32035 - Add more test coverage for DeleteByIdAndUserIdAsync

* PM-32035 - Fix missing GranteeAvatarColor and GrantorAvatarColor projections in EmergencyAccessDetailsViewQuery. The EF view query omitted both avatar color fields from its Select projection, causing the integration tests to fail on all non-SqlServer databases (MySql, Postgres, Sqlite) where EF is used instead of Dapper.

* PM-32035 - Rename migration after main merge revealed collision

* PM-32035 - Rename migration script

* PM-32035 - PR feedback - add ticket + todos to deprecated delete async method.

* PM-32035 - DeleteEmergencyAccessCommand - add logs if we don't have user data required to send email notifications.

* PM-32035 - PR Feedback - rename EmergencyAccessDetails_ReadByUserIds to EmergencyAccessDetails_ReadManyByUserIds
This commit is contained in:
Jared Snider
2026-02-26 12:49:26 -05:00
committed by GitHub
parent fd5ea2f7b3
commit 18973a4f63
17 changed files with 1400 additions and 272 deletions

View File

@@ -8,9 +8,6 @@ public class EmergencyAccessDetails : EmergencyAccess
public string? GranteeEmail { get; set; }
public string? GranteeAvatarColor { get; set; }
public string? GrantorName { get; set; }
/// <summary>
/// Grantor email is assumed not null because in order to create an emergency access the grantor must be an existing user.
/// </summary>
public required string GrantorEmail { get; set; }
public string? GrantorEmail { get; set; }
public string? GrantorAvatarColor { get; set; }
}

View File

@@ -10,6 +10,12 @@ public interface IEmergencyAccessRepository : IRepository<EmergencyAccess, Guid>
Task<ICollection<EmergencyAccessDetails>> GetManyDetailsByGrantorIdAsync(Guid grantorId);
Task<ICollection<EmergencyAccessDetails>> GetManyDetailsByGranteeIdAsync(Guid granteeId);
/// <summary>
/// Gets all emergency access details where the user IDs are either grantors or grantees
/// </summary>
/// <param name="userIds">Collection of user IDs to query</param>
/// <returns>All emergency access details matching the user IDs</returns>
Task<ICollection<EmergencyAccessDetails>> GetManyDetailsByUserIdsAsync(ICollection<Guid> userIds);
/// <summary>
/// Fetches emergency access details by EmergencyAccess id and grantor id
/// </summary>
/// <param name="id">Emergency Access Id</param>
@@ -17,6 +23,12 @@ public interface IEmergencyAccessRepository : IRepository<EmergencyAccess, Guid>
/// <returns>EmergencyAccessDetails or null</returns>
Task<EmergencyAccessDetails?> GetDetailsByIdGrantorIdAsync(Guid id, Guid grantorId);
/// <summary>
/// Fetches emergency access details by EmergencyAccess id
/// </summary>
/// <param name="id">Emergency Access Id</param>
/// <returns>EmergencyAccessDetails or null</returns>
Task<EmergencyAccessDetails?> GetDetailsByIdAsync(Guid id);
/// <summary>
/// Database call to fetch emergency accesses that need notification emails sent through a Job
/// </summary>
/// <returns>collection of EmergencyAccessNotify objects that require notification</returns>

View File

@@ -1,107 +1,148 @@
using Bit.Core.Auth.Models.Data;
using Bit.Core.Auth.UserFeatures.EmergencyAccess.Interfaces;
using Bit.Core.Auth.UserFeatures.EmergencyAccess.Interfaces;
using Bit.Core.Auth.UserFeatures.EmergencyAccess.Mail;
using Bit.Core.Exceptions;
using Bit.Core.Platform.Mail.Mailer;
using Bit.Core.Repositories;
using Microsoft.Extensions.Logging;
namespace Bit.Core.Auth.UserFeatures.EmergencyAccess.Commands;
public class DeleteEmergencyAccessCommand(
IEmergencyAccessRepository _emergencyAccessRepository,
IMailer mailer) : IDeleteEmergencyAccessCommand
IMailer mailer,
ILogger<DeleteEmergencyAccessCommand> _logger) : IDeleteEmergencyAccessCommand
{
/// <inheritdoc />
public async Task<EmergencyAccessDetails> DeleteByIdGrantorIdAsync(Guid emergencyAccessId, Guid grantorId)
public async Task DeleteByIdAndUserIdAsync(Guid emergencyAccessId, Guid userId)
{
var emergencyAccessDetails = await _emergencyAccessRepository.GetDetailsByIdGrantorIdAsync(emergencyAccessId, grantorId);
var emergencyAccessDetails = await _emergencyAccessRepository.GetDetailsByIdAsync(emergencyAccessId);
if (emergencyAccessDetails == null || emergencyAccessDetails.GrantorId != grantorId)
// Error if the emergency access doesn't exist or the user trying to delete is neither the grantor nor the grantee
if (emergencyAccessDetails == null || (emergencyAccessDetails.GrantorId != userId && emergencyAccessDetails.GranteeId != userId))
{
throw new BadRequestException("Emergency Access not valid.");
}
var (grantorEmails, granteeEmails) = await DeleteEmergencyAccessAsync([emergencyAccessDetails]);
await _emergencyAccessRepository.DeleteAsync(emergencyAccessDetails);
// Send notification email to grantor
await SendEmergencyAccessRemoveGranteesEmailAsync(grantorEmails, granteeEmails);
return emergencyAccessDetails;
// Emails may be null if the grantor or grantee user account has since been deleted
// so ensure we have both emails we need.
if (!string.IsNullOrEmpty(emergencyAccessDetails.GrantorEmail) &&
!string.IsNullOrEmpty(emergencyAccessDetails.GranteeEmail))
{
await SendGranteesRemovalNotificationToGrantorAsync(
emergencyAccessDetails.GrantorEmail,
[emergencyAccessDetails.GranteeEmail]);
}
else
{
// If we are missing the emails needed to send a notification, log this occurrence.
_logger.LogWarning(
"Emergency access deletion notification skipped for grantor {GrantorId} and grantee {GranteeId}: GrantorEmail missing: {GrantorEmailMissing}, GranteeEmail missing: {GranteeEmailMissing}.",
emergencyAccessDetails.GrantorId,
emergencyAccessDetails.GranteeId,
string.IsNullOrEmpty(emergencyAccessDetails.GrantorEmail),
string.IsNullOrEmpty(emergencyAccessDetails.GranteeEmail));
}
}
/// <inheritdoc />
public async Task<ICollection<EmergencyAccessDetails>?> DeleteAllByGrantorIdAsync(Guid grantorId)
public async Task DeleteAllByUserIdAsync(Guid userId)
{
var emergencyAccessDetails = await _emergencyAccessRepository.GetManyDetailsByGrantorIdAsync(grantorId);
await DeleteAllByUserIdsAsync([userId]);
}
/// <inheritdoc />
public async Task DeleteAllByUserIdsAsync(ICollection<Guid> userIds)
{
var emergencyAccessDetails = await _emergencyAccessRepository.GetManyDetailsByUserIdsAsync(userIds);
// if there is nothing return an empty array and do not send an email
if (emergencyAccessDetails.Count == 0)
{
return emergencyAccessDetails;
// No records found, so nothing to delete or notify
// However, don't throw an error since the end state of "no records for these user IDs"
// is already achieved
return;
}
var (grantorEmails, granteeEmails) = await DeleteEmergencyAccessAsync(emergencyAccessDetails);
// Delete all records using existing DeleteManyAsync (batching already implemented)
var emergencyAccessIds = emergencyAccessDetails.Select(ea => ea.Id).ToList();
await _emergencyAccessRepository.DeleteManyAsync(emergencyAccessIds);
// Send notification email to grantor
await SendEmergencyAccessRemoveGranteesEmailAsync(grantorEmails, granteeEmails);
// After deletion, send notifications to grantors about their removed grantees.
// GrantorEmail may be null when a grantor's account has been deleted, since it is sourced
// entirely from a LEFT JOIN on the User table with no fallback column. Log any affected
// GrantorIds up front for traceability — the grantor's account is already gone so the ID
// cannot be used to look up the user, but it can be correlated with audit logs generated
// at the time of that account's deletion to understand why the notification was skipped.
var grantorIdsWithNullEmail = emergencyAccessDetails
.Where(ea => string.IsNullOrEmpty(ea.GrantorEmail))
.Select(ea => ea.GrantorId)
.Distinct()
.ToList();
return emergencyAccessDetails;
}
/// <inheritdoc />
public async Task<ICollection<EmergencyAccessDetails>?> DeleteAllByGranteeIdAsync(Guid granteeId)
{
var emergencyAccessDetails = await _emergencyAccessRepository.GetManyDetailsByGranteeIdAsync(granteeId);
// if there is nothing return an empty array
if (emergencyAccessDetails == null || emergencyAccessDetails.Count == 0)
if (grantorIdsWithNullEmail.Count > 0)
{
return emergencyAccessDetails;
_logger.LogWarning(
"Emergency access deletion notification skipped for {Count} grantor(s) with missing GrantorEmail. GrantorIds: {GrantorIds}.",
grantorIdsWithNullEmail.Count,
grantorIdsWithNullEmail);
}
var (grantorEmails, granteeEmails) = await DeleteEmergencyAccessAsync(emergencyAccessDetails);
// Group by grantor email to send each grantor a single email listing all their removed grantees.
// Records with null GrantorEmail are excluded above and will not receive a notification.
var grantorEmergencyAccessDetailGroups = emergencyAccessDetails
.Where(ea => !string.IsNullOrEmpty(ea.GrantorEmail))
.GroupBy(ea => ea.GrantorEmail!); // .GrantorEmail is safe here due to the Where above
// Send notification email to grantor(s)
await SendEmergencyAccessRemoveGranteesEmailAsync(grantorEmails, granteeEmails);
return emergencyAccessDetails;
}
private async Task<(HashSet<string> grantorEmails, HashSet<string> granteeEmails)> DeleteEmergencyAccessAsync(IEnumerable<EmergencyAccessDetails> emergencyAccessDetails)
{
var grantorEmails = new HashSet<string>();
var granteeEmails = new HashSet<string>();
await _emergencyAccessRepository.DeleteManyAsync([.. emergencyAccessDetails.Select(ea => ea.Id)]);
foreach (var details in emergencyAccessDetails)
foreach (var grantorGroup in grantorEmergencyAccessDetailGroups)
{
granteeEmails.Add(details.GranteeEmail ?? string.Empty);
grantorEmails.Add(details.GrantorEmail);
}
var grantorEmail = grantorGroup.Key;
var granteeEmails = grantorGroup
.Select(ea => ea.GranteeEmail)
// Filter out null grantee emails, which may occur if a grantee's account has been deleted
.Where(e => !string.IsNullOrEmpty(e))
.Cast<string>() // Cast is safe here due to the Where above
.Distinct();
return (grantorEmails, granteeEmails);
var granteeIdsWithNullEmail = grantorGroup
.Where(ea => string.IsNullOrEmpty(ea.GranteeEmail))
.Select(ea => ea.GranteeId)
.Distinct()
.ToList();
if (granteeIdsWithNullEmail.Count > 0)
{
_logger.LogWarning(
"Emergency access deletion notification skipped for {Count} grantee(s) with missing GranteeEmail. GranteeIds: {GranteeIds}.",
granteeIdsWithNullEmail.Count,
granteeIdsWithNullEmail);
}
if (granteeEmails.Any())
{
await SendGranteesRemovalNotificationToGrantorAsync(grantorEmail, granteeEmails);
}
}
}
/// <summary>
/// Sends an email notification to the grantor about removed grantees.
/// Sends an email notification to a grantor about their removed grantees.
/// </summary>
/// <param name="grantorEmails">The email addresses of the grantors to notify when deleting by grantee</param>
/// <param name="formattedGranteeIdentifiers">The formatted identifiers of the removed grantees to include in the email</param>
/// <returns></returns>
private async Task SendEmergencyAccessRemoveGranteesEmailAsync(IEnumerable<string> grantorEmails, IEnumerable<string> formattedGranteeIdentifiers)
/// <param name="grantorEmail">The email address of the grantor to notify</param>
/// <param name="granteeEmails">The email addresses of the removed grantees</param>
private async Task SendGranteesRemovalNotificationToGrantorAsync(string grantorEmail, IEnumerable<string> granteeEmails)
{
foreach (var email in grantorEmails)
var emailViewModel = new EmergencyAccessRemoveGranteesMail
{
var emailViewModel = new EmergencyAccessRemoveGranteesMail
ToEmails = [grantorEmail],
View = new EmergencyAccessRemoveGranteesMailView
{
ToEmails = [email],
View = new EmergencyAccessRemoveGranteesMailView
{
RemovedGranteeEmails = formattedGranteeIdentifiers
}
};
RemovedGranteeEmails = granteeEmails
}
};
await mailer.SendEmail(emailViewModel);
}
await mailer.SendEmail(emailViewModel);
}
}

View File

@@ -161,12 +161,13 @@ public class EmergencyAccessService : IEmergencyAccessService
return emergencyAccess;
}
public async Task DeleteAsync(Guid emergencyAccessId, Guid grantorId)
// TODO: remove with PM-31327 when we migrate to the command.
public async Task DeleteAsync(Guid emergencyAccessId, Guid userId)
{
var emergencyAccess = await _emergencyAccessRepository.GetByIdAsync(emergencyAccessId);
// TODO PM-19438/PM-21687
// Not sure why the GrantorId and the GranteeId are supposed to be the same?
if (emergencyAccess == null || (emergencyAccess.GrantorId != grantorId && emergencyAccess.GranteeId != grantorId))
// Error if the emergency access doesn't exist or the user trying to delete is neither the grantor nor the grantee
if (emergencyAccess == null || (emergencyAccess.GrantorId != userId && emergencyAccess.GranteeId != userId))
{
throw new BadRequestException("Emergency Access not valid.");
}

View File

@@ -38,12 +38,14 @@ public interface IEmergencyAccessService
/// <returns>void</returns>
Task<Entities.EmergencyAccess> AcceptUserAsync(Guid emergencyAccessId, User granteeUser, string token, IUserService userService);
/// <summary>
/// The creator of the emergency access request can delete the request.
/// Either the grantor OR the grantee can delete the emergency access.
/// </summary>
/// <param name="emergencyAccessId">Id of the emergency access being acted on</param>
/// <param name="grantorId">Id of the owner trying to delete the emergency access request</param>
/// <param name="userId">Id of the user (needs to be the grantor or grantee) trying to delete the emergency access</param>
/// <returns>void</returns>
Task DeleteAsync(Guid emergencyAccessId, Guid grantorId);
/// TODO: Remove this deprecated method with PM-31327
[Obsolete("Use IDeleteEmergencyAccessCommand.DeleteByIdAndUserIdAsync instead.")]
Task DeleteAsync(Guid emergencyAccessId, Guid userId);
/// <summary>
/// The grantor user confirms the acceptance of the emergency contact request. This stores the encrypted key allowing the grantee
/// access based on the emergency access type.

View File

@@ -1,35 +1,43 @@
using Bit.Core.Auth.Models.Data;
using Bit.Core.Exceptions;
using Bit.Core.Exceptions;
namespace Bit.Core.Auth.UserFeatures.EmergencyAccess.Interfaces;
/// <summary>
/// Command for deleting emergency access records based on the grantor's user ID.
/// Command for deleting emergency access records.
/// </summary>
public interface IDeleteEmergencyAccessCommand
{
/// <summary>
/// Deletes a single emergency access record for the specified grantor.
/// Deletes a single emergency access record if the requesting user is the grantor or grantee.
/// Sends an email notification to the grantor when a grantee is removed.
/// </summary>
/// <param name="emergencyAccessId">The ID of the emergency access record to delete.</param>
/// <param name="grantorId">The ID of the grantor user who owns the emergency access record.</param>
/// <param name="userId">The ID of the requesting user; must be either the grantor or grantee of the record.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <exception cref="BadRequestException">
/// Thrown when the emergency access record is not found or does not belong to the specified grantor.
/// Thrown when the emergency access record is not found or does not belong to the specified user.
/// </exception>
Task<EmergencyAccessDetails> DeleteByIdGrantorIdAsync(Guid emergencyAccessId, Guid grantorId);
Task DeleteByIdAndUserIdAsync(Guid emergencyAccessId, Guid userId);
/// <summary>
/// Deletes all emergency access records for the specified grantor.
/// Deletes all emergency access records where the user IDs are either grantors or grantees.
/// Sends email notifications only to grantors when their grantees are removed.
/// </summary>
/// <param name="grantorId">The ID of the grantor user whose emergency access records should be deleted.</param>
/// <returns>A collection of the deleted emergency access records.</returns>
Task<ICollection<EmergencyAccessDetails>?> DeleteAllByGrantorIdAsync(Guid grantorId);
/// <param name="userIds">The IDs of users whose emergency access records — as grantor or grantee — will be deleted.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <remarks>
/// If no records are found for the provided user IDs, the method returns.
/// </remarks>
Task DeleteAllByUserIdsAsync(ICollection<Guid> userIds);
/// <summary>
/// Deletes all emergency access records for the specified grantee.
/// Deletes all emergency access records where the user ID is either a grantor or a grantee.
/// Sends email notifications only to grantors when their grantees are removed.
/// </summary>
/// <param name="granteeId">The ID of the grantee user whose emergency access records should be deleted.</param>
/// <returns>A collection of the deleted emergency access records.</returns>
Task<ICollection<EmergencyAccessDetails>?> DeleteAllByGranteeIdAsync(Guid granteeId);
/// <param name="userId">The ID of the user whose emergency access records — as grantor or grantee — will be deleted.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <remarks>
/// If no records are found for the provided user ID, the method returns.
/// </remarks>
Task DeleteAllByUserIdAsync(Guid userId);
}

View File

@@ -1,4 +1,5 @@
# Emergency Access System
This system allows users to share their `User.Key` with other users using public key exchange. An emergency contact (a grantee user) can view or takeover (reset the password) of the grantor user.
When an account is taken over all two factor methods are turned off and device verification is disabled.
@@ -6,6 +7,7 @@ When an account is taken over all two factor methods are turned off and device v
This system is affected by the Key Rotation feature. The `EmergencyAccess.KeyEncrypted` is the `Grantor.UserKey` encrypted by the `Grantee.PublicKey`. So if the `User.Key` is rotated then all `EmergencyAccess` entities will need to be updated.
## Special Cases
Users who use `KeyConnector` are not able to allow `Takeover` of their accounts. However, they can allow `View`.
When a grantee user _takes over_ a grantor user's account, the grantor user will be removed from all organizations where the grantor user is not the `OrganizationUserType.Owner`. A grantor user will not be removed from organizations if the `EmergencyAccessType` is `View`. The grantee user will only be able to `View` the grantor user's ciphers, and not any of the organization ciphers, if any exist.
@@ -16,6 +18,7 @@ A grantor user invites another user to be their emergency contact, the grantee.
The `EmergencyAccess.KeyEncrypted` field is empty, and the `GranteeId` is `null` since the user being invited via email may not have an account yet.
### code
```csharp
// creates entity.
Task<EmergencyAccess> InviteAsync(User grantorUser, string emergencyContactEmail, EmergencyAccessType accessType, int waitTime);
@@ -32,6 +35,7 @@ At this point the grantee user can accept the request. This will set the `Emerge
If the grantee user does not have an account then they can create an account and accept the invitation.
### Code
```csharp
// accepts the request to be an emergency contact.
Task<EmergencyAccess> AcceptUserAsync(Guid emergencyAccessId, User granteeUser, string token, IUserService userService);
@@ -44,6 +48,7 @@ Once the grantee user has accepted, the `EmergencyAccess.GranteeId` allows the g
The `EmergencyAccess.Status` is set to `Confirmed`, and the `EmergencyAccess.KeyEncrypted` is set.
### Code
```csharp
Task<EmergencyAccess> ConfirmUserAsync(Guid emergencyAccessId, string key, Guid grantorId);
```
@@ -53,6 +58,7 @@ Task<EmergencyAccess> ConfirmUserAsync(Guid emergencyAccessId, string key, Guid
The grantee user can now exercise the ability to view or takeover the account. This is done by initiating the recovery. Initiating recovery has a time delay specified by `EmergencyAccess.WaitTime`. `WaitTime` is set in the initial invite. The grantor user can approve the request before the `WaitTime`, but they _cannot_ reject the request _after_ the `WaitTime` has completed. If the recovery request is not rejected then once the `WaitTime` has passed the grantee user will be able to access the emergency access entity.
### Code
```csharp
// Initiates the recovery process; Will set EmergencyAccess.Status to RecoveryInitiated.
Task InitiateAsync(Guid id, User granteeUser);
@@ -69,6 +75,7 @@ Task HandleTimedOutRequestsAsync();
Once the `EmergencyAccess.Status` is `RecoveryApproved` the grantee user is able to exercise their ability to view or takeover the grantor account. Viewing allows the grantee user to view the vault data of the grantor user. Takeover allows the grantee to change the password of the grantor user.
### Takeover
`TakeoverAsync(Guid, User)` returns the grantor user object along with the `EmergencyAccess` entity. The grantor user object is required since to update the password the client needs access to the grantor kdf configuration. Once the password has been set in the `PasswordAsync(Guid, User, string, string)` the account has been successfully recovered.
Taking over the account will change the password of the grantor user, empty the two factor array on the grantor user, and disable device verification.
@@ -86,10 +93,11 @@ Task<AttachmentResponseData> GetAttachmentDownloadAsync(Guid emergencyAccessId,
## Optional steps
The grantor user is able to delete an emergency contact at anytime, at any point in the recovery process.
Either the grantor or grantee is able to delete an emergency access record at any time, at any point in the recovery process.
### Code
```csharp
// deletes the associated EmergencyAccess Entity
Task DeleteAsync(Guid emergencyAccessId, Guid grantorId);
// Deletes the associated EmergencyAccess entity. The requesting user must be the grantor or grantee.
Task DeleteByIdAndUserIdAsync(Guid emergencyAccessId, Guid userId);
```

View File

@@ -60,6 +60,19 @@ public class EmergencyAccessRepository : Repository<EmergencyAccess, Guid>, IEme
}
}
public async Task<ICollection<EmergencyAccessDetails>> GetManyDetailsByUserIdsAsync(ICollection<Guid> userIds)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<EmergencyAccessDetails>(
"[dbo].[EmergencyAccessDetails_ReadManyByUserIds]",
new { UserIds = userIds.ToGuidIdArrayTVP() },
commandType: CommandType.StoredProcedure);
return results.ToList();
}
}
public async Task<EmergencyAccessDetails?> GetDetailsByIdGrantorIdAsync(Guid id, Guid grantorId)
{
using (var connection = new SqlConnection(ConnectionString))
@@ -73,6 +86,19 @@ public class EmergencyAccessRepository : Repository<EmergencyAccess, Guid>, IEme
}
}
public async Task<EmergencyAccessDetails?> GetDetailsByIdAsync(Guid id)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<EmergencyAccessDetails>(
"[dbo].[EmergencyAccessDetails_ReadById]",
new { Id = id },
commandType: CommandType.StoredProcedure);
return results.FirstOrDefault();
}
}
public async Task<ICollection<EmergencyAccessNotify>> GetManyToNotifyAsync()
{
using (var connection = new SqlConnection(ConnectionString))

View File

@@ -29,6 +29,8 @@ public class EmergencyAccessRepository : Repository<Core.Auth.Entities.Emergency
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
// TODO: in future, this probably is not necessary as we have no synced EA data.
// if we delete from here, also delete from stored proc as well + update repo tests.
await dbContext.UserBumpAccountRevisionDateByEmergencyAccessGranteeIdAsync(emergencyAccess.Id);
await dbContext.SaveChangesAsync();
}
@@ -49,6 +51,17 @@ public class EmergencyAccessRepository : Repository<Core.Auth.Entities.Emergency
}
}
public async Task<EmergencyAccessDetails?> GetDetailsByIdAsync(Guid id)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var view = new EmergencyAccessDetailsViewQuery();
var query = view.Run(dbContext).Where(ea => ea.Id == id);
return await query.FirstOrDefaultAsync();
}
}
public async Task<ICollection<EmergencyAccessDetails>> GetExpiredRecoveriesAsync()
{
using (var scope = ServiceScopeFactory.CreateScope())
@@ -88,6 +101,20 @@ public class EmergencyAccessRepository : Repository<Core.Auth.Entities.Emergency
}
}
public async Task<ICollection<EmergencyAccessDetails>> GetManyDetailsByUserIdsAsync(ICollection<Guid> userIds)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var view = new EmergencyAccessDetailsViewQuery();
var query = view.Run(dbContext).Where(ea =>
userIds.Contains(ea.GrantorId) ||
(ea.GranteeId.HasValue && userIds.Contains(ea.GranteeId.Value))
);
return await query.ToListAsync();
}
}
public async Task<ICollection<EmergencyAccessNotify>> GetManyToNotifyAsync()
{
using (var scope = ServiceScopeFactory.CreateScope())
@@ -153,14 +180,7 @@ public class EmergencyAccessRepository : Repository<Core.Auth.Entities.Emergency
where emergencyAccessIds.Contains(ea.Id)
select ea;
var granteeIds = entitiesToRemove
.Where(ea => ea.Status == EmergencyAccessStatusType.Confirmed)
.Where(ea => ea.GranteeId.HasValue)
.Select(ea => ea.GranteeId!.Value) // .Value is safe here due to the Where above
.Distinct();
dbContext.EmergencyAccesses.RemoveRange(entitiesToRemove);
await dbContext.UserBumpManyAccountRevisionDatesAsync([.. granteeIds]);
await dbContext.SaveChangesAsync();
}
}

View File

@@ -32,8 +32,10 @@ public class EmergencyAccessDetailsViewQuery : IQuery<EmergencyAccessDetails>
RevisionDate = x.ea.RevisionDate,
GranteeName = x.grantee.Name,
GranteeEmail = x.grantee.Email ?? x.ea.Email,
GranteeAvatarColor = x.grantee.AvatarColor,
GrantorName = x.grantor.Name,
GrantorEmail = x.grantor.Email,
GrantorAvatarColor = x.grantor.AvatarColor,
});
}
}

View File

@@ -0,0 +1,13 @@
CREATE PROCEDURE [dbo].[EmergencyAccessDetails_ReadById]
@Id UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
SELECT
*
FROM
[dbo].[EmergencyAccessDetailsView]
WHERE
[Id] = @Id
END

View File

@@ -0,0 +1,15 @@
CREATE PROCEDURE [dbo].[EmergencyAccessDetails_ReadManyByUserIds]
@UserIds [dbo].[GuidIdArray] READONLY
AS
BEGIN
SET NOCOUNT ON
SELECT
*
FROM
[dbo].[EmergencyAccessDetailsView]
WHERE
[GrantorId] IN (SELECT [Id] FROM @UserIds)
OR [GranteeId] IN (SELECT [Id] FROM @UserIds)
END
GO