using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization.Attributes; using System.Security.Cryptography; using System.Text.Json; namespace AobaServer.Models; public class AuthInfo { [BsonId] public ObjectId Id { get; set; } public required string Issuer { get; set; } public required string Audience { get; set; } public required byte[] SecureKey { get; set; } /// /// 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; } }