-
-
Notifications
You must be signed in to change notification settings - Fork 486
/
OpenIddictEntityFrameworkCoreTokenStore.cs
1115 lines (914 loc) · 39.1 KB
/
OpenIddictEntityFrameworkCoreTokenStore.cs
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
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Collections.Immutable;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using OpenIddict.EntityFrameworkCore.Models;
using OpenIddict.Extensions;
using static OpenIddict.Abstractions.OpenIddictExceptions;
namespace OpenIddict.EntityFrameworkCore;
/// <summary>
/// Provides methods allowing to manage the tokens stored in a database.
/// </summary>
/// <typeparam name="TContext">The type of the Entity Framework database context.</typeparam>
public class OpenIddictEntityFrameworkCoreTokenStore<TContext> :
OpenIddictEntityFrameworkCoreTokenStore<OpenIddictEntityFrameworkCoreToken,
OpenIddictEntityFrameworkCoreApplication,
OpenIddictEntityFrameworkCoreAuthorization, TContext, string>
where TContext : DbContext
{
public OpenIddictEntityFrameworkCoreTokenStore(
IMemoryCache cache,
TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options)
: base(cache, context, options)
{
}
}
/// <summary>
/// Provides methods allowing to manage the tokens stored in a database.
/// </summary>
/// <typeparam name="TContext">The type of the Entity Framework database context.</typeparam>
/// <typeparam name="TKey">The type of the entity primary keys.</typeparam>
public class OpenIddictEntityFrameworkCoreTokenStore<TContext, TKey> :
OpenIddictEntityFrameworkCoreTokenStore<OpenIddictEntityFrameworkCoreToken<TKey>,
OpenIddictEntityFrameworkCoreApplication<TKey>,
OpenIddictEntityFrameworkCoreAuthorization<TKey>, TContext, TKey>
where TContext : DbContext
where TKey : notnull, IEquatable<TKey>
{
public OpenIddictEntityFrameworkCoreTokenStore(
IMemoryCache cache,
TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options)
: base(cache, context, options)
{
}
}
/// <summary>
/// Provides methods allowing to manage the tokens stored in a database.
/// </summary>
/// <typeparam name="TToken">The type of the Token entity.</typeparam>
/// <typeparam name="TApplication">The type of the Application entity.</typeparam>
/// <typeparam name="TAuthorization">The type of the Authorization entity.</typeparam>
/// <typeparam name="TContext">The type of the Entity Framework database context.</typeparam>
/// <typeparam name="TKey">The type of the entity primary keys.</typeparam>
public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuthorization, TContext, TKey> : IOpenIddictTokenStore<TToken>
where TToken : OpenIddictEntityFrameworkCoreToken<TKey, TApplication, TAuthorization>
where TApplication : OpenIddictEntityFrameworkCoreApplication<TKey, TAuthorization, TToken>
where TAuthorization : OpenIddictEntityFrameworkCoreAuthorization<TKey, TApplication, TToken>
where TContext : DbContext
where TKey : notnull, IEquatable<TKey>
{
public OpenIddictEntityFrameworkCoreTokenStore(
IMemoryCache cache,
TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options)
{
Cache = cache ?? throw new ArgumentNullException(nameof(cache));
Context = context ?? throw new ArgumentNullException(nameof(context));
Options = options ?? throw new ArgumentNullException(nameof(options));
}
/// <summary>
/// Gets the memory cache associated with the current store.
/// </summary>
protected IMemoryCache Cache { get; }
/// <summary>
/// Gets the database context associated with the current store.
/// </summary>
protected TContext Context { get; }
/// <summary>
/// Gets the options associated with the current store.
/// </summary>
protected IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> Options { get; }
/// <summary>
/// Gets the database set corresponding to the <typeparamref name="TApplication"/> entity.
/// </summary>
private DbSet<TApplication> Applications => Context.Set<TApplication>();
/// <summary>
/// Gets the database set corresponding to the <typeparamref name="TAuthorization"/> entity.
/// </summary>
private DbSet<TAuthorization> Authorizations => Context.Set<TAuthorization>();
/// <summary>
/// Gets the database set corresponding to the <typeparamref name="TToken"/> entity.
/// </summary>
private DbSet<TToken> Tokens => Context.Set<TToken>();
/// <inheritdoc/>
public virtual async ValueTask<long> CountAsync(CancellationToken cancellationToken)
=> await Tokens.AsQueryable().LongCountAsync(cancellationToken);
/// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TToken>, IQueryable<TResult>> query, CancellationToken cancellationToken)
{
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Tokens).LongCountAsync(cancellationToken);
}
/// <inheritdoc/>
public virtual async ValueTask CreateAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
Context.Add(token);
await Context.SaveChangesAsync(cancellationToken);
}
/// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
Context.Remove(token);
try
{
await Context.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateConcurrencyException exception)
{
// Reset the state of the entity to prevents future calls to SaveChangesAsync() from failing.
Context.Entry(token).State = EntityState.Unchanged;
throw new ConcurrencyException(SR.GetResourceString(SR.ID0247), exception);
}
}
/// <inheritdoc/>
public virtual IAsyncEnumerable<TToken> FindAsync(string subject, string client, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(subject))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0198), nameof(subject));
}
if (string.IsNullOrEmpty(client))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0124), nameof(client));
}
// Note: due to a bug in Entity Framework Core's query visitor, the authorizations can't be
// filtered using token.Application.Id.Equals(key). To work around this issue,
// this compiled query uses an explicit join before applying the equality check.
// See https://github.com/openiddict/openiddict-core/issues/499 for more information.
var key = ConvertIdentifierFromString(client);
return (from token in Tokens.Include(token => token.Application).Include(token => token.Authorization).AsTracking()
where token.Subject == subject
join application in Applications.AsTracking() on token.Application!.Id equals application.Id
where application.Id!.Equals(key)
select token).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/>
public virtual IAsyncEnumerable<TToken> FindAsync(
string subject, string client,
string status, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(subject))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0198), nameof(subject));
}
if (string.IsNullOrEmpty(client))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0124), nameof(client));
}
if (string.IsNullOrEmpty(status))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0199), nameof(status));
}
// Note: due to a bug in Entity Framework Core's query visitor, the authorizations can't be
// filtered using token.Application.Id.Equals(key). To work around this issue,
// this compiled query uses an explicit join before applying the equality check.
// See https://github.com/openiddict/openiddict-core/issues/499 for more information.
var key = ConvertIdentifierFromString(client);
return (from token in Tokens.Include(token => token.Application).Include(token => token.Authorization).AsTracking()
where token.Subject == subject &&
token.Status == status
join application in Applications.AsTracking() on token.Application!.Id equals application.Id
where application.Id!.Equals(key)
select token).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/>
public virtual IAsyncEnumerable<TToken> FindAsync(
string subject, string client,
string status, string type, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(subject))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0198), nameof(subject));
}
if (string.IsNullOrEmpty(client))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0124), nameof(client));
}
if (string.IsNullOrEmpty(status))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0199), nameof(status));
}
if (string.IsNullOrEmpty(type))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0200), nameof(type));
}
// Note: due to a bug in Entity Framework Core's query visitor, the authorizations can't be
// filtered using token.Application.Id.Equals(key). To work around this issue,
// this compiled query uses an explicit join before applying the equality check.
// See https://github.com/openiddict/openiddict-core/issues/499 for more information.
var key = ConvertIdentifierFromString(client);
return (from token in Tokens.Include(token => token.Application).Include(token => token.Authorization).AsTracking()
where token.Subject == subject &&
token.Status == status &&
token.Type == type
join application in Applications.AsTracking() on token.Application!.Id equals application.Id
where application.Id!.Equals(key)
select token).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/>
public virtual IAsyncEnumerable<TToken> FindByApplicationIdAsync(string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0195), nameof(identifier));
}
// Note: due to a bug in Entity Framework Core's query visitor, the tokens can't be
// filtered using token.Application.Id.Equals(key). To work around this issue,
// this method is overridden to use an explicit join before applying the equality check.
// See https://github.com/openiddict/openiddict-core/issues/499 for more information.
var key = ConvertIdentifierFromString(identifier);
return (from token in Tokens.Include(token => token.Application).Include(token => token.Authorization).AsTracking()
join application in Applications.AsTracking() on token.Application!.Id equals application.Id
where application.Id!.Equals(key)
select token).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/>
public virtual IAsyncEnumerable<TToken> FindByAuthorizationIdAsync(string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0195), nameof(identifier));
}
// Note: due to a bug in Entity Framework Core's query visitor, the tokens can't be
// filtered using token.Authorization.Id.Equals(key). To work around this issue,
// this method is overridden to use an explicit join before applying the equality check.
// See https://github.com/openiddict/openiddict-core/issues/499 for more information.
var key = ConvertIdentifierFromString(identifier);
return (from token in Tokens.Include(token => token.Application).Include(token => token.Authorization).AsTracking()
join authorization in Authorizations.AsTracking() on token.Authorization!.Id equals authorization.Id
where authorization.Id!.Equals(key)
select token).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/>
public virtual ValueTask<TToken?> FindByIdAsync(string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0195), nameof(identifier));
}
var key = ConvertIdentifierFromString(identifier);
return GetTrackedEntity() is TToken token ? new(token) : new(QueryAsync());
TToken? GetTrackedEntity() =>
(from entry in Context.ChangeTracker.Entries<TToken>()
where entry.Entity.Id is TKey identifier && identifier.Equals(key)
select entry.Entity).FirstOrDefault();
Task<TToken?> QueryAsync() =>
(from token in Tokens.Include(token => token.Application).Include(token => token.Authorization).AsTracking()
where token.Id!.Equals(key)
select token).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/>
public virtual ValueTask<TToken?> FindByReferenceIdAsync(string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0195), nameof(identifier));
}
return GetTrackedEntity() is TToken token ? new(token) : new(QueryAsync());
TToken? GetTrackedEntity() =>
(from entry in Context.ChangeTracker.Entries<TToken>()
where string.Equals(entry.Entity.ReferenceId, identifier, StringComparison.Ordinal)
select entry.Entity).FirstOrDefault();
Task<TToken?> QueryAsync() =>
(from token in Tokens.Include(token => token.Application).Include(token => token.Authorization).AsTracking()
where token.ReferenceId == identifier
select token).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/>
public virtual IAsyncEnumerable<TToken> FindBySubjectAsync(string subject, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(subject))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0198), nameof(subject));
}
return (from token in Tokens.Include(token => token.Application).Include(token => token.Authorization).AsTracking()
where token.Subject == subject
select token).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/>
public virtual async ValueTask<string?> GetApplicationIdAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
// If the application is not attached to the token, try to load it manually.
if (token.Application is null)
{
var reference = Context.Entry(token).Reference(entry => entry.Application);
if (reference.EntityEntry.State is EntityState.Detached)
{
return null;
}
await reference.LoadAsync(cancellationToken);
}
if (token.Application is null)
{
return null;
}
return ConvertIdentifierToString(token.Application.Id);
}
/// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TToken>, TState, IQueryable<TResult>> query,
TState state, CancellationToken cancellationToken)
{
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Tokens.Include(token => token.Application)
.Include(token => token.Authorization)
.AsTracking(), state).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/>
public virtual async ValueTask<string?> GetAuthorizationIdAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
// If the authorization is not attached to the token, try to load it manually.
if (token.Authorization is null)
{
var reference = Context.Entry(token).Reference(entry => entry.Authorization);
if (reference.EntityEntry.State is EntityState.Detached)
{
return null;
}
await reference.LoadAsync(cancellationToken);
}
if (token.Authorization is null)
{
return null;
}
return ConvertIdentifierToString(token.Authorization.Id);
}
/// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.CreationDate is null)
{
return new(result: null);
}
return new(DateTime.SpecifyKind(token.CreationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetExpirationDateAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.ExpirationDate is null)
{
return new(result: null);
}
return new(DateTime.SpecifyKind(token.ExpirationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new(ConvertIdentifierToString(token.Id));
}
/// <inheritdoc/>
public virtual ValueTask<string?> GetPayloadAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new(token.Payload);
}
/// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (string.IsNullOrEmpty(token.Properties))
{
return new(ImmutableDictionary.Create<string, JsonElement>());
}
// Note: parsing the stringified properties is an expensive operation.
// To mitigate that, the resulting object is stored in the memory cache.
var key = string.Concat("d0509397-1bbf-40e7-97e1-5e6d7bc2536c", "\x1e", token.Properties);
var properties = Cache.GetOrCreate(key, entry =>
{
entry.SetPriority(CacheItemPriority.High)
.SetSlidingExpiration(TimeSpan.FromMinutes(1));
using var document = JsonDocument.Parse(token.Properties);
var builder = ImmutableDictionary.CreateBuilder<string, JsonElement>();
foreach (var property in document.RootElement.EnumerateObject())
{
builder[property.Name] = property.Value.Clone();
}
return builder.ToImmutable();
})!;
return new(properties);
}
/// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetRedemptionDateAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.RedemptionDate is null)
{
return new(result: null);
}
return new(DateTime.SpecifyKind(token.RedemptionDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/>
public virtual ValueTask<string?> GetReferenceIdAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new(token.ReferenceId);
}
/// <inheritdoc/>
public virtual ValueTask<string?> GetStatusAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new(token.Status);
}
/// <inheritdoc/>
public virtual ValueTask<string?> GetSubjectAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new(token.Subject);
}
/// <inheritdoc/>
public virtual ValueTask<string?> GetTypeAsync(TToken token, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new(token.Type);
}
/// <inheritdoc/>
public virtual ValueTask<TToken> InstantiateAsync(CancellationToken cancellationToken)
{
try
{
return new(Activator.CreateInstance<TToken>());
}
catch (MemberAccessException exception)
{
return new(Task.FromException<TToken>(
new InvalidOperationException(SR.GetResourceString(SR.ID0248), exception)));
}
}
/// <inheritdoc/>
public virtual IAsyncEnumerable<TToken> ListAsync(int? count, int? offset, CancellationToken cancellationToken)
{
var query = Tokens.Include(token => token.Application)
.Include(token => token.Authorization)
.OrderBy(token => token.Id!)
.AsTracking();
if (offset.HasValue)
{
query = query.Skip(offset.Value);
}
if (count.HasValue)
{
query = query.Take(count.Value);
}
return query.AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TToken>, TState, IQueryable<TResult>> query,
TState state, CancellationToken cancellationToken)
{
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return query(
Tokens.Include(token => token.Application)
.Include(token => token.Authorization)
.AsTracking(), state).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/>
public virtual async ValueTask<long> PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken)
{
List<Exception>? exceptions = null;
var result = 0L;
// Note: the Oracle MySQL provider doesn't support DateTimeOffset and is unable
// to create a SQL query with an expression calling DateTimeOffset.UtcDateTime.
// To work around this limitation, the threshold represented as a DateTimeOffset
// instance is manually converted to a UTC DateTime instance outside the query.
var date = threshold.UtcDateTime;
// Note: to avoid sending too many queries, the maximum number of elements
// that can be removed by a single call to PruneAsync() is deliberately limited.
for (var index = 0; index < 1_000; index++)
{
cancellationToken.ThrowIfCancellationRequested();
#if SUPPORTS_BULK_DBSET_OPERATIONS
if (!Options.CurrentValue.DisableBulkOperations)
{
try
{
var count = await
(from token in Tokens
where token.CreationDate < date
where (token.Status != Statuses.Inactive && token.Status != Statuses.Valid) ||
(token.Authorization != null && token.Authorization.Status != Statuses.Valid) ||
token.ExpirationDate < DateTime.UtcNow
orderby token.Id
select token).Take(1_000).ExecuteDeleteAsync(cancellationToken);
if (count is 0)
{
break;
}
// Note: calling DbContext.SaveChangesAsync() is not necessary
// with bulk delete operations as they are executed immediately.
result += count;
}
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
{
exceptions ??= new List<Exception>(capacity: 1);
exceptions.Add(exception);
}
}
else
#endif
{
var strategy = Context.Database.CreateExecutionStrategy();
var count = await strategy.ExecuteAsync(async () =>
{
// To prevent concurrency exceptions from being thrown if an entry is modified
// after it was retrieved from the database, the following logic is executed in
// a repeatable read transaction, that will put a lock on the retrieved entries
// and thus prevent them from being concurrently modified outside this block.
using var transaction = await Context.CreateTransactionAsync(IsolationLevel.RepeatableRead, cancellationToken);
var tokens = await
(from token in Tokens.AsTracking()
where token.CreationDate < date
where (token.Status != Statuses.Inactive && token.Status != Statuses.Valid) ||
(token.Authorization != null && token.Authorization.Status != Statuses.Valid) ||
token.ExpirationDate < DateTime.UtcNow
orderby token.Id
select token).Take(1_000).ToListAsync(cancellationToken);
if (tokens.Count is not 0)
{
Context.RemoveRange(tokens);
try
{
await Context.SaveChangesAsync(cancellationToken);
transaction?.Commit();
}
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
{
exceptions ??= [];
exceptions.Add(exception);
}
}
return tokens.Count;
});
if (count is 0)
{
break;
}
result += count;
}
}
if (exceptions is not null)
{
throw new AggregateException(SR.GetResourceString(SR.ID0249), exceptions);
}
return result;
}
/// <inheritdoc/>
public virtual async ValueTask<long> RevokeByAuthorizationIdAsync(string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0195), nameof(identifier));
}
var key = ConvertIdentifierFromString(identifier);
#if SUPPORTS_BULK_DBSET_OPERATIONS
if (!Options.CurrentValue.DisableBulkOperations)
{
return await (
from token in Tokens
where token.Authorization!.Id!.Equals(key)
select token).ExecuteUpdateAsync(entity => entity.SetProperty(
token => token.Status, Statuses.Revoked), cancellationToken);
// Note: calling DbContext.SaveChangesAsync() is not necessary
// with bulk update operations as they are executed immediately.
}
#endif
List<Exception>? exceptions = null;
var result = 0L;
foreach (var token in await (from token in Tokens
where token.Authorization!.Id!.Equals(key)
select token).ToListAsync(cancellationToken))
{
token.Status = Statuses.Revoked;
try
{
await Context.SaveChangesAsync(cancellationToken);
}
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
{
// Reset the state of the entity to prevents future calls to SaveChangesAsync() from failing.
Context.Entry(token).State = EntityState.Unchanged;
exceptions ??= [];
exceptions.Add(exception);
continue;
}
result++;
}
if (exceptions is not null)
{
throw new AggregateException(SR.GetResourceString(SR.ID0249), exceptions);
}
return result;
}
/// <inheritdoc/>
public virtual async ValueTask SetApplicationIdAsync(TToken token, string? identifier, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (!string.IsNullOrEmpty(identifier))
{
#if SUPPORTS_DBSET_VALUETASK_FINDASYNC
token.Application = await Applications.FindAsync([ConvertIdentifierFromString(identifier)], cancellationToken);
#else
// Warning: when targeting older TFMs, FindAsync() is deliberately not used to work around a breaking
// change introduced in Entity Framework Core 3.x (where a ValueTask instead of a Task is now returned).
var key = ConvertIdentifierFromString(identifier);
token.Application = GetTrackedEntity() ?? await QueryAsync() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0250));
TApplication? GetTrackedEntity() =>
(from entry in Context.ChangeTracker.Entries<TApplication>()
where entry.Entity.Id is TKey identifier && identifier.Equals(key)
select entry.Entity).FirstOrDefault();
Task<TApplication?> QueryAsync() =>
(from application in Applications.AsTracking()
where application.Id!.Equals(key)
select application).FirstOrDefaultAsync(cancellationToken);
#endif
}
else
{
// If the application is not attached to the token, try to load it manually.
if (token.Application is null)
{
var reference = Context.Entry(token).Reference(entry => entry.Application);
if (reference.EntityEntry.State is EntityState.Detached)
{
return;
}
await reference.LoadAsync(cancellationToken);
}
token.Application = null;
}
}
/// <inheritdoc/>
public virtual async ValueTask SetAuthorizationIdAsync(TToken token, string? identifier, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (!string.IsNullOrEmpty(identifier))
{
#if SUPPORTS_DBSET_VALUETASK_FINDASYNC
token.Authorization = await Authorizations.FindAsync([ConvertIdentifierFromString(identifier)], cancellationToken);
#else
// Warning: when targeting older TFMs, FindAsync() is deliberately not used to work around a breaking
// change introduced in Entity Framework Core 3.x (where a ValueTask instead of a Task is now returned).
var key = ConvertIdentifierFromString(identifier);
token.Authorization = GetTrackedEntity() ?? await QueryAsync() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0251));
TAuthorization? GetTrackedEntity() =>
(from entry in Context.ChangeTracker.Entries<TAuthorization>()
where entry.Entity.Id is TKey identifier && identifier.Equals(key)
select entry.Entity).FirstOrDefault();
Task<TAuthorization?> QueryAsync() =>
(from authorization in Authorizations.AsTracking()
where authorization.Id!.Equals(key)
select authorization).FirstOrDefaultAsync(cancellationToken);
#endif
}
else
{
// If the authorization is not attached to the token, try to load it manually.
if (token.Authorization is null)
{
var reference = Context.Entry(token).Reference(entry => entry.Authorization);
if (reference.EntityEntry.State is EntityState.Detached)
{
return;
}
await reference.LoadAsync(cancellationToken);
}
token.Authorization = null;
}
}
/// <inheritdoc/>
public virtual ValueTask SetCreationDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.CreationDate = date?.UtcDateTime;
return default;
}
/// <inheritdoc/>
public virtual ValueTask SetExpirationDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.ExpirationDate = date?.UtcDateTime;
return default;
}
/// <inheritdoc/>
public virtual ValueTask SetPayloadAsync(TToken token, string? payload, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Payload = payload;
return default;
}
/// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TToken token,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (properties is not { Count: > 0 })
{
token.Properties = null;
return default;
}
using var stream = new MemoryStream();
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
Indented = false
});
writer.WriteStartObject();
foreach (var property in properties)
{
writer.WritePropertyName(property.Key);
property.Value.WriteTo(writer);
}
writer.WriteEndObject();
writer.Flush();
token.Properties = Encoding.UTF8.GetString(stream.ToArray());
return default;
}
/// <inheritdoc/>
public virtual ValueTask SetRedemptionDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken)
{
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.RedemptionDate = date?.UtcDateTime;