Refactored Mailer out of backend into lib.

This commit is contained in:
Kim 2023-09-15 16:30:41 +02:00
parent 875d00d8a9
commit 13a2f22e36
11 changed files with 133 additions and 92 deletions

View File

@ -9,7 +9,6 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Flurl.Http" Version="3.2.4" /> <PackageReference Include="Flurl.Http" Version="3.2.4" />
<PackageReference Include="Hellang.Middleware.ProblemDetails" Version="6.5.1" /> <PackageReference Include="Hellang.Middleware.ProblemDetails" Version="6.5.1" />
<PackageReference Include="MailKit" Version="3.6.0" />
<PackageReference Include="Microsoft.AspNet.Identity.Core" Version="2.2.3" /> <PackageReference Include="Microsoft.AspNet.Identity.Core" Version="2.2.3" />
<PackageReference Include="Microsoft.AspNet.Identity.Owin" Version="2.2.3" /> <PackageReference Include="Microsoft.AspNet.Identity.Owin" Version="2.2.3" />
<PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.9" /> <PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.9" />
@ -34,6 +33,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="../../Lib/Utils/Utils.csproj" /> <ProjectReference Include="../../Lib/Utils/Utils.csproj" />
<ProjectReference Include="../../Lib/Mailer/Mailer.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -442,7 +442,7 @@ public class Controller : ControllerBase
: Unauthorized(); : Unauthorized();
} }
[HttpGet(nameof(ResetPasswordRequest))] [HttpPost(nameof(ResetPasswordRequest))]
public ActionResult<IEnumerable<Object>> ResetPasswordRequest(String username) public ActionResult<IEnumerable<Object>> ResetPasswordRequest(String username)
{ {
var user = Db.GetUserByEmail(username); var user = Db.GetUserByEmail(username);
@ -457,7 +457,7 @@ public class Controller : ControllerBase
: Unauthorized(); : Unauthorized();
} }
[HttpPost(nameof(ResetPassword))] [HttpGet(nameof(ResetPassword))]
public ActionResult<IEnumerable<Object>> ResetPassword(Token authToken) public ActionResult<IEnumerable<Object>> ResetPassword(Token authToken)
{ {
var user = Db.GetSession(authToken)?.User; var user = Db.GetSession(authToken)?.User;

View File

@ -1,14 +1,10 @@
using System.Data.SQLite;
using System.Reactive.Concurrency; using System.Reactive.Concurrency;
using System.Reactive.Linq; using System.Reactive.Linq;
using System.Runtime.InteropServices;
using CliWrap; using CliWrap;
using CliWrap.Buffered; using CliWrap.Buffered;
using InnovEnergy.App.Backend.DataTypes; using InnovEnergy.App.Backend.DataTypes;
using InnovEnergy.App.Backend.DataTypes.Methods; using InnovEnergy.App.Backend.DataTypes.Methods;
using InnovEnergy.App.Backend.Relations; using InnovEnergy.App.Backend.Relations;
using InnovEnergy.Lib.Utils;
using Microsoft.Identity.Client;
using SQLite; using SQLite;
using SQLiteConnection = SQLite.SQLiteConnection; using SQLiteConnection = SQLite.SQLiteConnection;
@ -170,7 +166,7 @@ public static partial class Db
public static Boolean SendPasswordResetEmail(User user, String sessionToken) public static Boolean SendPasswordResetEmail(User user, String sessionToken)
{ {
return Mailer.Mailer.SendPasswordResetMessage(user, sessionToken); return Email.Email.SendPasswordResetMessage(user, sessionToken);
} }
public static Boolean DeleteUserPassword(User user) public static Boolean DeleteUserPassword(User user)

View File

@ -0,0 +1,54 @@
using System.Diagnostics.CodeAnalysis;
using InnovEnergy.App.Backend.DataTypes;
using InnovEnergy.Lib.Mailer;
using MimeKit;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace InnovEnergy.App.Backend.Email;
public static class Email
{
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "<Pending>")]
public static Boolean SendVerificationMessage(User emailRecipientUser)
{
var config = JsonSerializer.Deserialize<SmtpConfig>(File.OpenRead("./Resources/smtpConfig.json"))!;
var mailer = new Mailer();
Mailer.From("InnovEnergy", "noreply@innov.energy");
Mailer.To(emailRecipientUser.Name, emailRecipientUser.Email);
Mailer.Subject("Create a new password for your Innovenergy-Account");
Mailer.Body("Dear " + emailRecipientUser.Name +
"\n Please create a new password for your Innovenergy-account." +
"\n To do this just login at https://HEEEEELP");
return Mailer.SendEmailUsingSmtpConfig(config);
}
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "<Pending>")]
public static Boolean SendPasswordResetMessage (User emailRecipientUser, String token)
{
var config = JsonSerializer.Deserialize<SmtpConfig>(File.OpenRead("./Resources/smtpConfig.json"))!;
//todo am I right?
const String resetLink = "https://monitor.innov.energy/api/resetPassword";
try
{
Mailer.From("InnovEnergy", "noreply@innov.energy");
Mailer.To(emailRecipientUser.Name, emailRecipientUser.Email);
Mailer.Subject("Reset the password of your Innovenergy-Account");
Mailer.Body("Dear " + emailRecipientUser.Name
+ "\n To reset your password open this link:"
+ resetLink + "/"
+ token);
return Mailer.SendEmailUsingSmtpConfig(config);
}
catch (Exception)
{
return false;
}
}
}

View File

@ -1,80 +0,0 @@
using System.Diagnostics.CodeAnalysis;
using InnovEnergy.App.Backend.DataTypes;
using MailKit.Net.Smtp;
using MimeKit;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace InnovEnergy.App.Backend.Mailer;
public static class Mailer
{
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "<Pending>")]
public static Boolean SendVerificationMessage (User emailRecipientUser)
{
var config = JsonSerializer.Deserialize<SmptConfig>(File.OpenRead("./Resources/smtpConfig.json"))!;
var email = new MimeMessage();
try
{
email.From.Add(new MailboxAddress("InnovEnergy", "noreply@innov.energy"));
email.To.Add(new MailboxAddress(emailRecipientUser.Name, emailRecipientUser.Email));
email.Subject = "Create a new password for your Innovenergy-Account";
email.Body = new TextPart(MimeKit.Text.TextFormat.Plain) {
Text = "Dear " + emailRecipientUser.Name + "\n Please create a new password for your Innovenergy-account." +
"\n To do this just login at https://HEEEEELP"
};
using var smtp = new SmtpClient();
smtp.Connect(config.Url, config.Port, false);
smtp.Authenticate(config.Username, config.Password);
smtp.Send(email);
smtp.Disconnect(true);
}
catch (Exception)
{
return false;
}
return true;
}
public static Boolean SendPasswordResetMessage (User emailRecipientUser, String token)
{
var config = JsonSerializer.Deserialize<SmptConfig>(File.OpenRead("./Resources/smtpConfig.json"))!;
var email = new MimeMessage();
//todo am I right?
const String resetLink = "https://monitor.innov.energy/api/sresetPassword";
try
{
email.From.Add(new MailboxAddress("InnovEnergy", "noreply@innov.energy"));
email.To.Add(new MailboxAddress(emailRecipientUser.Name, emailRecipientUser.Email));
email.Subject = "Reset the password of your Innovenergy-Account";
email.Body = new TextPart(MimeKit.Text.TextFormat.Plain) {
Text = "Dear " + emailRecipientUser.Name
+ "\n To reset your password open this link:"
+ resetLink + "/"
+ token
};
using var smtp = new SmtpClient();
smtp.Connect(config.Url, config.Port, false);
smtp.Authenticate(config.Username, config.Password);
smtp.Send(email);
smtp.Disconnect(true);
}
catch (Exception)
{
return false;
}
return true;
}
}

View File

@ -188,7 +188,7 @@ th { /* header cell */
await SendNewBatteryFirmware(installationIp); await SendNewBatteryFirmware(installationIp);
var batteryTtyName = split[1].Split(".").Last(); var batteryTtyName = split[1].Split(".").Last();
var localCommand = $"/opt/innovenergy/scripts/upload-bms-firmware {batteryTtyName} 2 /opt/innovenergy/{FirmwareVersion}.bin"; var localCommand = $"/opt/innovenergy/scripts/upload-bms-firmware {batteryTtyName} 2 /opt/innovenergy/bms-firmware/{FirmwareVersion}.bin";
var installation = Db.Installations.First(installation => installation.Ip == installationIp); var installation = Db.Installations.First(installation => installation.Ip == installationIp);
installation.BatteryUpdateStatus = "Running"; installation.BatteryUpdateStatus = "Running";
Db.Update(installation: installation); Db.Update(installation: installation);

Binary file not shown.

View File

@ -81,6 +81,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "S3Explorer", "App\S3Explore
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VrmGrabber", "App\VrmGrabber\VrmGrabber.csproj", "{88633C71-D701-49B3-A6DE-9D7CED9046E3}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VrmGrabber", "App\VrmGrabber\VrmGrabber.csproj", "{88633C71-D701-49B3-A6DE-9D7CED9046E3}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mailer", "Lib\Mailer\Mailer.csproj", "{73B97F6E-2BDC-40DA-84A7-7FB0264387D6}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -208,6 +210,10 @@ Global
{88633C71-D701-49B3-A6DE-9D7CED9046E3}.Debug|Any CPU.Build.0 = Debug|Any CPU {88633C71-D701-49B3-A6DE-9D7CED9046E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{88633C71-D701-49B3-A6DE-9D7CED9046E3}.Release|Any CPU.ActiveCfg = Release|Any CPU {88633C71-D701-49B3-A6DE-9D7CED9046E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{88633C71-D701-49B3-A6DE-9D7CED9046E3}.Release|Any CPU.Build.0 = Release|Any CPU {88633C71-D701-49B3-A6DE-9D7CED9046E3}.Release|Any CPU.Build.0 = Release|Any CPU
{73B97F6E-2BDC-40DA-84A7-7FB0264387D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{73B97F6E-2BDC-40DA-84A7-7FB0264387D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{73B97F6E-2BDC-40DA-84A7-7FB0264387D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{73B97F6E-2BDC-40DA-84A7-7FB0264387D6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution GlobalSection(NestedProjects) = preSolution
{CF4834CB-91B7-4172-AC13-ECDA8613CD17} = {145597B4-3E30-45E6-9F72-4DD43194539A} {CF4834CB-91B7-4172-AC13-ECDA8613CD17} = {145597B4-3E30-45E6-9F72-4DD43194539A}
@ -244,5 +250,6 @@ Global
{1391165D-51F1-45B4-8B7F-042A20AA0277} = {4931A385-24DC-4E78-BFF4-356F8D6D5183} {1391165D-51F1-45B4-8B7F-042A20AA0277} = {4931A385-24DC-4E78-BFF4-356F8D6D5183}
{EB56EF94-D8A7-4111-A8E7-A87EF13596DA} = {145597B4-3E30-45E6-9F72-4DD43194539A} {EB56EF94-D8A7-4111-A8E7-A87EF13596DA} = {145597B4-3E30-45E6-9F72-4DD43194539A}
{88633C71-D701-49B3-A6DE-9D7CED9046E3} = {145597B4-3E30-45E6-9F72-4DD43194539A} {88633C71-D701-49B3-A6DE-9D7CED9046E3} = {145597B4-3E30-45E6-9F72-4DD43194539A}
{73B97F6E-2BDC-40DA-84A7-7FB0264387D6} = {AD5B98A8-AB7F-4DA2-B66D-5B4E63E7D854}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View File

@ -0,0 +1,55 @@
using MailKit.Net.Smtp;
using MimeKit;
namespace InnovEnergy.Lib.Mailer;
public class Mailer
{
private static MimeMessage Email = new();
public static MimeMessage To(String name, String emailAddress)
{
Email.To.Add(new MailboxAddress(name, emailAddress));
return Email;
}
public static MimeMessage From(String name, String emailAddress)
{
Email.From.Add(new MailboxAddress(name, emailAddress));
return Email;
}
public static MimeMessage Subject(String subjectText)
{
Email.Subject = subjectText;
return Email;
}
public static MimeMessage Body(String bodyText)
{
Email.Body = new TextPart(MimeKit.Text.TextFormat.Plain)
{
Text = bodyText
};
return Email;
}
public static Boolean SendEmailUsingSmtpConfig(SmtpConfig config)
{
try{
using var smtp = new SmtpClient();
smtp.Connect(config.Url, config.Port, false);
smtp.Authenticate(config.Username, config.Password);
smtp.Send(Email);
smtp.Disconnect(true);
}
catch (Exception)
{
return false;
}
return true;
}
}

View File

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="../InnovEnergy.Lib.props" />
<PropertyGroup>
<RootNamespace>InnovEnergy.Lib.Mailer</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MailKit" Version="4.2.0" />
</ItemGroup>
</Project>

View File

@ -1,13 +1,12 @@
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
namespace InnovEnergy.Lib.Mailer;
namespace InnovEnergy.App.Backend.Mailer;
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")] [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
public class SmptConfig public class SmtpConfig
{ {
public String Url { get; init; } = null!; public String Url { get; init; } = null!;
public String Username { get; init; } = null!; public String Username { get; init; } = null!;
public String Password { get; init; } = null!; public String Password { get; init; } = null!;
public Int32 Port { get; init; } = 587; public Int32 Port { get; init; } = 587;
} }