66 lines
No EOL
1.7 KiB
C#
66 lines
No EOL
1.7 KiB
C#
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));
|
|
}
|
|
} |