Add project files
This commit is contained in:
parent
4dafed3553
commit
8cf01ead74
40 changed files with 3967 additions and 0 deletions
66
StalwartSimpleLoginMiddleware/Utilities/ApiKeyHelper.cs
Normal file
66
StalwartSimpleLoginMiddleware/Utilities/ApiKeyHelper.cs
Normal 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));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue