-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathSendRepository.cs
More file actions
220 lines (188 loc) · 6.71 KB
/
SendRepository.cs
File metadata and controls
220 lines (188 loc) · 6.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#nullable enable
using System.Data;
using Bit.Core;
using Bit.Core.KeyManagement.UserKey;
using Bit.Core.Settings;
using Bit.Core.Tools.Entities;
using Bit.Core.Tools.Repositories;
using Bit.Infrastructure.Dapper.Repositories;
using Bit.Infrastructure.Dapper.Tools.Helpers;
using Dapper;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Data.SqlClient;
namespace Bit.Infrastructure.Dapper.Tools.Repositories;
/// <inheritdoc cref="ISendRepository" />
public class SendRepository : Repository<Send, Guid>, ISendRepository
{
private readonly IDataProtector _dataProtector;
public SendRepository(GlobalSettings globalSettings, IDataProtectionProvider dataProtectionProvider)
: this(globalSettings.SqlServer.ConnectionString, globalSettings.SqlServer.ReadOnlyConnectionString, dataProtectionProvider)
{ }
public SendRepository(string connectionString, string readOnlyConnectionString, IDataProtectionProvider dataProtectionProvider)
: base(connectionString, readOnlyConnectionString)
{
_dataProtector = dataProtectionProvider.CreateProtector(Constants.DatabaseFieldProtectorPurpose);
}
public override async Task<Send?> GetByIdAsync(Guid id)
{
var send = await base.GetByIdAsync(id);
UnprotectData(send);
return send;
}
/// <inheritdoc />
public async Task<ICollection<Send>> GetManyByUserIdAsync(Guid userId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<Send>(
$"[{Schema}].[Send_ReadByUserId]",
new { UserId = userId },
commandType: CommandType.StoredProcedure);
var sends = results.ToList();
UnprotectData(sends);
return sends;
}
}
/// <inheritdoc />
public async Task<ICollection<Send>> GetManyByOrganizationIdAsync(Guid organizationId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<Send>(
$"[{Schema}].[Send_ReadByOrganizationId]",
new { OrganizationId = organizationId },
commandType: CommandType.StoredProcedure);
var sends = results.ToList();
UnprotectData(sends);
return sends;
}
}
/// <inheritdoc />
public async Task<ICollection<Send>> GetManyByDeletionDateAsync(DateTime deletionDateBefore)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<Send>(
$"[{Schema}].[Send_ReadByDeletionDateBefore]",
new { DeletionDate = deletionDateBefore },
commandType: CommandType.StoredProcedure);
var sends = results.ToList();
UnprotectData(sends);
return sends;
}
}
public override async Task<Send> CreateAsync(Send send)
{
await ProtectDataAndSaveAsync(send, async () => await base.CreateAsync(send));
return send;
}
public override async Task ReplaceAsync(Send send)
{
await ProtectDataAndSaveAsync(send, async () => await base.ReplaceAsync(send));
}
/// <inheritdoc />
public UpdateEncryptedDataForKeyRotation UpdateForKeyRotation(Guid userId, IEnumerable<Send> sends)
{
return async (connection, transaction) =>
{
// Protect all sends before bulk update
var sendsList = sends.ToList();
foreach (var send in sendsList)
{
ProtectData(send);
}
// Create temp table
var sqlCreateTemp = @"
SELECT TOP 0 *
INTO #TempSend
FROM [dbo].[Send]";
await using (var cmd = new SqlCommand(sqlCreateTemp, connection, transaction))
{
cmd.ExecuteNonQuery();
}
// Bulk copy data into temp table
using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction))
{
bulkCopy.DestinationTableName = "#TempSend";
var sendsTable = sendsList.ToDataTable();
foreach (DataColumn col in sendsTable.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
sendsTable.PrimaryKey = new DataColumn[] { sendsTable.Columns[0] };
await bulkCopy.WriteToServerAsync(sendsTable);
}
// Update send table from temp table
var sql = @"
UPDATE
[dbo].[Send]
SET
[Key] = TS.[Key],
[RevisionDate] = TS.[RevisionDate]
FROM
[dbo].[Send] S
INNER JOIN
#TempSend TS ON S.Id = TS.Id
WHERE
S.[UserId] = @UserId
DROP TABLE #TempSend";
await using (var cmd = new SqlCommand(sql, connection, transaction))
{
cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = userId;
cmd.ExecuteNonQuery();
}
// Unprotect after save
foreach (var send in sendsList)
{
UnprotectData(send);
}
};
}
private async Task ProtectDataAndSaveAsync(Send send, Func<Task> saveTask)
{
if (send == null)
{
await saveTask();
return;
}
// Capture original value
var emails = send.Emails;
// Protect value
ProtectData(send);
// Save
await saveTask();
// Restore original value
send.Emails = emails;
}
private void ProtectData(Send send)
{
if (!send.Emails?.StartsWith(Constants.DatabaseFieldProtectedPrefix) ?? false)
{
send.Emails = string.Concat(Constants.DatabaseFieldProtectedPrefix,
_dataProtector.Protect(send.Emails!));
}
}
private void UnprotectData(Send? send)
{
if (send == null)
{
return;
}
if (send.Emails?.StartsWith(Constants.DatabaseFieldProtectedPrefix) ?? false)
{
send.Emails = _dataProtector.Unprotect(
send.Emails.Substring(Constants.DatabaseFieldProtectedPrefix.Length));
}
}
private void UnprotectData(IEnumerable<Send> sends)
{
if (sends == null)
{
return;
}
foreach (var send in sends)
{
UnprotectData(send);
}
}
}