/*
* Copyright (c) 2022 Vaughn Nugent
*
* Library: VNLib
* Package: VNLib.Plugins.Essentials.Accounts.Registration
* File: EmailSystemConfig.cs
*
* EmailSystemConfig.cs is part of VNLib.Plugins.Essentials.Accounts.Registration which is part of the larger
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials.Accounts.Registration is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 2 of the License,
* or (at your option) any later version.
*
* VNLib.Plugins.Essentials.Accounts.Registration is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VNLib.Plugins.Essentials.Accounts.Registration. If not, see http://www.gnu.org/licenses/.
*/
using System;
using System.Text;
using System.Text.Json;
using RestSharp;
using Emails.Transactional.Client;
using VNLib.Utils.Extensions;
using VNLib.Net.Rest.Client;
using VNLib.Net.Rest.Client.OAuth2;
using VNLib.Plugins.Extensions.Loading;
namespace VNLib.Plugins.Essentials.Accounts.Registration
{
///
/// An extended configuration
/// object that contains a pool for making
/// transactions
///
internal sealed class EmailSystemConfig : TransactionalEmailConfig
{
public const string REG_TEMPLATE_NAME = "Registration";
public EmailSystemConfig(PluginBase pbase)
{
IReadOnlyDictionary conf = pbase.GetConfig("email");
EmailFromName = conf["from_name"].GetString() ?? throw new KeyNotFoundException("");
EmailFromAddress = conf["from_address"].GetString() ?? throw new KeyNotFoundException("");
Uri baseServerPath = new(conf["base_url"].GetString()!, UriKind.RelativeOrAbsolute);
Uri tokenServerBase = new(conf["token_server_url"].GetString()!, UriKind.RelativeOrAbsolute);
Uri transactionEndpoint = new(conf["transaction_path"].GetString()!, UriKind.RelativeOrAbsolute);
//Load templates
Dictionary templates = conf["templates"].EnumerateObject().ToDictionary(jp => jp.Name, jp => jp.Value.GetString()!);
//Init base config
WithTemplates(templates)
.WithUrl(transactionEndpoint);
//Load credentials
string authEndpoint = conf["token_path"].GetString() ?? throw new KeyNotFoundException();
int maxClients = conf["max_clients"].GetInt32();
//Load oauth secrets from vault
Task oauth2ClientID = pbase.TryGetSecretAsync("oauth2_client_id");
Task oauth2Password = pbase.TryGetSecretAsync("oauth2_client_secret");
//Lazy cred loaded, tasks should be loaded before this method will ever get called
Credential lazyCredentialGet()
{
//Load the results
string cliendId = oauth2ClientID.Result ?? throw new KeyNotFoundException("Missing required oauth2 client id");
string password = oauth2Password.Result ?? throw new KeyNotFoundException("Missing required oauth2 client secret");
return Credential.Create(cliendId, password);
}
//Init client creation options
RestClientOptions poolOptions = new()
{
AllowMultipleDefaultParametersWithSameName = true,
AutomaticDecompression = System.Net.DecompressionMethods.All,
PreAuthenticate = true,
Encoding = Encoding.UTF8,
MaxTimeout = conf["request_timeout_ms"].GetInt32(),
UserAgent = "Essentials.EmailRegistation",
FollowRedirects = false,
BaseUrl = baseServerPath
};
//Options for auth token endpoint
RestClientOptions oAuth2ClientOptions = new()
{
AllowMultipleDefaultParametersWithSameName = true,
AutomaticDecompression = System.Net.DecompressionMethods.All,
PreAuthenticate = false,
Encoding = Encoding.UTF8,
MaxTimeout = conf["request_timeout_ms"].GetInt32(),
UserAgent = "Essentials.EmailRegistation",
FollowRedirects = false,
BaseUrl = baseServerPath
};
//Init Oauth authenticator
OAuth2Authenticator authenticator = new(oAuth2ClientOptions, lazyCredentialGet, authEndpoint);
//Store pool
RestClientPool = new(maxClients, poolOptions, authenticator:authenticator);
void Cleanup()
{
authenticator.Dispose();
RestClientPool.Dispose();
}
//register password cleanup
_ = pbase.UnloadToken.RegisterUnobserved(Cleanup);
}
///
/// A shared for renting configuraed
///
///
public RestClientPool RestClientPool { get; }
///
/// A global from email address name
///
public string EmailFromName { get; }
///
/// A global from email address
///
public string EmailFromAddress { get; }
///
/// Prepares a new registration email transaction request
///
/// The prepared object
public EmailTransactionRequest GetRegistrationMessage()
{
EmailTransactionRequest req = GetTemplateRequest(REG_TEMPLATE_NAME);
req.FromAddress = EmailFromAddress;
req.FromName = EmailFromName;
//set reg subject
req.Subject = "One more step to register";
return req;
}
}
}