-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathUserRepository.cs
More file actions
631 lines (542 loc) · 26.5 KB
/
Copy pathUserRepository.cs
File metadata and controls
631 lines (542 loc) · 26.5 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
using AutoMapper;
using Bit.Core.Billing.Premium.Models;
using Bit.Core.Enums;
using Bit.Core.KeyManagement.Kdf;
using Bit.Core.KeyManagement.Models.Data;
using Bit.Core.KeyManagement.UserKey;
using Bit.Core.Models.Data;
using Bit.Core.Repositories;
using Bit.Infrastructure.EntityFramework.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace Bit.Infrastructure.EntityFramework.Repositories;
public class UserRepository : Repository<Core.Entities.User, User, Guid>, IUserRepository
{
public UserRepository(IServiceScopeFactory serviceScopeFactory, IMapper mapper)
: base(serviceScopeFactory, mapper, (DatabaseContext context) => context.Users)
{ }
public async Task<Core.Entities.User?> GetByGatewayCustomerIdAsync(string gatewayCustomerId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var entity = await GetDbSet(dbContext)
.FirstOrDefaultAsync(e => e.GatewayCustomerId == gatewayCustomerId);
return Mapper.Map<Core.Entities.User>(entity);
}
}
public async Task<Core.Entities.User?> GetByGatewaySubscriptionIdAsync(string gatewaySubscriptionId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var entity = await GetDbSet(dbContext)
.FirstOrDefaultAsync(e => e.GatewaySubscriptionId == gatewaySubscriptionId);
return Mapper.Map<Core.Entities.User>(entity);
}
}
public async Task<Core.Entities.User?> GetByEmailAsync(string email)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var entity = await GetDbSet(dbContext).FirstOrDefaultAsync(e => e.Email == email);
return Mapper.Map<Core.Entities.User>(entity);
}
}
public async Task<IEnumerable<Core.Entities.User>> GetManyByEmailsAsync(IEnumerable<string> emails)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var users = await GetDbSet(dbContext)
.Where(u => emails.Contains(u.Email))
.ToListAsync();
return Mapper.Map<List<Core.Entities.User>>(users);
}
}
public async Task<UserKdfInformation?> GetKdfInformationByEmailAsync(string email)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
return await GetDbSet(dbContext).Where(e => e.Email == email)
.Select(e => new UserKdfInformation
{
Kdf = e.Kdf,
KdfIterations = e.KdfIterations,
KdfMemory = e.KdfMemory,
KdfParallelism = e.KdfParallelism,
MasterPasswordSalt = e.MasterPasswordSalt
}).SingleOrDefaultAsync();
}
}
public async Task<ICollection<Core.Entities.User>> SearchAsync(string email, int skip, int take)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
List<User> users;
if (dbContext.Database.IsNpgsql())
{
users = await GetDbSet(dbContext)
.Where(e => e.Email == null ||
EF.Functions.ILike(EF.Functions.Collate(e.Email, "default"), $"{email}%"))
.OrderBy(e => e.Email)
.Skip(skip).Take(take)
.ToListAsync();
}
else
{
users = await GetDbSet(dbContext)
.Where(e => email == null || e.Email.StartsWith(email))
.OrderBy(e => e.Email)
.Skip(skip).Take(take)
.ToListAsync();
}
return Mapper.Map<List<Core.Entities.User>>(users);
}
}
public async Task<ICollection<Core.Entities.User>> GetManyByPremiumAsync(bool premium)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var users = await GetDbSet(dbContext).Where(e => e.Premium == premium).ToListAsync();
return Mapper.Map<List<Core.Entities.User>>(users);
}
}
public async Task<string?> GetPublicKeyAsync(Guid id)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
return await GetDbSet(dbContext).Where(e => e.Id == id).Select(e => e.PublicKey).SingleOrDefaultAsync();
}
}
public async Task<DateTime> GetAccountRevisionDateAsync(Guid id)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
return await GetDbSet(dbContext).Where(e => e.Id == id).Select(e => e.AccountRevisionDate)
.SingleOrDefaultAsync();
}
}
public async Task UpdateStorageAsync(Guid id)
{
await base.UserUpdateStorage(id);
}
public async Task UpdateRenewalReminderDateAsync(Guid id, DateTime renewalReminderDate)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var user = new User
{
Id = id,
RenewalReminderDate = renewalReminderDate,
};
var set = GetDbSet(dbContext);
set.Attach(user);
dbContext.Entry(user).Property(e => e.RenewalReminderDate).IsModified = true;
await dbContext.SaveChangesAsync();
}
}
public async Task<Core.Entities.User?> GetBySsoUserAsync(string externalId, Guid? organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var ssoUser = await dbContext.SsoUsers.SingleOrDefaultAsync(e =>
e.OrganizationId == organizationId && e.ExternalId == externalId);
if (ssoUser == null)
{
return null;
}
var entity = await dbContext.Users.SingleOrDefaultAsync(e => e.Id == ssoUser.UserId);
return Mapper.Map<Core.Entities.User>(entity);
}
}
/// <inheritdoc />
public async Task UpdateUserKeyAndEncryptedDataAsync(Core.Entities.User user,
IEnumerable<UpdateEncryptedDataForKeyRotation> updateDataActions)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
await using var transaction = await dbContext.Database.BeginTransactionAsync();
try
{
// Update user
var entity = await dbContext.Users.FindAsync(user.Id);
if (entity == null)
{
throw new ArgumentException("User not found", nameof(user));
}
entity.SecurityStamp = user.SecurityStamp;
entity.Key = user.Key;
entity.PrivateKey = user.PrivateKey;
entity.LastKeyRotationDate = user.LastKeyRotationDate;
entity.AccountRevisionDate = user.AccountRevisionDate;
entity.RevisionDate = user.RevisionDate;
await dbContext.SaveChangesAsync();
// Update re-encrypted data
foreach (var action in updateDataActions)
{
// connection and transaction aren't used in EF
await action();
}
await transaction.CommitAsync();
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
public async Task UpdateUserKeyAndEncryptedDataV2Async(Core.Entities.User user,
IEnumerable<UpdateEncryptedDataForKeyRotation> updateDataActions)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
await using var transaction = await dbContext.Database.BeginTransactionAsync();
// Update user
var userEntity = await dbContext.Users.FindAsync(user.Id);
if (userEntity == null)
{
throw new ArgumentException("User not found", nameof(user));
}
userEntity.SecurityStamp = user.SecurityStamp;
userEntity.Key = user.Key;
userEntity.PrivateKey = user.PrivateKey;
userEntity.Kdf = user.Kdf;
userEntity.KdfIterations = user.KdfIterations;
userEntity.KdfMemory = user.KdfMemory;
userEntity.KdfParallelism = user.KdfParallelism;
userEntity.Email = user.Email;
userEntity.MasterPassword = user.MasterPassword;
userEntity.MasterPasswordHint = user.MasterPasswordHint;
userEntity.LastPasswordChangeDate = user.LastPasswordChangeDate;
userEntity.LastKeyRotationDate = user.LastKeyRotationDate;
userEntity.AccountRevisionDate = user.AccountRevisionDate;
userEntity.RevisionDate = user.RevisionDate;
userEntity.SignedPublicKey = user.SignedPublicKey;
userEntity.SecurityState = user.SecurityState;
userEntity.SecurityVersion = user.SecurityVersion;
userEntity.V2UpgradeToken = user.V2UpgradeToken;
await dbContext.SaveChangesAsync();
// Update re-encrypted data
foreach (var action in updateDataActions)
{
// connection and transaction aren't used in EF
await action();
}
await transaction.CommitAsync();
}
public async Task SetV2AccountCryptographicStateAsync(
Guid userId,
UserAccountKeysData accountKeysData,
IEnumerable<UpdateUserData>? updateUserDataActions = null)
{
if (!accountKeysData.IsV2Encryption())
{
throw new ArgumentException("Provided account keys data is not valid V2 encryption data.", nameof(accountKeysData));
}
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
await using var transaction = await dbContext.Database.BeginTransactionAsync();
// Update user
var userEntity = await dbContext.Users.FindAsync(userId);
if (userEntity == null)
{
throw new ArgumentException("User not found", nameof(userId));
}
// Update public key encryption key pair
var timestamp = DateTime.UtcNow;
userEntity.RevisionDate = timestamp;
userEntity.AccountRevisionDate = timestamp;
// V1 + V2 user crypto changes
userEntity.PublicKey = accountKeysData.PublicKeyEncryptionKeyPairData.PublicKey;
userEntity.PrivateKey = accountKeysData.PublicKeyEncryptionKeyPairData.WrappedPrivateKey;
userEntity.SecurityState = accountKeysData.SecurityStateData!.SecurityState;
userEntity.SecurityVersion = accountKeysData.SecurityStateData.SecurityVersion;
userEntity.SignedPublicKey = accountKeysData.PublicKeyEncryptionKeyPairData.SignedPublicKey;
// Replace existing key-pair if it exists
var existingKeyPair = await dbContext.UserSignatureKeyPairs
.FirstOrDefaultAsync(x => x.UserId == userId);
if (existingKeyPair != null)
{
existingKeyPair.SignatureAlgorithm = accountKeysData.SignatureKeyPairData!.SignatureAlgorithm;
existingKeyPair.SigningKey = accountKeysData.SignatureKeyPairData.WrappedSigningKey;
existingKeyPair.VerifyingKey = accountKeysData.SignatureKeyPairData.VerifyingKey;
existingKeyPair.RevisionDate = timestamp;
}
else
{
var newKeyPair = new UserSignatureKeyPair
{
UserId = userId,
SignatureAlgorithm = accountKeysData.SignatureKeyPairData!.SignatureAlgorithm,
SigningKey = accountKeysData.SignatureKeyPairData.WrappedSigningKey,
VerifyingKey = accountKeysData.SignatureKeyPairData.VerifyingKey,
CreationDate = timestamp,
RevisionDate = timestamp
};
newKeyPair.SetNewId();
await dbContext.UserSignatureKeyPairs.AddAsync(newKeyPair);
}
await dbContext.SaveChangesAsync();
// Update additional user data within the same transaction
if (updateUserDataActions != null)
{
foreach (var action in updateUserDataActions)
{
await action();
}
}
await transaction.CommitAsync();
}
public async Task<IEnumerable<Core.Entities.User>> GetManyAsync(IEnumerable<Guid> ids)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var users = dbContext.Users.Where(x => ids.Contains(x.Id));
return await users.ToListAsync();
}
}
public async Task<IEnumerable<UserWithCalculatedPremium>> GetManyWithCalculatedPremiumAsync(IEnumerable<Guid> ids)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var users = dbContext.Users.Where(x => ids.Contains(x.Id));
return await users.Select(e => new UserWithCalculatedPremium(e)
{
HasPremiumAccess = e.Premium || dbContext.OrganizationUsers
.Any(ou => ou.UserId == e.Id &&
dbContext.Organizations
.Any(o => o.Id == ou.OrganizationId &&
o.UsersGetPremium == true &&
o.Enabled == true))
}).ToListAsync();
}
}
public async Task<UserWithCalculatedPremium?> GetCalculatedPremiumAsync(Guid id)
{
var result = await GetManyWithCalculatedPremiumAsync([id]);
return result.FirstOrDefault();
}
public async Task<IEnumerable<UserPremiumAccess>> GetPremiumAccessByIdsAsync(IEnumerable<Guid> ids)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var users = await dbContext.Users
.Where(x => ids.Contains(x.Id))
.Include(u => u.OrganizationUsers)
.ThenInclude(ou => ou.Organization)
.ToListAsync();
return users.Select(user => new UserPremiumAccess
{
Id = user.Id,
PersonalPremium = user.Premium,
OrganizationPremium = user.OrganizationUsers
.Any(ou => ou.Organization != null &&
ou.Organization.Enabled == true &&
ou.Organization.UsersGetPremium == true)
}).ToList();
}
}
public async Task<UserPremiumAccess?> GetPremiumAccessAsync(Guid userId)
{
var result = await GetPremiumAccessByIdsAsync([userId]);
return result.FirstOrDefault();
}
public override async Task DeleteAsync(Core.Entities.User user)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var transaction = await dbContext.Database.BeginTransactionAsync();
MigrateDefaultUserCollectionsToShared(dbContext, [user.Id]);
await dbContext.SaveChangesAsync();
dbContext.WebAuthnCredentials.RemoveRange(dbContext.WebAuthnCredentials.Where(w => w.UserId == user.Id));
dbContext.Ciphers.RemoveRange(dbContext.Ciphers.Where(c => c.UserId == user.Id));
dbContext.Folders.RemoveRange(dbContext.Folders.Where(f => f.UserId == user.Id));
dbContext.AuthRequests.RemoveRange(dbContext.AuthRequests.Where(s => s.UserId == user.Id));
dbContext.Devices.RemoveRange(dbContext.Devices.Where(d => d.UserId == user.Id));
var collectionUsers = from cu in dbContext.CollectionUsers
join ou in dbContext.OrganizationUsers on cu.OrganizationUserId equals ou.Id
where ou.UserId == user.Id
select cu;
dbContext.CollectionUsers.RemoveRange(collectionUsers);
var groupUsers = from gu in dbContext.GroupUsers
join ou in dbContext.OrganizationUsers on gu.OrganizationUserId equals ou.Id
where ou.UserId == user.Id
select gu;
dbContext.GroupUsers.RemoveRange(groupUsers);
dbContext.UserProjectAccessPolicy.RemoveRange(
dbContext.UserProjectAccessPolicy.Where(ap => ap.OrganizationUser.UserId == user.Id));
dbContext.UserServiceAccountAccessPolicy.RemoveRange(
dbContext.UserServiceAccountAccessPolicy.Where(ap => ap.OrganizationUser.UserId == user.Id));
dbContext.OrganizationUsers.RemoveRange(dbContext.OrganizationUsers.Where(ou => ou.UserId == user.Id));
dbContext.ProviderUsers.RemoveRange(dbContext.ProviderUsers.Where(pu => pu.UserId == user.Id));
dbContext.SsoUsers.RemoveRange(dbContext.SsoUsers.Where(su => su.UserId == user.Id));
dbContext.EmergencyAccesses.RemoveRange(
dbContext.EmergencyAccesses.Where(ea => ea.GrantorId == user.Id || ea.GranteeId == user.Id));
dbContext.Sends.RemoveRange(dbContext.Sends.Where(s => s.UserId == user.Id));
dbContext.NotificationStatuses.RemoveRange(dbContext.NotificationStatuses.Where(ns => ns.UserId == user.Id));
dbContext.Notifications.RemoveRange(dbContext.Notifications.Where(n => n.UserId == user.Id));
var mappedUser = Mapper.Map<User>(user);
dbContext.Users.Remove(mappedUser);
await dbContext.SaveChangesAsync();
await transaction.CommitAsync();
}
}
public async Task DeleteManyAsync(IEnumerable<Core.Entities.User> users)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var transaction = await dbContext.Database.BeginTransactionAsync();
var targetIds = users.Select(u => u.Id).ToList();
MigrateDefaultUserCollectionsToShared(dbContext, targetIds);
await dbContext.SaveChangesAsync();
await dbContext.WebAuthnCredentials.Where(wa => targetIds.Contains(wa.UserId)).ExecuteDeleteAsync();
await dbContext.Ciphers.Where(c => targetIds.Contains(c.UserId ?? default)).ExecuteDeleteAsync();
await dbContext.Folders.Where(f => targetIds.Contains(f.UserId)).ExecuteDeleteAsync();
await dbContext.AuthRequests.Where(a => targetIds.Contains(a.UserId)).ExecuteDeleteAsync();
await dbContext.Devices.Where(d => targetIds.Contains(d.UserId)).ExecuteDeleteAsync();
await dbContext.CollectionUsers
.Join(dbContext.OrganizationUsers,
cu => cu.OrganizationUserId,
ou => ou.Id,
(cu, ou) => new { CollectionUser = cu, OrganizationUser = ou })
.Where((joined) => targetIds.Contains(joined.OrganizationUser.UserId ?? default))
.Select(joined => joined.CollectionUser)
.ExecuteDeleteAsync();
await dbContext.GroupUsers
.Join(dbContext.OrganizationUsers,
gu => gu.OrganizationUserId,
ou => ou.Id,
(gu, ou) => new { GroupUser = gu, OrganizationUser = ou })
.Where(joined => targetIds.Contains(joined.OrganizationUser.UserId ?? default))
.Select(joined => joined.GroupUser)
.ExecuteDeleteAsync();
await dbContext.UserProjectAccessPolicy.Where(ap => targetIds.Contains(ap.OrganizationUser.UserId ?? default)).ExecuteDeleteAsync();
await dbContext.UserServiceAccountAccessPolicy.Where(ap => targetIds.Contains(ap.OrganizationUser.UserId ?? default)).ExecuteDeleteAsync();
await dbContext.OrganizationUsers.Where(ou => targetIds.Contains(ou.UserId ?? default)).ExecuteDeleteAsync();
await dbContext.ProviderUsers.Where(pu => targetIds.Contains(pu.UserId ?? default)).ExecuteDeleteAsync();
await dbContext.SsoUsers.Where(su => targetIds.Contains(su.UserId)).ExecuteDeleteAsync();
await dbContext.EmergencyAccesses.Where(ea => targetIds.Contains(ea.GrantorId) || targetIds.Contains(ea.GranteeId ?? default)).ExecuteDeleteAsync();
await dbContext.Sends.Where(s => targetIds.Contains(s.UserId ?? default)).ExecuteDeleteAsync();
await dbContext.NotificationStatuses.Where(ns => targetIds.Contains(ns.UserId)).ExecuteDeleteAsync();
await dbContext.Notifications.Where(n => targetIds.Contains(n.UserId ?? default)).ExecuteDeleteAsync();
await dbContext.Users.Where(u => targetIds.Contains(u.Id)).ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
await transaction.CommitAsync();
}
}
public UpdateUserData SetKeyConnectorUserKey(Guid userId, string keyConnectorWrappedUserKey)
{
return async (_, _) =>
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var userEntity = await dbContext.Users.FindAsync(userId);
if (userEntity == null)
{
throw new ArgumentException("User not found", nameof(userId));
}
var timestamp = DateTime.UtcNow;
userEntity.Key = keyConnectorWrappedUserKey;
// Key Connector does not use KDF, so we set some defaults
userEntity.Kdf = KdfType.Argon2id;
userEntity.KdfIterations = KdfConstants.ARGON2_ITERATIONS.Default;
userEntity.KdfMemory = KdfConstants.ARGON2_MEMORY.Default;
userEntity.KdfParallelism = KdfConstants.ARGON2_PARALLELISM.Default;
userEntity.UsesKeyConnector = true;
userEntity.RevisionDate = timestamp;
userEntity.AccountRevisionDate = timestamp;
await dbContext.SaveChangesAsync();
};
}
public UpdateUserData SetMasterPassword(Guid userId, MasterPasswordUnlockData masterPasswordUnlockData,
string serverSideHashedMasterPasswordAuthenticationHash, string? masterPasswordHint)
{
return async (_, _) =>
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var userEntity = await dbContext.Users.FindAsync(userId);
if (userEntity == null)
{
throw new ArgumentException("User not found", nameof(userId));
}
var timestamp = DateTime.UtcNow;
userEntity.MasterPassword = serverSideHashedMasterPasswordAuthenticationHash;
userEntity.MasterPasswordHint = masterPasswordHint;
userEntity.Key = masterPasswordUnlockData.MasterKeyWrappedUserKey;
userEntity.Kdf = masterPasswordUnlockData.Kdf.KdfType;
userEntity.KdfIterations = masterPasswordUnlockData.Kdf.Iterations;
userEntity.KdfMemory = masterPasswordUnlockData.Kdf.Memory;
userEntity.KdfParallelism = masterPasswordUnlockData.Kdf.Parallelism;
userEntity.RevisionDate = timestamp;
userEntity.AccountRevisionDate = timestamp;
userEntity.MasterPasswordSalt = masterPasswordUnlockData.Salt;
// TODO (PM-35501): Persist SecurityStamp so the rotation done in
// MasterPasswordService.BuildUpdateUserDelegateSetInitialMasterPassword
// is persisted.
// userEntity.LastPasswordChangeDate = timestamp; This needs adding in PM-34905
await dbContext.SaveChangesAsync();
};
}
public async Task UpdateUserDataAsync(IEnumerable<UpdateUserData> updateUserDataActions)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
await using var transaction = await dbContext.Database.BeginTransactionAsync();
foreach (var action in updateUserDataActions)
{
await action();
}
await transaction.CommitAsync();
}
public UpdateUserData UpdateMasterPasswordUnlockData(Guid userId, RegisterFinishData registerFinishData)
{
return async (_, _) =>
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var userEntity = await dbContext.Users.FindAsync(userId) ?? throw new ArgumentException("User not found", nameof(userId));
var timestamp = DateTime.UtcNow;
userEntity.Kdf = registerFinishData.Kdf.KdfType;
userEntity.KdfIterations = registerFinishData.Kdf.Iterations;
userEntity.KdfMemory = registerFinishData.Kdf.Memory;
userEntity.KdfParallelism = registerFinishData.Kdf.Parallelism;
userEntity.MasterPasswordSalt = registerFinishData.Salt;
userEntity.Key = registerFinishData.MasterKeyWrappedUserKey;
userEntity.RevisionDate = timestamp;
userEntity.AccountRevisionDate = timestamp;
await dbContext.SaveChangesAsync();
};
}
private static void MigrateDefaultUserCollectionsToShared(DatabaseContext dbContext, IEnumerable<Guid> userIds)
{
var defaultCollections = (from c in dbContext.Collections
join cu in dbContext.CollectionUsers on c.Id equals cu.CollectionId
join ou in dbContext.OrganizationUsers on cu.OrganizationUserId equals ou.Id
join u in dbContext.Users on ou.UserId equals u.Id
where userIds.Contains(ou.UserId!.Value)
&& c.Type == Core.Enums.CollectionType.DefaultUserCollection
select new { Collection = c, UserEmail = u.Email })
.ToList();
foreach (var item in defaultCollections)
{
item.Collection.Type = Core.Enums.CollectionType.SharedCollection;
item.Collection.DefaultUserCollectionEmail = item.Collection.DefaultUserCollectionEmail ?? item.UserEmail;
item.Collection.RevisionDate = DateTime.UtcNow;
}
}
}