feat: initial working discord authentication

This commit is contained in:
sam 2024-06-13 02:23:55 +02:00
parent 6186eda092
commit a7950671e1
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
12 changed files with 262 additions and 25 deletions

View file

@ -2,6 +2,7 @@ using Foxnouns.Backend.Database;
using Foxnouns.Backend.Database.Models;
using Foxnouns.Backend.Utils;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using NodaTime;
namespace Foxnouns.Backend.Services;
@ -42,16 +43,18 @@ public class KeyCacheService(DatabaseContext db, IClock clock, ILogger logger)
if (count != 0) logger.Information("Removed {Count} expired keys from the database", count);
}
public async Task<string> GenerateAuthStateAsync()
public Task SetKeyAsync<T>(string key, T obj, Duration expiresAt) where T : class =>
SetKeyAsync(key, obj, clock.GetCurrentInstant() + expiresAt);
public async Task SetKeyAsync<T>(string key, T obj, Instant expires) where T : class
{
var state = OauthUtils.RandomToken();
await SetKeyAsync($"oauth_state:{state}", "", Duration.FromMinutes(10));
return state;
var value = JsonConvert.SerializeObject(obj);
await SetKeyAsync(key, value, expires);
}
public async Task ValidateAuthStateAsync(string state)
public async Task<T?> GetKeyAsync<T>(string key, bool delete = false) where T : class
{
var val = await GetKeyAsync($"oauth_state:{state}", delete: true);
if (val == null) throw new ApiError.BadRequest("Invalid OAuth state");
var value = await GetKeyAsync(key, delete: false);
return value == null ? default : JsonConvert.DeserializeObject<T>(value);
}
}