Add project files

This commit is contained in:
Sean Greenawalt 2025-05-10 05:16:40 -04:00
commit 8cf01ead74
Signed by: seang96
GPG key ID: 504F02B511005571
40 changed files with 3967 additions and 0 deletions

View file

@ -0,0 +1,66 @@
using System.Net.Mail;
using System.Security.Cryptography;
using StalwartSimpleLoginMiddleware.Entities;
using StalwartSimpleLoginMiddleware.Models;
namespace StalwartSimpleLoginMiddleware.Utilities;
public class ApiKeyHelper
{
public static string GenerateKey()
{
var key = new byte[64];
using (var generator = RandomNumberGenerator.Create())
generator.GetBytes(key);
return Convert.ToBase64String(key);
}
public static DbApiKey CreateDbApiKey(ApiKey dbKey)
{
return new DbApiKey
{
Key = dbKey.Key,
OwnerName = dbKey.OwnerEmail,
Claims = ClaimsHelper.BuildClaims(dbKey)
};
}
public static KeyMetadata CreateKeyMetadata(ApiKey dbKey)
{
return new KeyMetadata
{
Domain = GetEmailDomain(dbKey.OwnerEmail),
Members = GetMembers(dbKey, false),
ExternalMembers = GetMembers(dbKey, true)
};
}
public static ICollection<string> GetMembers(ApiKey dbKey, bool isExternal)
{
var members = dbKey.Members.Where(m => m.IsExternal == isExternal)
.Select(m => m.Email);
if (!isExternal)
{
return members.Append(dbKey.OwnerEmail)
.ToArray();
}
return members.ToArray();
}
public static string GetEmailDomain(string email)
{
if (string.IsNullOrEmpty(email))
{
throw new ArgumentException("Email cannot be null or empty.", nameof(email));
}
if (MailAddress.TryCreate(email, out var address))
{
return address.Host;
}
throw new ArgumentException($"Invalid email format: {email}", nameof(email));
}
}