From 526c2364b9ad685d1c000fc8a168bf1305aaa8b7 Mon Sep 17 00:00:00 2001 From: vman Date: Fri, 18 Nov 2022 16:08:51 -0500 Subject: Add project files. --- .../src/TokenRevocation/RevokedTokenStore.cs | 77 ++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 VNLib.Plugins.Essentials.Accounts.Registration/src/TokenRevocation/RevokedTokenStore.cs (limited to 'VNLib.Plugins.Essentials.Accounts.Registration/src/TokenRevocation/RevokedTokenStore.cs') diff --git a/VNLib.Plugins.Essentials.Accounts.Registration/src/TokenRevocation/RevokedTokenStore.cs b/VNLib.Plugins.Essentials.Accounts.Registration/src/TokenRevocation/RevokedTokenStore.cs new file mode 100644 index 0000000..ccc7b37 --- /dev/null +++ b/VNLib.Plugins.Essentials.Accounts.Registration/src/TokenRevocation/RevokedTokenStore.cs @@ -0,0 +1,77 @@ +using System.Collections; + +using Microsoft.EntityFrameworkCore; + +using VNLib.Utils; + +namespace VNLib.Plugins.Essentials.Accounts.Registration.TokenRevocation +{ + internal class RevokedTokenStore + { + private readonly DbContextOptions Options; + + public RevokedTokenStore(DbContextOptions options) + { + Options = options; + } + + public async Task IsRevokedAsync(string token, CancellationToken cancellation) + { + await using RevocationContext context = new (Options); + await context.OpenTransactionAsync(cancellation); + + //Select any that match tokens + bool any = await (from t in context.RevokedRegistrationTokens + where t.Token == token + select t).AnyAsync(cancellation); + + await context.CommitTransactionAsync(cancellation); + return any; + } + + public async Task RevokeAsync(string token, CancellationToken cancellation) + { + await using RevocationContext context = new (Options); + await context.OpenTransactionAsync(cancellation); + + //Add to table + context.RevokedRegistrationTokens.Add(new RevokedToken() + { + Created = DateTime.UtcNow, + Token = token + }); + + //Save changes and commit transaction + await context.SaveChangesAsync(cancellation); + await context.CommitTransactionAsync(cancellation); + } + + /// + /// Removes expired records from the store + /// + /// The time a token is valid for + /// A token that cancels the async operation + /// The number of records evicted from the store + public async Task CleanTableAsync(TimeSpan validFor, CancellationToken cancellation) + { + DateTime expiredBefore = DateTime.UtcNow.Subtract(validFor); + + await using RevocationContext context = new (Options); + await context.OpenTransactionAsync(cancellation); + + //Select any that match tokens + RevokedToken[] expired = await context.RevokedRegistrationTokens.Where(t => t.Created < expiredBefore) + .Select(static t => t) + .ToArrayAsync(cancellation); + + + context.RevokedRegistrationTokens.RemoveRange(expired); + + ERRNO count =await context.SaveChangesAsync(cancellation); + + await context.CommitTransactionAsync(cancellation); + + return count; + } + } +} \ No newline at end of file -- cgit