2024-09-09 14:37:59 +02:00
|
|
|
using Foxnouns.Backend.Database;
|
2024-06-13 02:23:55 +02:00
|
|
|
using Foxnouns.Backend.Services;
|
|
|
|
using Foxnouns.Backend.Utils;
|
|
|
|
using NodaTime;
|
|
|
|
|
|
|
|
namespace Foxnouns.Backend.Extensions;
|
|
|
|
|
|
|
|
public static class KeyCacheExtensions
|
|
|
|
{
|
2024-09-09 14:50:00 +02:00
|
|
|
public static async Task<string> GenerateAuthStateAsync(this KeyCacheService keyCacheService,
|
|
|
|
CancellationToken ct = default)
|
2024-06-13 02:23:55 +02:00
|
|
|
{
|
2024-07-08 19:03:04 +02:00
|
|
|
var state = AuthUtils.RandomToken();
|
2024-09-09 14:50:00 +02:00
|
|
|
await keyCacheService.SetKeyAsync($"oauth_state:{state}", "", Duration.FromMinutes(10), ct);
|
2024-06-13 02:23:55 +02:00
|
|
|
return state;
|
|
|
|
}
|
|
|
|
|
2024-09-09 14:50:00 +02:00
|
|
|
public static async Task ValidateAuthStateAsync(this KeyCacheService keyCacheService, string state,
|
|
|
|
CancellationToken ct = default)
|
2024-06-13 02:23:55 +02:00
|
|
|
{
|
2024-09-09 14:50:00 +02:00
|
|
|
var val = await keyCacheService.GetKeyAsync($"oauth_state:{state}", delete: true, ct);
|
2024-06-13 02:23:55 +02:00
|
|
|
if (val == null) throw new ApiError.BadRequest("Invalid OAuth state");
|
|
|
|
}
|
2024-09-09 14:37:59 +02:00
|
|
|
|
2024-09-09 14:50:00 +02:00
|
|
|
public static async Task<string> GenerateRegisterEmailStateAsync(this KeyCacheService keyCacheService, string email,
|
2024-09-09 14:37:59 +02:00
|
|
|
Snowflake? userId = null, CancellationToken ct = default)
|
|
|
|
{
|
|
|
|
var state = AuthUtils.RandomToken();
|
2024-09-09 14:50:00 +02:00
|
|
|
await keyCacheService.SetKeyAsync($"email_state:{state}", new RegisterEmailState(email, userId),
|
2024-09-09 14:37:59 +02:00
|
|
|
Duration.FromDays(1), ct);
|
|
|
|
return state;
|
|
|
|
}
|
|
|
|
|
2024-09-09 14:50:00 +02:00
|
|
|
public static async Task<RegisterEmailState?> GetRegisterEmailStateAsync(this KeyCacheService keyCacheService,
|
2024-09-09 14:37:59 +02:00
|
|
|
string state, CancellationToken ct = default) =>
|
2024-09-09 14:50:00 +02:00
|
|
|
await keyCacheService.GetKeyAsync<RegisterEmailState>($"email_state:{state}", delete: true, ct);
|
2024-09-09 14:37:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public record RegisterEmailState(string Email, Snowflake? ExistingUserId);
|