-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathCipherRepository.cs
More file actions
1144 lines (1029 loc) · 46.6 KB
/
CipherRepository.cs
File metadata and controls
1144 lines (1029 loc) · 46.6 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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// FIXME: Update this file to be null safe and then delete the line below
#nullable disable
using System.Text.Json;
using System.Text.Json.Nodes;
using AutoMapper;
using Bit.Core.Enums;
using Bit.Core.KeyManagement.UserKey;
using Bit.Core.Utilities;
using Bit.Core.Vault.Enums;
using Bit.Core.Vault.Models.Data;
using Bit.Core.Vault.Repositories;
using Bit.Infrastructure.EntityFramework.Models;
using Bit.Infrastructure.EntityFramework.Repositories;
using Bit.Infrastructure.EntityFramework.Repositories.Queries;
using Bit.Infrastructure.EntityFramework.Repositories.Vault.Queries;
using Bit.Infrastructure.EntityFramework.Vault.Models;
using Bit.Infrastructure.EntityFramework.Vault.Repositories.Queries;
using LinqToDB.EntityFrameworkCore;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using NS = Newtonsoft.Json;
using NSL = Newtonsoft.Json.Linq;
namespace Bit.Infrastructure.EntityFramework.Vault.Repositories;
public class CipherRepository : Repository<Core.Vault.Entities.Cipher, Cipher, Guid>, ICipherRepository
{
public CipherRepository(IServiceScopeFactory serviceScopeFactory, IMapper mapper)
: base(serviceScopeFactory, mapper, (DatabaseContext context) => context.Ciphers)
{ }
public override async Task<Core.Vault.Entities.Cipher> CreateAsync(Core.Vault.Entities.Cipher cipher)
{
cipher = await base.CreateAsync(cipher);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
if (cipher.OrganizationId.HasValue)
{
await dbContext.UserBumpAccountRevisionDateByCipherIdAsync(cipher.Id, cipher.OrganizationId.Value);
}
else if (cipher.UserId.HasValue)
{
await dbContext.UserBumpAccountRevisionDateAsync(cipher.UserId.Value);
}
await dbContext.SaveChangesAsync();
}
return cipher;
}
public override async Task DeleteAsync(Core.Vault.Entities.Cipher cipher)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var cipherInfo = await dbContext.Ciphers
.Where(c => c.Id == cipher.Id)
.Select(c => new { c.UserId, c.OrganizationId, HasAttachments = c.Attachments != null })
.FirstOrDefaultAsync();
await base.DeleteAsync(cipher);
if (cipherInfo?.OrganizationId != null)
{
if (cipherInfo.HasAttachments == true)
{
await OrganizationUpdateStorage(cipherInfo.OrganizationId.Value);
}
await dbContext.UserBumpAccountRevisionDateByCipherIdAsync(cipher.Id, cipherInfo.OrganizationId.Value);
}
else if (cipherInfo?.UserId != null)
{
if (cipherInfo.HasAttachments)
{
await UserUpdateStorage(cipherInfo.UserId.Value);
}
await dbContext.UserBumpAccountRevisionDateAsync(cipherInfo.UserId.Value);
}
await dbContext.SaveChangesAsync();
}
}
public async Task CreateAsync(Core.Vault.Entities.Cipher cipher, IEnumerable<Guid> collectionIds)
{
cipher = await CreateAsync(cipher);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
await UpdateCollectionsAsync(dbContext, cipher.Id,
cipher.UserId, cipher.OrganizationId, collectionIds);
await dbContext.SaveChangesAsync();
}
}
public async Task CreateAsync(CipherDetails cipher)
{
await CreateAsyncReturnCipher(cipher);
}
private async Task<CipherDetails> CreateAsyncReturnCipher(CipherDetails cipher)
{
cipher.SetNewId();
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var userIdKey = $"\"{cipher.UserId}\"";
cipher.UserId = cipher.OrganizationId.HasValue ? null : cipher.UserId;
cipher.Favorites = cipher.Favorite ?
$"{{{userIdKey}:true}}" :
null;
cipher.Folders = cipher.FolderId.HasValue ?
$"{{{userIdKey}:\"{cipher.FolderId}\"}}" :
null;
var entity = Mapper.Map<Cipher>((Core.Vault.Entities.Cipher)cipher);
await dbContext.AddAsync(entity);
await dbContext.SaveChangesAsync();
if (cipher.OrganizationId.HasValue)
{
await dbContext.UserBumpAccountRevisionDateByCipherIdAsync(cipher.Id, cipher.OrganizationId.Value);
}
else if (cipher.UserId.HasValue)
{
await dbContext.UserBumpAccountRevisionDateAsync(cipher.UserId.Value);
}
await dbContext.SaveChangesAsync();
}
return cipher;
}
public async Task CreateAsync(CipherDetails cipher, IEnumerable<Guid> collectionIds)
{
cipher = await CreateAsyncReturnCipher(cipher);
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
await UpdateCollectionsAsync(dbContext, cipher.Id,
cipher.UserId, cipher.OrganizationId, collectionIds);
await dbContext.SaveChangesAsync();
}
}
public async Task CreateAsync(Guid userId, IEnumerable<Core.Vault.Entities.Cipher> ciphers,
IEnumerable<Core.Vault.Entities.Folder> folders)
{
ciphers = ciphers.ToList();
if (!ciphers.Any())
{
return;
}
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var folderEntities = Mapper.Map<List<Folder>>(folders);
var cipherEntities = Mapper.Map<List<Cipher>>(ciphers);
// SQLite does not support LinqToDB BulkCopy; use EF Core directly instead
if (dbContext.Database.IsSqlite())
{
await dbContext.AddRangeAsync(folderEntities);
await dbContext.AddRangeAsync(cipherEntities);
}
else
{
await dbContext.BulkCopyAsync(base.DefaultBulkCopyOptions, folderEntities);
await dbContext.BulkCopyAsync(base.DefaultBulkCopyOptions, cipherEntities);
}
await dbContext.UserBumpAccountRevisionDateAsync(userId);
await dbContext.SaveChangesAsync();
}
}
public async Task CreateAsync(IEnumerable<Core.Vault.Entities.Cipher> ciphers,
IEnumerable<Core.Entities.Collection> collections,
IEnumerable<Core.Entities.CollectionCipher> collectionCiphers,
IEnumerable<Core.Entities.CollectionUser> collectionUsers)
{
if (!ciphers.Any())
{
return;
}
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var cipherEntities = Mapper.Map<List<Cipher>>(ciphers);
// SQLite does not support LinqToDB BulkCopy; use EF Core directly instead
if (dbContext.Database.IsSqlite())
{
await dbContext.AddRangeAsync(cipherEntities);
if (collections.Any())
{
await dbContext.AddRangeAsync(Mapper.Map<List<Collection>>(collections));
}
if (collectionCiphers.Any())
{
await dbContext.AddRangeAsync(Mapper.Map<List<CollectionCipher>>(collectionCiphers));
}
if (collectionUsers.Any())
{
await dbContext.AddRangeAsync(Mapper.Map<List<CollectionUser>>(collectionUsers));
}
}
else
{
await dbContext.BulkCopyAsync(base.DefaultBulkCopyOptions, cipherEntities);
if (collections.Any())
{
var collectionEntities = Mapper.Map<List<Collection>>(collections);
await dbContext.BulkCopyAsync(base.DefaultBulkCopyOptions, collectionEntities);
}
if (collectionCiphers.Any())
{
var collectionCipherEntities = Mapper.Map<List<CollectionCipher>>(collectionCiphers);
await dbContext.BulkCopyAsync(base.DefaultBulkCopyOptions, collectionCipherEntities);
}
if (collectionUsers.Any())
{
var collectionUserEntities = Mapper.Map<List<CollectionUser>>(collectionUsers);
await dbContext.BulkCopyAsync(base.DefaultBulkCopyOptions, collectionUserEntities);
}
}
await dbContext.UserBumpAccountRevisionDateByOrganizationIdAsync(ciphers.First().OrganizationId.Value);
await dbContext.SaveChangesAsync();
}
}
public async Task DeleteAsync(IEnumerable<Guid> ids, Guid userId)
{
await ToggleDeleteCipherStatesAsync(ids, userId, CipherStateAction.HardDelete);
}
public async Task DeleteAttachmentAsync(Guid cipherId, string attachmentId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var cipher = await dbContext.Ciphers.FindAsync(cipherId);
var attachmentsJson = NSL.JObject.Parse(cipher.Attachments);
attachmentsJson.Remove(attachmentId);
cipher.Attachments = NS.JsonConvert.SerializeObject(attachmentsJson);
await dbContext.SaveChangesAsync();
if (cipher.OrganizationId.HasValue)
{
await OrganizationUpdateStorage(cipher.OrganizationId.Value);
await dbContext.UserBumpAccountRevisionDateByCipherIdAsync(cipher.Id, cipher.OrganizationId.Value);
}
else if (cipher.UserId.HasValue)
{
await UserUpdateStorage(cipher.UserId.Value);
await dbContext.UserBumpAccountRevisionDateAsync(cipher.UserId.Value);
}
await dbContext.SaveChangesAsync();
}
}
public async Task DeleteByIdsOrganizationIdAsync(IEnumerable<Guid> ids, Guid organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var ciphers = from c in dbContext.Ciphers
where c.OrganizationId == organizationId &&
ids.Contains(c.Id)
select c;
dbContext.RemoveRange(ciphers);
await dbContext.SaveChangesAsync();
await OrganizationUpdateStorage(organizationId);
await dbContext.UserBumpAccountRevisionDateByOrganizationIdAsync(organizationId);
await dbContext.SaveChangesAsync();
}
}
public async Task DeleteByOrganizationIdAsync(Guid organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var ciphersToDelete = from c in dbContext.Ciphers
where c.OrganizationId == organizationId
&& !c.CollectionCiphers.Any(cc =>
cc.Collection.Type == CollectionType.DefaultUserCollection)
select c;
dbContext.RemoveRange(ciphersToDelete);
var collectionCiphersToRemove = from cc in dbContext.CollectionCiphers
join col in dbContext.Collections on cc.CollectionId equals col.Id
join c in dbContext.Ciphers on cc.CipherId equals c.Id
where col.Type != CollectionType.DefaultUserCollection
&& c.OrganizationId == organizationId
select cc;
dbContext.RemoveRange(collectionCiphersToRemove);
await OrganizationUpdateStorage(organizationId);
await dbContext.UserBumpAccountRevisionDateByOrganizationIdAsync(organizationId);
await dbContext.SaveChangesAsync();
}
}
public async Task DeleteByUserIdAsync(Guid userId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var ciphers = from c in dbContext.Ciphers
where c.UserId == userId
select c;
dbContext.RemoveRange(ciphers);
var folders = from f in dbContext.Folders
where f.UserId == userId
select f;
dbContext.RemoveRange(folders);
await dbContext.SaveChangesAsync();
await UserUpdateStorage(userId);
await dbContext.UserBumpAccountRevisionDateAsync(userId);
await dbContext.SaveChangesAsync();
}
}
public async Task DeleteDeletedAsync(DateTime deletedDateBefore)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = dbContext.Ciphers.Where(c => c.DeletedDate < deletedDateBefore);
dbContext.RemoveRange(query);
await dbContext.SaveChangesAsync();
}
}
public async Task<ICollection<OrganizationCipherPermission>>
GetCipherPermissionsForOrganizationAsync(Guid organizationId, Guid userId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = new CipherOrganizationPermissionsQuery(organizationId, userId).Run(dbContext);
ICollection<OrganizationCipherPermission> permissions;
// SQLite does not support the GROUP BY clause
if (dbContext.Database.IsSqlite())
{
permissions = (await query.ToListAsync())
.GroupBy(c => new { c.Id, c.OrganizationId })
.Select(g => new OrganizationCipherPermission
{
Id = g.Key.Id,
OrganizationId = g.Key.OrganizationId,
Read = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Read))),
ViewPassword = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.ViewPassword))),
Edit = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Edit))),
Manage = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Manage))),
}).ToList();
}
else
{
var groupByQuery = from p in query
group p by new { p.Id, p.OrganizationId }
into g
select new OrganizationCipherPermission
{
Id = g.Key.Id,
OrganizationId = g.Key.OrganizationId,
Read = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Read))),
ViewPassword = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.ViewPassword))),
Edit = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Edit))),
Manage = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Manage))),
};
permissions = await groupByQuery.ToListAsync();
}
return permissions;
}
}
public async Task<ICollection<UserSecurityTaskCipher>> GetUserSecurityTasksByCipherIdsAsync(Guid organizationId, IEnumerable<Core.Vault.Entities.SecurityTask> tasks)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var cipherIds = tasks.Where(t => t.CipherId.HasValue).Select(t => t.CipherId.Value);
var dbContext = GetDatabaseContext(scope);
var query = new UserSecurityTasksByCipherIdsQuery(organizationId, cipherIds).Run(dbContext);
ICollection<UserSecurityTaskCipher> userTaskCiphers;
// SQLite does not support the GROUP BY clause
if (dbContext.Database.IsSqlite())
{
userTaskCiphers = (await query.ToListAsync())
.GroupBy(c => new { c.UserId, c.Email, c.CipherId })
.Select(g => new UserSecurityTaskCipher
{
UserId = g.Key.UserId,
Email = g.Key.Email,
CipherId = g.Key.CipherId,
}).ToList();
}
else
{
var groupByQuery = from p in query
group p by new { p.UserId, p.Email, p.CipherId }
into g
select new UserSecurityTaskCipher
{
UserId = g.Key.UserId,
CipherId = g.Key.CipherId,
Email = g.Key.Email,
};
userTaskCiphers = await groupByQuery.ToListAsync();
}
foreach (var userTaskCipher in userTaskCiphers)
{
userTaskCipher.TaskId = tasks.First(t => t.CipherId == userTaskCipher.CipherId).Id;
}
return userTaskCiphers;
}
}
public async Task<CipherDetails> GetByIdAsync(Guid id, Guid userId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var userCipherDetails = new UserCipherDetailsQuery(userId);
var data = await userCipherDetails.Run(dbContext).FirstOrDefaultAsync(c => c.Id == id);
return data;
}
}
public async Task<ICollection<CipherOrganizationDetails>> GetManyOrganizationDetailsByOrganizationIdAsync(
Guid organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = new CipherOrganizationDetailsReadByOrganizationIdQuery(organizationId);
var data = await query.Run(dbContext).ToListAsync();
return data;
}
}
public async Task<bool> GetCanEditByIdAsync(Guid userId, Guid cipherId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = new CipherReadCanEditByIdUserIdQuery(userId, cipherId);
var canEdit = await query.Run(dbContext).AnyAsync();
return canEdit;
}
}
public async Task<ICollection<Core.Vault.Entities.Cipher>> GetManyByOrganizationIdAsync(Guid organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = dbContext.Ciphers.Where(x => !x.UserId.HasValue && x.OrganizationId == organizationId);
var data = await query.ToListAsync();
return Mapper.Map<List<Core.Vault.Entities.Cipher>>(data);
}
}
public async Task<ICollection<CipherOrganizationDetails>> GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(Guid organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = new CipherOrganizationDetailsReadByOrganizationIdQuery(organizationId, true);
var data = await query.Run(dbContext).ToListAsync();
return data;
}
}
public async Task<ICollection<CipherDetails>> GetManyByUserIdAsync(Guid userId, bool withOrganizations = true)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var cipherDetailsView = withOrganizations ?
new UserCipherDetailsQuery(userId).Run(dbContext) :
new CipherDetailsQuery(userId).Run(dbContext);
if (!withOrganizations)
{
cipherDetailsView = from c in cipherDetailsView
where c.UserId == userId
select new CipherDetails
{
Id = c.Id,
UserId = c.UserId,
OrganizationId = c.OrganizationId,
Type = c.Type,
Data = c.Data,
Attachments = c.Attachments,
CreationDate = c.CreationDate,
RevisionDate = c.RevisionDate,
DeletedDate = c.DeletedDate,
Favorite = c.Favorite,
FolderId = c.FolderId,
Edit = true,
Reprompt = c.Reprompt,
ViewPassword = true,
Manage = true,
OrganizationUseTotp = false,
Key = c.Key,
ArchivedDate = c.ArchivedDate,
};
}
var ciphers = await cipherDetailsView.ToListAsync();
return ciphers.GroupBy(c => c.Id)
.Select(g => g.OrderByDescending(c => c.Manage)
.ThenByDescending(c => c.Edit)
.ThenByDescending(c => c.ViewPassword)
.First())
.ToList();
}
}
public async Task<CipherOrganizationDetails> GetOrganizationDetailsByIdAsync(Guid id)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = new CipherOrganizationDetailsReadByIdQuery(id);
var data = await query.Run(dbContext).FirstOrDefaultAsync();
return data;
}
}
public async Task MoveAsync(IEnumerable<Guid> ids, Guid? folderId, Guid userId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var cipherEntities = dbContext.Ciphers.Where(c => ids.Contains(c.Id));
var userCipherDetails = new UserCipherDetailsQuery(userId).Run(dbContext);
var idsToMove = from ucd in userCipherDetails
join c in cipherEntities
on ucd.Id equals c.Id
select c;
await idsToMove.ForEachAsync(cipher =>
{
var foldersJson = string.IsNullOrWhiteSpace(cipher.Folders) ?
new NSL.JObject() :
NSL.JObject.Parse(cipher.Folders);
if (folderId.HasValue)
{
foldersJson.Remove(userId.ToString());
foldersJson.Add(userId.ToString(), folderId.Value.ToString());
}
else if (!string.IsNullOrWhiteSpace(cipher.Folders))
{
foldersJson.Remove(userId.ToString());
}
dbContext.Attach(cipher);
cipher.Folders = NS.JsonConvert.SerializeObject(foldersJson);
});
await dbContext.UserBumpAccountRevisionDateAsync(userId);
await dbContext.SaveChangesAsync();
}
}
public async Task ReplaceAsync(CipherDetails cipher)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var entity = await dbContext.Ciphers.FindAsync(cipher.Id);
if (entity != null)
{
if (cipher.UserId.HasValue)
{
if (cipher.Favorite)
{
if (cipher.Favorites == null)
{
var jsonObject = new JsonObject(new[]
{
new KeyValuePair<string, JsonNode>(cipher.UserId.Value.ToString(), true),
});
cipher.Favorites = JsonSerializer.Serialize(jsonObject);
}
else
{
var favorites = CoreHelpers.LoadClassFromJsonData<Dictionary<Guid, bool>>(cipher.Favorites);
favorites.Add(cipher.UserId.Value, true);
cipher.Favorites = JsonSerializer.Serialize(favorites);
}
}
else
{
if (cipher.Favorites != null && cipher.Favorites.Contains(cipher.UserId.Value.ToString()))
{
var favorites = CoreHelpers.LoadClassFromJsonData<Dictionary<Guid, bool>>(cipher.Favorites);
favorites.Remove(cipher.UserId.Value);
cipher.Favorites = JsonSerializer.Serialize(favorites);
}
}
if (cipher.FolderId.HasValue)
{
if (cipher.Folders == null)
{
var jsonObject = new JsonObject(new[]
{
new KeyValuePair<string, JsonNode>(cipher.UserId.Value.ToString(), cipher.FolderId),
});
cipher.Folders = JsonSerializer.Serialize(jsonObject);
}
else
{
var folders = CoreHelpers.LoadClassFromJsonData<Dictionary<Guid, Guid>>(cipher.Folders);
folders.Add(cipher.UserId.Value, cipher.FolderId.Value);
cipher.Folders = JsonSerializer.Serialize(folders);
}
}
else
{
if (cipher.Folders != null && cipher.Folders.Contains(cipher.UserId.Value.ToString()))
{
var folders = CoreHelpers.LoadClassFromJsonData<Dictionary<Guid, Guid>>(cipher.Folders);
folders.Remove(cipher.UserId.Value);
cipher.Folders = JsonSerializer.Serialize(folders);
}
}
}
// Check if this cipher is a part of an organization, and if so do
// not save the UserId into the database. This must be done after we
// set the user specific data like Folders and Favorites because
// the UserId key is used for that
cipher.UserId = cipher.OrganizationId.HasValue ?
null :
cipher.UserId;
var mappedEntity = Mapper.Map<Cipher>(cipher);
dbContext.Entry(entity).CurrentValues.SetValues(mappedEntity);
if (cipher.OrganizationId.HasValue)
{
await dbContext.UserBumpAccountRevisionDateByCipherIdAsync(cipher.Id, cipher.OrganizationId.Value);
}
else if (cipher.UserId.HasValue)
{
await dbContext.UserBumpAccountRevisionDateAsync(cipher.UserId.Value);
}
await dbContext.SaveChangesAsync();
}
}
}
private static async Task<int> UpdateCollectionsAsync(DatabaseContext context, Guid id, Guid? userId, Guid? organizationId, IEnumerable<Guid> collectionIds)
{
if (!organizationId.HasValue || !collectionIds.Any())
{
return -1;
}
IQueryable<Guid> availableCollectionsQuery;
if (!userId.HasValue)
{
availableCollectionsQuery = context.Collections
.Where(c => c.OrganizationId == organizationId.Value)
.Select(c => c.Id);
}
else
{
availableCollectionsQuery =
new CollectionsReadByOrganizationIdUserIdQuery(organizationId.Value, userId.Value)
.Run(context)
.Select(c => c.Id);
}
var availableCollections = await availableCollectionsQuery.ToListAsync();
if (!availableCollections.Any())
{
return -1;
}
var collectionCiphers = collectionIds
.Where(collectionId => availableCollections.Contains(collectionId))
.Select(collectionId => new CollectionCipher
{
CollectionId = collectionId,
CipherId = id,
});
context.CollectionCiphers.AddRange(collectionCiphers);
return 0;
}
public async Task<bool> ReplaceAsync(Core.Vault.Entities.Cipher cipher, IEnumerable<Guid> collectionIds)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var transaction = await dbContext.Database.BeginTransactionAsync();
var successes = await UpdateCollectionsAsync(
dbContext, cipher.Id, cipher.UserId,
cipher.OrganizationId, collectionIds);
if (successes < 0)
{
await transaction.CommitAsync();
return false;
}
var trackedCipher = await dbContext.Ciphers.FindAsync(cipher.Id);
trackedCipher.UserId = null;
trackedCipher.OrganizationId = cipher.OrganizationId;
trackedCipher.Data = cipher.Data;
trackedCipher.Attachments = cipher.Attachments;
trackedCipher.RevisionDate = cipher.RevisionDate;
trackedCipher.DeletedDate = cipher.DeletedDate;
trackedCipher.Key = cipher.Key;
trackedCipher.Folders = cipher.Folders;
trackedCipher.Favorites = cipher.Favorites;
trackedCipher.Reprompt = cipher.Reprompt;
await transaction.CommitAsync();
if (!string.IsNullOrWhiteSpace(cipher.Attachments))
{
if (cipher.OrganizationId.HasValue)
{
await OrganizationUpdateStorage(cipher.OrganizationId.Value);
}
else if (cipher.UserId.HasValue)
{
await UserUpdateStorage(cipher.UserId.Value);
}
}
if (cipher.OrganizationId.HasValue)
{
await dbContext.UserBumpAccountRevisionDateByCipherIdAsync(cipher.Id, cipher.OrganizationId.Value);
}
else if (cipher.UserId.HasValue)
{
await dbContext.UserBumpAccountRevisionDateAsync(cipher.UserId.Value);
}
await dbContext.SaveChangesAsync();
return true;
}
}
public async Task<DateTime> UnarchiveAsync(IEnumerable<Guid> ids, Guid userId)
{
return await ToggleArchiveCipherStatesAsync(ids, userId, CipherStateAction.Unarchive);
}
public async Task<DateTime> RestoreAsync(IEnumerable<Guid> ids, Guid userId)
{
return await ToggleDeleteCipherStatesAsync(ids, userId, CipherStateAction.Restore);
}
public async Task<DateTime> RestoreByIdsOrganizationIdAsync(IEnumerable<Guid> ids, Guid organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var utcNow = DateTime.UtcNow;
var ciphers = from c in dbContext.Ciphers
where c.OrganizationId == organizationId &&
ids.Contains(c.Id)
select c;
await ciphers.ForEachAsync(cipher =>
{
dbContext.Attach(cipher);
cipher.DeletedDate = null;
cipher.RevisionDate = utcNow;
});
await OrganizationUpdateStorage(organizationId);
await dbContext.UserBumpAccountRevisionDateByOrganizationIdAsync(organizationId);
await dbContext.SaveChangesAsync();
return utcNow;
}
}
public async Task<DateTime> ArchiveAsync(IEnumerable<Guid> ids, Guid userId)
{
return await ToggleArchiveCipherStatesAsync(ids, userId, CipherStateAction.Archive);
}
public async Task SoftDeleteAsync(IEnumerable<Guid> ids, Guid userId)
{
await ToggleDeleteCipherStatesAsync(ids, userId, CipherStateAction.SoftDelete);
}
private async Task<DateTime> ToggleArchiveCipherStatesAsync(IEnumerable<Guid> ids, Guid userId, CipherStateAction action)
{
static bool FilterArchivedDate(CipherStateAction action, CipherDetails ucd)
{
return action switch
{
CipherStateAction.Unarchive => ucd.ArchivedDate != null,
CipherStateAction.Archive => ucd.ArchivedDate == null,
_ => true
};
}
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var userCipherDetailsQuery = new UserCipherDetailsQuery(userId);
var cipherEntitiesToCheck = await dbContext.Ciphers.Where(c => ids.Contains(c.Id)).ToListAsync();
var query = from ucd in await userCipherDetailsQuery.Run(dbContext).ToListAsync()
join c in cipherEntitiesToCheck
on ucd.Id equals c.Id
where FilterArchivedDate(action, ucd)
select c;
var utcNow = DateTime.UtcNow;
var cipherIdsToModify = query.Select(c => c.Id);
var cipherEntitiesToModify = dbContext.Ciphers.Where(x => cipherIdsToModify.Contains(x.Id));
await cipherEntitiesToModify.ForEachAsync(cipher =>
{
dbContext.Attach(cipher);
// Build or load the per-user archives map
var archives = string.IsNullOrWhiteSpace(cipher.Archives)
? new Dictionary<Guid, DateTime>()
: CoreHelpers.LoadClassFromJsonData<Dictionary<Guid, DateTime>>(cipher.Archives)
?? new Dictionary<Guid, DateTime>();
if (action == CipherStateAction.Unarchive)
{
// Remove this user's archive record
archives.Remove(userId);
}
else if (action == CipherStateAction.Archive)
{
// Set this user's archive date
archives[userId] = utcNow;
}
// Persist the updated JSON or clear it if empty
cipher.Archives = archives.Count == 0
? null
: CoreHelpers.ClassToJsonData(archives);
cipher.RevisionDate = utcNow;
});
await dbContext.UserBumpAccountRevisionDateAsync(userId);
await dbContext.SaveChangesAsync();
return utcNow;
}
}
private async Task<DateTime> ToggleDeleteCipherStatesAsync(IEnumerable<Guid> ids, Guid userId, CipherStateAction action)
{
static bool FilterDeletedDate(CipherStateAction action, CipherDetails ucd)
{
return action switch
{
CipherStateAction.Restore => ucd.DeletedDate != null,
CipherStateAction.SoftDelete => ucd.DeletedDate == null,
_ => true
};
}
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var userCipherDetailsQuery = new UserCipherDetailsQuery(userId);
var cipherEntitiesToCheck = await dbContext.Ciphers.Where(c => ids.Contains(c.Id)).ToListAsync();
var query = from ucd in await userCipherDetailsQuery.Run(dbContext).ToListAsync()
join c in cipherEntitiesToCheck
on ucd.Id equals c.Id
where ucd.Edit && FilterDeletedDate(action, ucd)
select c;
var utcNow = DateTime.UtcNow;
var cipherIdsToModify = query.Select(c => c.Id);
var cipherEntitiesToModify = dbContext.Ciphers.Where(x => cipherIdsToModify.Contains(x.Id));
if (action == CipherStateAction.HardDelete)
{
dbContext.RemoveRange(cipherEntitiesToModify);
}
else
{
await cipherEntitiesToModify.ForEachAsync(cipher =>
{
dbContext.Attach(cipher);
cipher.DeletedDate = action == CipherStateAction.Restore ? null : utcNow;
cipher.RevisionDate = utcNow;
});
}
var orgIds = query
.Where(c => c.OrganizationId.HasValue)
.GroupBy(c => c.OrganizationId).Select(x => x.Key);
foreach (var orgId in orgIds)
{
await OrganizationUpdateStorage(orgId.Value);
await dbContext.UserBumpAccountRevisionDateByOrganizationIdAsync(orgId.Value);
}
if (query.Any(c => c.UserId.HasValue && !string.IsNullOrWhiteSpace(c.Attachments)))
{
await UserUpdateStorage(userId);
}
await dbContext.UserBumpAccountRevisionDateAsync(userId);
await dbContext.SaveChangesAsync();
return utcNow;
}
}
public async Task SoftDeleteByIdsOrganizationIdAsync(IEnumerable<Guid> ids, Guid organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var utcNow = DateTime.UtcNow;
var ciphers = dbContext.Ciphers.Where(c => ids.Contains(c.Id) && c.OrganizationId == organizationId);
await ciphers.ForEachAsync(cipher =>
{
dbContext.Attach(cipher);
cipher.DeletedDate = utcNow;
cipher.RevisionDate = utcNow;
});
await OrganizationUpdateStorage(organizationId);
await dbContext.UserBumpAccountRevisionDateByOrganizationIdAsync(organizationId);
await dbContext.SaveChangesAsync();
}
}
public async Task UpdateAttachmentAsync(CipherAttachment attachment)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var cipher = await dbContext.Ciphers.FindAsync(attachment.Id);
var attachments = string.IsNullOrWhiteSpace(cipher.Attachments) ?
new Dictionary<string, CipherAttachment.MetaData>() :
NS.JsonConvert.DeserializeObject<Dictionary<string, CipherAttachment.MetaData>>(cipher.Attachments);
var metaData = NS.JsonConvert.DeserializeObject<CipherAttachment.MetaData>(attachment.AttachmentData);
attachments[attachment.AttachmentId] = metaData;
cipher.Attachments = NS.JsonConvert.SerializeObject(attachments);
await dbContext.SaveChangesAsync();
if (attachment.OrganizationId.HasValue)
{
await OrganizationUpdateStorage(cipher.OrganizationId.Value);
await dbContext.UserBumpAccountRevisionDateByCipherIdAsync(cipher.Id, cipher.OrganizationId.Value);
}
else if (attachment.UserId.HasValue)
{
await UserUpdateStorage(attachment.UserId.Value);
await dbContext.UserBumpAccountRevisionDateAsync(attachment.UserId.Value);
}
await dbContext.SaveChangesAsync();
}
}
public async Task UpdateCiphersAsync(Guid userId, IEnumerable<Core.Vault.Entities.Cipher> ciphers)
{
if (!ciphers.Any())
{
return;
}
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var ciphersToUpdate = ciphers.ToDictionary(c => c.Id);
var existingCiphers = await dbContext.Ciphers
.Where(c => c.UserId == userId && ciphersToUpdate.Keys.Contains(c.Id))
.ToDictionaryAsync(c => c.Id);
foreach (var (cipherId, cipher) in ciphersToUpdate)
{
if (!existingCiphers.TryGetValue(cipherId, out var existingCipher))