Skip to content

Commit

Permalink
removed references to the appsettings.secrets.json file, refactored S…
Browse files Browse the repository at this point in the history
…mtpEmailSender
  • Loading branch information
suxrobGM committed Jan 27, 2024
1 parent fefe49b commit 8842e81
Show file tree
Hide file tree
Showing 21 changed files with 117 additions and 170 deletions.
15 changes: 8 additions & 7 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,21 @@
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

# Exclude production appsettings file
appsettings.Production.json

.idea/
.config/
.VSCodeCounter/
firebase-adminsdk-key.json

# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates

.idea/
.config/
.VSCodeCounter/
secrets.json
*.secrets.json
firebase-adminsdk-key.json

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

Expand Down
6 changes: 0 additions & 6 deletions src/Client/Logistics.AdminApp/Logistics.AdminApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,4 @@
<ItemGroup>
<ProjectReference Include="..\Logistics.Client\Logistics.Client.csproj" />
</ItemGroup>

<ItemGroup>
<Content Update="wwwroot\appsettings.secrets.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
1 change: 0 additions & 1 deletion src/Client/Logistics.DriverApp/Logistics.DriverApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@

<ItemGroup>
<EmbeddedResource Include="appsettings.json" />
<EmbeddedResource Include="appsettings.secrets.json" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net8.0-android'">
Expand Down
3 changes: 0 additions & 3 deletions src/Client/Logistics.DriverApp/Setup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,6 @@ private static IConfiguration BuildConfiguration(this MauiAppBuilder builder)
{
var configuration = builder.Configuration
.AddJsonConfig("appsettings.json")
#if !DEBUG
.AddJsonConfig("appsettings.secrets.json")
#endif
.Build();

return configuration;
Expand Down

This file was deleted.

14 changes: 7 additions & 7 deletions src/Core/Logistics.Application.Core/Registrar.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using Logistics.Application.Core.Behaviours;
using Logistics.Application.Core.Options;
using Logistics.Application.Core.Services;
using Logistics.Application.Core.Services.Implementations;
using MediatR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -12,20 +12,20 @@ public static class Registrar
public static IServiceCollection AddApplicationCoreLayer(
this IServiceCollection services,
IConfiguration configuration,
string emailConfigSection = "Email",
string captchaConfigSection = "Captcha")
string emailConfigSection = "SmtpConfig",
string captchaConfigSection = "GoogleRecaptchaConfig")
{

var emailSenderOptions = configuration.GetSection(emailConfigSection).Get<EmailSenderOptions>();
var emailSenderOptions = configuration.GetSection(emailConfigSection).Get<SmtpOptions>();
var googleRecaptchaOptions = configuration.GetSection(captchaConfigSection).Get<GoogleRecaptchaOptions>();

if (emailSenderOptions != null)
if (emailSenderOptions is not null)
{
services.AddSingleton(emailSenderOptions);
services.AddTransient<IEmailSender, EmailSender>();
services.AddTransient<IEmailSender, SmtpEmailSender>();
}

if (googleRecaptchaOptions != null)
if (googleRecaptchaOptions is not null)
{
services.AddSingleton(googleRecaptchaOptions);
services.AddScoped<ICaptchaService, GoogleRecaptchaService>();
Expand Down
84 changes: 0 additions & 84 deletions src/Core/Logistics.Application.Core/Services/EmailSender.cs

This file was deleted.

6 changes: 3 additions & 3 deletions src/Core/Logistics.Application.Core/Services/IEmailSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ public interface IEmailSender
/// <summary>
/// Sends mail to specified address.
/// </summary>
/// <param name="receiverMail">Receiver email address</param>
/// <param name="recipient">Receiver email address</param>
/// <param name="subject">Mail subject</param>
/// <param name="htmlBody">Mail html body</param>
/// <returns>True if mail has been sent successfully, otherwise false</returns>
Task<bool> SendMailAsync(string receiverMail, string subject, string htmlBody);
}
Task<bool> SendEmailAsync(string recipient, string subject, string htmlBody);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Logistics.Application.Core.Services.Implementations;

internal class GoogleRecaptchaOptions
{
public string? SiteKey { get; set; }
public string? SecretKey { get; set; }
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Net.Http.Json;
using Logistics.Application.Core.Options;

namespace Logistics.Application.Core.Services;
namespace Logistics.Application.Core.Services.Implementations;

internal sealed class GoogleRecaptchaService : ICaptchaService
{
Expand Down Expand Up @@ -39,4 +38,4 @@ internal record GoogleRecaptchaResponse
public float Score { get; init; }
public string? Action { get; init; }
public string? HostName { get; init; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System.Net;
using System.Net.Mail;
using Microsoft.Extensions.Logging;

namespace Logistics.Application.Core.Services.Implementations;

internal sealed class SmtpEmailSender : IEmailSender
{
private readonly SmtpOptions _options;
private readonly ILogger<SmtpEmailSender> _logger;

public SmtpEmailSender(
SmtpOptions options,
ILogger<SmtpEmailSender> logger)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));

ArgumentException.ThrowIfNullOrEmpty(options.SenderName);
ArgumentException.ThrowIfNullOrEmpty(options.SenderEmail);
ArgumentException.ThrowIfNullOrEmpty(options.Host);
ArgumentException.ThrowIfNullOrEmpty(options.UserName);
ArgumentException.ThrowIfNullOrEmpty(options.Password);
}

public async Task<bool> SendEmailAsync(string recipient, string subject, string htmlBody)
{
ArgumentException.ThrowIfNullOrEmpty(recipient);
ArgumentException.ThrowIfNullOrEmpty(subject);
ArgumentException.ThrowIfNullOrEmpty(htmlBody);

try
{
var from = new MailAddress(_options.SenderEmail!, _options.SenderName);
using var mailMessage = new MailMessage(from, new MailAddress(recipient));
mailMessage.Subject = subject;
mailMessage.Body = htmlBody;
mailMessage.IsBodyHtml = true;
mailMessage.Priority = MailPriority.High;
mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.Delay |
DeliveryNotificationOptions.OnFailure |
DeliveryNotificationOptions.OnSuccess;

using var smtpClient = new SmtpClient(_options.Host, _options.Port);
smtpClient.Port = _options.Port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Host = _options.Host!;
smtpClient.EnableSsl = true;
smtpClient.Timeout = 5000;
smtpClient.Credentials = new NetworkCredential(_options.UserName, _options.Password);

await smtpClient.SendMailAsync(mailMessage);
_logger.LogInformation("Email has been sent to {Mail}, subject: \'{Subject}\'", recipient, subject);
return true;
}
catch (Exception ex)
{
_logger.LogWarning(
"Could not send email to {Mail}, subject: \'{Subject}\'. \nThrown exception: {Exception}",
recipient, subject, ex.ToString());
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
namespace Logistics.Application.Core.Options;
namespace Logistics.Application.Core.Services.Implementations;

public class EmailSenderOptions
internal class SmtpOptions
{
public string? SenderMail { get; set; }
public string? SenderEmail { get; set; }
public string? SenderName { get; set; }
public string? UserName { get; set; }
public string? Password { get; set; }
Expand Down
5 changes: 0 additions & 5 deletions src/Core/Logistics.DbMigrator/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,7 @@
var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(configuration =>
{
var secretsFile = Path.Combine(AppContext.BaseDirectory, "appsettings.secrets.json");
var testDataFile = Path.Combine(AppContext.BaseDirectory, "fakeDataset.json");
#if !DEBUG
configuration.AddJsonFile(secretsFile, true);
#endif
configuration.AddJsonFile(testDataFile, true);
})
.ConfigureServices((ctx, services) =>
Expand Down
11 changes: 1 addition & 10 deletions src/Server/Logistics.API/Setup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ internal static class Setup
public static WebApplication ConfigureServices(this WebApplicationBuilder builder)
{
var services = builder.Services;
#if !DEBUG
AddSecretsJson(builder.Configuration);
#endif
services.AddApplicationCoreLayer(builder.Configuration, "EmailConfig");
services.AddApplicationCoreLayer(builder.Configuration);
services.AddAdminApplicationLayer();
services.AddTenantApplicationLayer();
services.AddInfrastructureLayer(builder.Configuration);
Expand Down Expand Up @@ -128,12 +125,6 @@ public static WebApplication ScheduleJobs(this WebApplication app)
return app;
}

private static void AddSecretsJson(IConfigurationBuilder configuration)
{
var path = Path.Combine(AppContext.BaseDirectory, "appsettings.secrets.json");
configuration.AddJsonFile(path, true);
}

private static string GetModelStateErrors(ModelStateDictionary modelState)
{
var errors = new StringBuilder();
Expand Down
10 changes: 5 additions & 5 deletions src/Server/Logistics.API/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@
"Authority": "https://localhost:7001",
"Audience": "logistics.api"
},
"EmailConfig": {
"SenderMail": "account email",
"SmtpConfig": {
"SenderEmail": "<Email address>",
"SenderName": "Logistics NoReply",
"UserName": "email account username",
"Password": "Paste email account password",
"Host": "Email host address",
"UserName": "<Email account username>",
"Password": "<Email account password>",
"Host": "<Server address>",
"Port": 587
},
"TenantsDatabaseConfig": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public async Task<IActionResult> OnPostAsync()
new { area = "Identity", code },
Request.Scheme);

await _emailSenderService.SendMailAsync(
await _emailSenderService.SendEmailAsync(
Input.Email,
"Reset Password",
$"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public async Task<IActionResult> OnPostChangeEmailAsync()
pageHandler: null,
values: new { userId = userId, email = Input.NewEmail, code = code },
protocol: Request.Scheme);
await _emailSender.SendMailAsync(
await _emailSender.SendEmailAsync(
Input.NewEmail,
"Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
Expand Down Expand Up @@ -119,7 +119,7 @@ public async Task<IActionResult> OnPostSendVerificationEmailAsync()
pageHandler: null,
values: new { area = "Identity", userId = userId, code = code },
protocol: Request.Scheme);
await _emailSender.SendMailAsync(
await _emailSender.SendEmailAsync(
email,
"Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
Expand Down
Loading

0 comments on commit 8842e81

Please sign in to comment.