♻️ Mix things up

This commit is contained in:
2025-07-13 01:55:35 +08:00
parent 4a7f2e18b3
commit e66abe2e0c
19 changed files with 546 additions and 78 deletions

View File

@@ -2,6 +2,7 @@ using System.Linq.Expressions;
using System.Reflection;
using DysonNetwork.Pass.Account;
using DysonNetwork.Pass.Auth;
using DysonNetwork.Pass.Developer;
using DysonNetwork.Pass.Permission;
using DysonNetwork.Pass.Wallet;
using DysonNetwork.Shared.Data;
@@ -46,6 +47,9 @@ public class AppDatabase(
public DbSet<Transaction> PaymentTransactions { get; set; }
public DbSet<Subscription> WalletSubscriptions { get; set; }
public DbSet<Coupon> WalletCoupons { get; set; }
public DbSet<CustomApp> CustomApps { get; set; }
public DbSet<CustomAppSecret> CustomAppSecrets { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{

View File

@@ -5,6 +5,7 @@ using System.Text;
using DysonNetwork.Pass.Auth.OidcProvider.Models;
using DysonNetwork.Pass.Auth.OidcProvider.Options;
using DysonNetwork.Pass.Auth.OidcProvider.Responses;
using DysonNetwork.Pass.Developer;
using DysonNetwork.Shared.Cache;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;

View File

@@ -2,6 +2,7 @@ using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
using DysonNetwork.Pass;
using DysonNetwork.Pass.Developer;
using DysonNetwork.Shared.Data;
using NodaTime;
using NodaTime.Serialization.Protobuf;
@@ -21,7 +22,7 @@ public class AuthSession : ModelBase
public Guid ChallengeId { get; set; }
public AuthChallenge Challenge { get; set; } = null!;
public Guid? AppId { get; set; }
// public CustomApp? App { get; set; }
public CustomApp? App { get; set; }
public Shared.Proto.AuthSession ToProtoValue() => new()
{

View File

@@ -0,0 +1,68 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
using DysonNetwork.Pass.Account;
using DysonNetwork.Shared.Data;
using NodaTime;
namespace DysonNetwork.Pass.Developer;
public enum CustomAppStatus
{
Developing,
Staging,
Production,
Suspended
}
public class CustomApp : ModelBase, IIdentifiedResource
{
public Guid Id { get; set; } = Guid.NewGuid();
[MaxLength(1024)] public string Slug { get; set; } = null!;
[MaxLength(1024)] public string Name { get; set; } = null!;
[MaxLength(4096)] public string? Description { get; set; }
public CustomAppStatus Status { get; set; } = CustomAppStatus.Developing;
[Column(TypeName = "jsonb")] public CloudFileReferenceObject? Picture { get; set; }
[Column(TypeName = "jsonb")] public CloudFileReferenceObject? Background { get; set; }
[Column(TypeName = "jsonb")] public VerificationMark? Verification { get; set; }
[Column(TypeName = "jsonb")] public CustomAppOauthConfig? OauthConfig { get; set; }
[Column(TypeName = "jsonb")] public CustomAppLinks? Links { get; set; }
[JsonIgnore] public ICollection<CustomAppSecret> Secrets { get; set; } = new List<CustomAppSecret>();
// TODO: Publisher
[NotMapped] public string ResourceIdentifier => "custom-app/" + Id;
}
public class CustomAppLinks
{
[MaxLength(8192)] public string? HomePage { get; set; }
[MaxLength(8192)] public string? PrivacyPolicy { get; set; }
[MaxLength(8192)] public string? TermsOfService { get; set; }
}
public class CustomAppOauthConfig
{
[MaxLength(1024)] public string? ClientUri { get; set; }
[MaxLength(4096)] public string[] RedirectUris { get; set; } = [];
[MaxLength(4096)] public string[]? PostLogoutRedirectUris { get; set; }
[MaxLength(256)] public string[]? AllowedScopes { get; set; } = ["openid", "profile", "email"];
[MaxLength(256)] public string[] AllowedGrantTypes { get; set; } = ["authorization_code", "refresh_token"];
public bool RequirePkce { get; set; } = true;
public bool AllowOfflineAccess { get; set; } = false;
}
public class CustomAppSecret : ModelBase
{
public Guid Id { get; set; } = Guid.NewGuid();
[MaxLength(1024)] public string Secret { get; set; } = null!;
[MaxLength(4096)] public string? Description { get; set; } = null!;
public Instant? ExpiredAt { get; set; }
public bool IsOidc { get; set; } = false; // Indicates if this secret is for OIDC/OAuth
public Guid AppId { get; set; }
public CustomApp App { get; set; } = null!;
}

View File

@@ -1,92 +1,56 @@
using MailKit.Net.Smtp;
using dotnet_etcd;
using DysonNetwork.Shared.Proto;
using Microsoft.AspNetCore.Components;
using MimeKit;
namespace DysonNetwork.Pass.Email;
public class EmailServiceConfiguration
{
public string Server { get; set; } = null!;
public int Port { get; set; }
public bool UseSsl { get; set; }
public string Username { get; set; } = null!;
public string Password { get; set; } = null!;
public string FromAddress { get; set; } = null!;
public string FromName { get; set; } = null!;
public string SubjectPrefix { get; set; } = null!;
}
public class EmailService
{
private readonly EmailServiceConfiguration _configuration;
private readonly PusherService.PusherServiceClient _client;
private readonly RazorViewRenderer _viewRenderer;
private readonly ILogger<EmailService> _logger;
public EmailService(IConfiguration configuration, RazorViewRenderer viewRenderer, ILogger<EmailService> logger)
public EmailService(
EtcdClient etcd,
RazorViewRenderer viewRenderer,
IConfiguration configuration,
ILogger<EmailService> logger,
PusherService.PusherServiceClient client
)
{
var cfg = configuration.GetSection("Email").Get<EmailServiceConfiguration>();
_configuration = cfg ?? throw new ArgumentException("Email service was not configured.");
_client = GrpcClientHelper.CreatePusherServiceClient(
etcd,
configuration["Service:CertPath"]!,
configuration["Service:KeyPath"]!
).GetAwaiter().GetResult();
_viewRenderer = viewRenderer;
_logger = logger;
_client = client;
}
public async Task SendEmailAsync(string? recipientName, string recipientEmail, string subject, string textBody)
public async Task SendEmailAsync(
string? recipientName,
string recipientEmail,
string subject,
string htmlBody
)
{
await SendEmailAsync(recipientName, recipientEmail, subject, textBody, null);
subject = $"[Solarpass] {subject}";
await _client.SendEmailAsync(
new SendEmailRequest()
{
Email = new EmailMessage()
{
ToName = recipientName,
ToAddress = recipientEmail,
Subject = subject,
Body = htmlBody
}
}
);
}
public async Task SendEmailAsync(string? recipientName, string recipientEmail, string subject, string textBody,
string? htmlBody)
{
subject = $"[{_configuration.SubjectPrefix}] {subject}";
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress(_configuration.FromName, _configuration.FromAddress));
emailMessage.To.Add(new MailboxAddress(recipientName, recipientEmail));
emailMessage.Subject = subject;
var bodyBuilder = new BodyBuilder
{
TextBody = textBody
};
if (!string.IsNullOrEmpty(htmlBody))
bodyBuilder.HtmlBody = htmlBody;
emailMessage.Body = bodyBuilder.ToMessageBody();
using var client = new SmtpClient();
await client.ConnectAsync(_configuration.Server, _configuration.Port, _configuration.UseSsl);
await client.AuthenticateAsync(_configuration.Username, _configuration.Password);
await client.SendAsync(emailMessage);
await client.DisconnectAsync(true);
}
private static string _ConvertHtmlToPlainText(string html)
{
// Remove style tags and their contents
html = System.Text.RegularExpressions.Regex.Replace(html, "<style[^>]*>.*?</style>", "",
System.Text.RegularExpressions.RegexOptions.Singleline);
// Replace header tags with text + newlines
html = System.Text.RegularExpressions.Regex.Replace(html, "<h[1-6][^>]*>(.*?)</h[1-6]>", "$1\n\n",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Replace line breaks
html = html.Replace("<br>", "\n").Replace("<br/>", "\n").Replace("<br />", "\n");
// Remove all remaining HTML tags
html = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
// Decode HTML entities
html = System.Net.WebUtility.HtmlDecode(html);
// Remove excess whitespace
html = System.Text.RegularExpressions.Regex.Replace(html, @"\s+", " ").Trim();
return html;
}
public async Task SendTemplatedEmailAsync<TComponent, TModel>(string? recipientName, string recipientEmail,
string subject, TModel model)
where TComponent : IComponent
@@ -94,8 +58,7 @@ public class EmailService
try
{
var htmlBody = await _viewRenderer.RenderComponentToStringAsync<TComponent, TModel>(model);
var fallbackTextBody = _ConvertHtmlToPlainText(htmlBody);
await SendEmailAsync(recipientName, recipientEmail, subject, fallbackTextBody, htmlBody);
await SendEmailAsync(recipientName, recipientEmail, subject, htmlBody);
}
catch (Exception err)
{

View File

@@ -1,6 +1,7 @@
using DysonNetwork.Pass;
using DysonNetwork.Pass.Account;
using DysonNetwork.Pass.Startup;
using DysonNetwork.Shared.Registry;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
@@ -12,6 +13,7 @@ builder.ConfigureAppKestrel();
builder.Services.AddAppMetrics();
// Add application services
builder.Services.AddEtcdService(builder.Configuration);
builder.Services.AddAppServices(builder.Configuration);
builder.Services.AddAppRateLimiting();
builder.Services.AddAppAuthentication();
@@ -26,6 +28,8 @@ builder.Services.AddAppBusinessServices(builder.Configuration);
// Add scheduled jobs
builder.Services.AddAppScheduledJobs();
builder.Services.AddHostedService<ServiceRegistrationHostedService>();
var app = builder.Build();
// Run database migrations

View File

@@ -0,0 +1,56 @@
using DysonNetwork.Shared.Registry;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;
namespace DysonNetwork.Pass.Startup;
public class ServiceRegistrationHostedService : IHostedService
{
private readonly ServiceRegistry _serviceRegistry;
private readonly IConfiguration _configuration;
private readonly ILogger<ServiceRegistrationHostedService> _logger;
public ServiceRegistrationHostedService(
ServiceRegistry serviceRegistry,
IConfiguration configuration,
ILogger<ServiceRegistrationHostedService> logger)
{
_serviceRegistry = serviceRegistry;
_configuration = configuration;
_logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
var serviceName = "DysonNetwork.Pass"; // Preset service name
var serviceUrl = _configuration["Service:Url"];
if (string.IsNullOrEmpty(serviceName) || string.IsNullOrEmpty(serviceUrl))
{
_logger.LogWarning("Service name or URL not configured. Skipping Etcd registration.");
return;
}
_logger.LogInformation("Registering service {ServiceName} at {ServiceUrl} with Etcd.", serviceName, serviceUrl);
try
{
await _serviceRegistry.RegisterService(serviceName, serviceUrl);
_logger.LogInformation("Service {ServiceName} registered successfully.", serviceName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to register service {ServiceName} with Etcd.", serviceName);
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
// The lease will expire automatically if the service stops.
// For explicit unregistration, you would implement it here.
_logger.LogInformation("Service registration hosted service is stopping.");
return Task.CompletedTask;
}
}