Authinator/Backend/Database/Tables/Config.cs
2023-06-01 06:14:24 +02:00

52 lines
1.8 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Authinator.Backend.Database.Tables;
public record Config(string Key, string Value) {
public string Key { get; set; } = Key;
public string Value { get; set; } = Value;
public class Configuration : IEntityTypeConfiguration<Config> {
public void Configure(EntityTypeBuilder<Config> config) {
config.ToTable("Config");
config.HasKey(p => p.Key);
config.Property(b => b.Key).HasColumnName("Key").IsRequired();
config.Property(b => b.Value).HasColumnName("Value").IsRequired();
}
}
}
public static class ConfigUtils {
public static bool HasKey(this DbSet<Config> config, string key) {
return config.Any(p => p.Key == key);
}
public static string? Get(this DbSet<Config> config, string key) {
return config.HasKey(key) ? config.First(p => p.Key == key).Value : null;
}
public static async void Set(this DbSet<Config> config, string key, string value, bool overwrite = true) {
if (!config.HasKey(key))
await config.AddAsync(new Config(key, value));
else if (overwrite)
config.First(p => p.Key == key).Value = value;
}
}
public static class ConfigCache {
public static string CookieName = null!;
public static string AdminGroup = null!;
public static string HmacSecret = null!;
public static TimeSpan AuthTokenLifetime;
public static TimeSpan PwResetTokenLifetime;
public static void UpdateCache(this DbSet<Config> config) {
CookieName = config.Get("cookie_name")!;
AdminGroup = config.Get("admin_group")!;
HmacSecret = config.Get("hmac_secret")!;
AuthTokenLifetime = TimeSpan.FromSeconds(long.Parse(config.Get("auth_token_lifetime")!));
PwResetTokenLifetime = TimeSpan.FromSeconds(long.Parse(config.Get("pw_reset_token_lifetime")!));
}
}