using MongoDB.Bson.IO;
using System.Security.Cryptography;
using System.Text.Json;
namespace AobaV2;
public class AuthInfo
{
public required string Issuer;
public required string Audience;
public required byte[] SecureKey;
///
/// Save this auth into in a json format to the sepcified file
///
/// File path
///
public AuthInfo Save(string path)
{
File.WriteAllText(path, JsonSerializer.Serialize(this));
return this;
}
///
/// Generate a new Auth Info with newly generated keys
///
///
///
///
public static AuthInfo Create(string issuer, string audience)
{
var auth = new AuthInfo
{
Issuer = issuer,
Audience = audience,
SecureKey = GenetateJWTKey()
};
return auth;
}
///
/// Load auth info from a json file
///
/// File path
///
internal static AuthInfo? Load(string path)
{
return JsonSerializer.Deserialize(File.ReadAllText(path));
}
internal static AuthInfo LoadOrCreate(string path, string issuer, string audience)
{
if (File.Exists(path))
{
var loaded = Load(path);
if(loaded != null)
return loaded;
}
var info = Create(issuer, audience);
info.Save(path);
return info;
}
///
/// Generate a new key for use by JWT
///
///
public static byte[] GenetateJWTKey(int size = 64)
{
var key = new byte[size];
RandomNumberGenerator.Fill(key);
return key;
}
}